@ottocode/web-ui 0.1.175 → 0.1.177

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.
@@ -1,4 +1,4 @@
1
- import{r as u,j as t,R as aA,e as Ko}from"./react-C7bPzU82.js";import{u as PA,a as nA,b as pA,_ as So,c as Ro,O as Lo,d as mg,r as qo,e as Oo,f as Yo,Q as To,g as vo,R as jo}from"./router-BJqKFLBP.js";import{T as fe,B as Ho,U as xg,A as jQ,X as MA,P as Je,C as fA,a as Be,E as SA,L as uA,b as fg,c as HQ,d as _e,F as le,e as Po,f as Wo,I as PQ,g as Ft,h as zo,i as WQ,j as gg,S as Ke,k as zQ,K as VQ,l as Vo,m as Ng,G as HA,n as XA,M as Zo,o as Xo,p as kg,q as Mg,R as TA,r as Zg,s as Ze,t as _o,u as ZQ,v as ZA,w as $e,x as XQ,y as Xe,z as $o,D as As,H as _Q,J as es,N as $Q,O as ts,Q as gs,V as Qs,W as Xg,Y as Bs,Z as os,_ as ss,$ as Ne,a0 as Es,a1 as _g,a2 as mt,a3 as Cs,a4 as is,a5 as AB,a6 as eB,a7 as tB,a8 as gB,a9 as QB,aa as yg,ab as as,ac as BB,ad as rs,ae as oB,af as Is,ag as ns,ah as ls,ai as cs,aj as ds,ak as sB,al as us,am as hs,an as Ds,ao as $g,ap as ws,aq as ps,ar as ms,as as xs}from"./icons-CauB6tyl.js";import{v as ae,p as re,h as jA}from"./syntax-COWumqTl.js";import{M as EB,a as CB}from"./markdown-DZTI3WvM.js";(function(){const A=document.createElement("link").relList;if(A&&A.supports&&A.supports("modulepreload"))return;for(const B of document.querySelectorAll('link[rel="modulepreload"]'))Q(B);new MutationObserver(B=>{for(const o of B)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&Q(s)}).observe(document,{childList:!0,subtree:!0});function g(B){const o={};return B.integrity&&(o.integrity=B.integrity),B.referrerPolicy&&(o.referrerPolicy=B.referrerPolicy),B.crossOrigin==="use-credentials"?o.credentials="include":B.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function Q(B){if(B.ep)return;B.ep=!0;const o=g(B);fetch(B.href,o)}})();const QA=u.forwardRef(({className:e="",variant:A="primary",size:g="md",...Q},B)=>{const o="inline-flex items-center justify-center rounded font-medium transition-colors focus-visible:outline-none disabled:opacity-50 disabled:cursor-not-allowed",s={primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-muted text-foreground hover:bg-muted/80 border border-border",ghost:"text-muted-foreground hover:text-foreground hover:bg-muted/50"},E={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base",icon:"w-10 h-10 p-0"};return t.jsx("button",{ref:B,className:`${o} ${s[A]} ${E[g]} ${e}`,...Q})});QA.displayName="Button";const AQ=e=>{let A;const g=new Set,Q=(C,a)=>{const I=typeof C=="function"?C(A):C;if(!Object.is(I,A)){const l=A;A=a??(typeof I!="object"||I===null)?I:Object.assign({},A,I),g.forEach(r=>r(A,l))}},B=()=>A,E={setState:Q,getState:B,getInitialState:()=>i,subscribe:C=>(g.add(C),()=>g.delete(C))},i=A=e(Q,B,E);return E},fs=(e=>e?AQ(e):AQ),Ns=e=>e;function ks(e,A=Ns){const g=aA.useSyncExternalStore(e.subscribe,aA.useCallback(()=>A(e.getState()),[e,A]),aA.useCallback(()=>A(e.getInitialState()),[e,A]));return aA.useDebugValue(g),g}const eQ=e=>{const A=fs(e),g=Q=>ks(A,Q);return Object.assign(g,A),g},UA=(e=>e?eQ(e):eQ),Qe=UA(e=>({isExpanded:!1,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(CA.getState().collapseSidebar(),wA.getState().collapseSidebar(),vA.getState().collapseSidebar(),bA.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>e({isExpanded:!0}),collapseSidebar:()=>e({isExpanded:!1})})),vA=UA((e,A)=>({isExpanded:!1,activeResearchSessionId:null,parentSessionId:null,toggleSidebar:()=>{e(g=>{const Q=!g.isExpanded;return Q&&(CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),wA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:Q}})},expandSidebar:()=>{CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),wA.getState().collapseSidebar(),Qe.getState().collapseSidebar(),e({isExpanded:!0})},collapseSidebar:()=>e({isExpanded:!1}),selectResearchSession:g=>e({activeResearchSessionId:g}),setParentSessionId:g=>{A().parentSessionId!==g&&e({parentSessionId:g,activeResearchSessionId:null})},reset:()=>e({activeResearchSessionId:null,parentSessionId:null})})),wA=UA(e=>({isExpanded:!1,selectedFile:null,allOperations:[],selectedOperationIndex:0,isDiffOpen:!1,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>{CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar(),e({isExpanded:!0})},collapseSidebar:()=>e({isExpanded:!1,isDiffOpen:!1,selectedFile:null,allOperations:[],selectedOperationIndex:0}),openDiff:(A,g)=>e({selectedFile:A,allOperations:g,selectedOperationIndex:g.length-1,isDiffOpen:!0,isExpanded:!0}),selectOperation:A=>e({selectedOperationIndex:A}),closeDiff:()=>e({isDiffOpen:!1,selectedFile:null,allOperations:[],selectedOperationIndex:0})})),CA=UA(e=>({isExpanded:!1,activeSessionId:null,selectedFile:null,selectedFileStaged:!1,isDiffOpen:!1,isCommitModalOpen:!1,commitSessionId:null,wasSessionListCollapsed:!1,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(bA.getState().collapseSidebar(),wA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>e({isExpanded:!0}),collapseSidebar:()=>e({isExpanded:!1,isDiffOpen:!1,selectedFile:null}),openDiff:(A,g)=>e({selectedFile:A,selectedFileStaged:g,isDiffOpen:!0,isExpanded:!0}),closeDiff:()=>e({isDiffOpen:!1,selectedFile:null}),switchFile:(A,g)=>e({selectedFile:A,selectedFileStaged:g}),openCommitModal:()=>e(A=>({isCommitModalOpen:!0,commitSessionId:A.activeSessionId})),openCommitModalForSession:A=>e({isCommitModalOpen:!0,commitSessionId:A}),closeCommitModal:()=>e({isCommitModalOpen:!1,commitSessionId:null}),setActiveSessionId:A=>e({activeSessionId:A}),setSessionListCollapsed:A=>e({wasSessionListCollapsed:A})})),bA=UA(e=>({isExpanded:!1,selectedTerminalId:null,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(CA.getState().collapseSidebar(),wA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>e({isExpanded:!0}),collapseSidebar:()=>e({isExpanded:!1,selectedTerminalId:null}),selectTerminal:A=>e({selectedTerminalId:A})}));var tQ;(function(e){e.OPENAI="openai",e.ANTHROPIC="anthropic",e.GOOGLE="google",e.OPENROUTER="openrouter",e.OPENCODE="opencode",e.ZAI="zai",e.ZAI_CODING="zai-coding",e.MOONSHOT="moonshot",e.COPILOT="copilot",e.SETU="setu"})(tQ||(tQ={}));function iB(e,A){return function(){return e.apply(A,arguments)}}const{toString:Ms}=Object.prototype,{getPrototypeOf:Gg}=Object,{iterator:bt,toStringTag:aB}=Symbol,Ut=(e=>A=>{const g=Ms.call(A);return e[g]||(e[g]=g.slice(8,-1).toLowerCase())})(Object.create(null)),Ae=e=>(e=e.toLowerCase(),A=>Ut(A)===e),Jt=e=>A=>typeof A===e,{isArray:Le}=Array,Se=Jt("undefined");function At(e){return e!==null&&!Se(e)&&e.constructor!==null&&!Se(e.constructor)&&RA(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const rB=Ae("ArrayBuffer");function ys(e){let A;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?A=ArrayBuffer.isView(e):A=e&&e.buffer&&rB(e.buffer),A}const Gs=Jt("string"),RA=Jt("function"),IB=Jt("number"),et=e=>e!==null&&typeof e=="object",Fs=e=>e===!0||e===!1,nt=e=>{if(Ut(e)!=="object")return!1;const A=Gg(e);return(A===null||A===Object.prototype||Object.getPrototypeOf(A)===null)&&!(aB in e)&&!(bt in e)},bs=e=>{if(!et(e)||At(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Us=Ae("Date"),Js=Ae("File"),Ks=Ae("Blob"),Ss=Ae("FileList"),Rs=e=>et(e)&&RA(e.pipe),Ls=e=>{let A;return e&&(typeof FormData=="function"&&e instanceof FormData||RA(e.append)&&((A=Ut(e))==="formdata"||A==="object"&&RA(e.toString)&&e.toString()==="[object FormData]"))},qs=Ae("URLSearchParams"),[Os,Ys,Ts,vs]=["ReadableStream","Request","Response","Headers"].map(Ae),js=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tt(e,A,{allOwnKeys:g=!1}={}){if(e===null||typeof e>"u")return;let Q,B;if(typeof e!="object"&&(e=[e]),Le(e))for(Q=0,B=e.length;Q<B;Q++)A.call(null,e[Q],Q,e);else{if(At(e))return;const o=g?Object.getOwnPropertyNames(e):Object.keys(e),s=o.length;let E;for(Q=0;Q<s;Q++)E=o[Q],A.call(null,e[E],E,e)}}function nB(e,A){if(At(e))return null;A=A.toLowerCase();const g=Object.keys(e);let Q=g.length,B;for(;Q-- >0;)if(B=g[Q],A===B.toLowerCase())return B;return null}const me=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,lB=e=>!Se(e)&&e!==me;function Qg(){const{caseless:e,skipUndefined:A}=lB(this)&&this||{},g={},Q=(B,o)=>{const s=e&&nB(g,o)||o;nt(g[s])&&nt(B)?g[s]=Qg(g[s],B):nt(B)?g[s]=Qg({},B):Le(B)?g[s]=B.slice():(!A||!Se(B))&&(g[s]=B)};for(let B=0,o=arguments.length;B<o;B++)arguments[B]&&tt(arguments[B],Q);return g}const Hs=(e,A,g,{allOwnKeys:Q}={})=>(tt(A,(B,o)=>{g&&RA(B)?Object.defineProperty(e,o,{value:iB(B,g),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,o,{value:B,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:Q}),e),Ps=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Ws=(e,A,g,Q)=>{e.prototype=Object.create(A.prototype,Q),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:A.prototype}),g&&Object.assign(e.prototype,g)},zs=(e,A,g,Q)=>{let B,o,s;const E={};if(A=A||{},e==null)return A;do{for(B=Object.getOwnPropertyNames(e),o=B.length;o-- >0;)s=B[o],(!Q||Q(s,e,A))&&!E[s]&&(A[s]=e[s],E[s]=!0);e=g!==!1&&Gg(e)}while(e&&(!g||g(e,A))&&e!==Object.prototype);return A},Vs=(e,A,g)=>{e=String(e),(g===void 0||g>e.length)&&(g=e.length),g-=A.length;const Q=e.indexOf(A,g);return Q!==-1&&Q===g},Zs=e=>{if(!e)return null;if(Le(e))return e;let A=e.length;if(!IB(A))return null;const g=new Array(A);for(;A-- >0;)g[A]=e[A];return g},Xs=(e=>A=>e&&A instanceof e)(typeof Uint8Array<"u"&&Gg(Uint8Array)),_s=(e,A)=>{const Q=(e&&e[bt]).call(e);let B;for(;(B=Q.next())&&!B.done;){const o=B.value;A.call(e,o[0],o[1])}},$s=(e,A)=>{let g;const Q=[];for(;(g=e.exec(A))!==null;)Q.push(g);return Q},AE=Ae("HTMLFormElement"),eE=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(g,Q,B){return Q.toUpperCase()+B}),gQ=(({hasOwnProperty:e})=>(A,g)=>e.call(A,g))(Object.prototype),tE=Ae("RegExp"),cB=(e,A)=>{const g=Object.getOwnPropertyDescriptors(e),Q={};tt(g,(B,o)=>{let s;(s=A(B,o,e))!==!1&&(Q[o]=s||B)}),Object.defineProperties(e,Q)},gE=e=>{cB(e,(A,g)=>{if(RA(e)&&["arguments","caller","callee"].indexOf(g)!==-1)return!1;const Q=e[g];if(RA(Q)){if(A.enumerable=!1,"writable"in A){A.writable=!1;return}A.set||(A.set=()=>{throw Error("Can not rewrite read-only method '"+g+"'")})}})},QE=(e,A)=>{const g={},Q=B=>{B.forEach(o=>{g[o]=!0})};return Le(e)?Q(e):Q(String(e).split(A)),g},BE=()=>{},oE=(e,A)=>e!=null&&Number.isFinite(e=+e)?e:A;function sE(e){return!!(e&&RA(e.append)&&e[aB]==="FormData"&&e[bt])}const EE=e=>{const A=new Array(10),g=(Q,B)=>{if(et(Q)){if(A.indexOf(Q)>=0)return;if(At(Q))return Q;if(!("toJSON"in Q)){A[B]=Q;const o=Le(Q)?[]:{};return tt(Q,(s,E)=>{const i=g(s,B+1);!Se(i)&&(o[E]=i)}),A[B]=void 0,o}}return Q};return g(e,0)},CE=Ae("AsyncFunction"),iE=e=>e&&(et(e)||RA(e))&&RA(e.then)&&RA(e.catch),dB=((e,A)=>e?setImmediate:A?((g,Q)=>(me.addEventListener("message",({source:B,data:o})=>{B===me&&o===g&&Q.length&&Q.shift()()},!1),B=>{Q.push(B),me.postMessage(g,"*")}))(`axios@${Math.random()}`,[]):g=>setTimeout(g))(typeof setImmediate=="function",RA(me.postMessage)),aE=typeof queueMicrotask<"u"?queueMicrotask.bind(me):typeof process<"u"&&process.nextTick||dB,rE=e=>e!=null&&RA(e[bt]),F={isArray:Le,isArrayBuffer:rB,isBuffer:At,isFormData:Ls,isArrayBufferView:ys,isString:Gs,isNumber:IB,isBoolean:Fs,isObject:et,isPlainObject:nt,isEmptyObject:bs,isReadableStream:Os,isRequest:Ys,isResponse:Ts,isHeaders:vs,isUndefined:Se,isDate:Us,isFile:Js,isBlob:Ks,isRegExp:tE,isFunction:RA,isStream:Rs,isURLSearchParams:qs,isTypedArray:Xs,isFileList:Ss,forEach:tt,merge:Qg,extend:Hs,trim:js,stripBOM:Ps,inherits:Ws,toFlatObject:zs,kindOf:Ut,kindOfTest:Ae,endsWith:Vs,toArray:Zs,forEachEntry:_s,matchAll:$s,isHTMLForm:AE,hasOwnProperty:gQ,hasOwnProp:gQ,reduceDescriptors:cB,freezeMethods:gE,toObjectSet:QE,toCamelCase:eE,noop:BE,toFiniteNumber:oE,findKey:nB,global:me,isContextDefined:lB,isSpecCompliantForm:sE,toJSONObject:EE,isAsyncFn:CE,isThenable:iE,setImmediate:dB,asap:aE,isIterable:rE};let W=class uB extends Error{static from(A,g,Q,B,o,s){const E=new uB(A.message,g||A.code,Q,B,o);return E.cause=A,E.name=A.name,s&&Object.assign(E,s),E}constructor(A,g,Q,B,o){super(A),this.name="AxiosError",this.isAxiosError=!0,g&&(this.code=g),Q&&(this.config=Q),B&&(this.request=B),o&&(this.response=o,this.status=o.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:F.toJSONObject(this.config),code:this.code,status:this.status}}};W.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";W.ERR_BAD_OPTION="ERR_BAD_OPTION";W.ECONNABORTED="ECONNABORTED";W.ETIMEDOUT="ETIMEDOUT";W.ERR_NETWORK="ERR_NETWORK";W.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";W.ERR_DEPRECATED="ERR_DEPRECATED";W.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";W.ERR_BAD_REQUEST="ERR_BAD_REQUEST";W.ERR_CANCELED="ERR_CANCELED";W.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";W.ERR_INVALID_URL="ERR_INVALID_URL";const IE=null;function Bg(e){return F.isPlainObject(e)||F.isArray(e)}function hB(e){return F.endsWith(e,"[]")?e.slice(0,-2):e}function QQ(e,A,g){return e?e.concat(A).map(function(B,o){return B=hB(B),!g&&o?"["+B+"]":B}).join(g?".":""):A}function nE(e){return F.isArray(e)&&!e.some(Bg)}const lE=F.toFlatObject(F,{},null,function(A){return/^is[A-Z]/.test(A)});function Kt(e,A,g){if(!F.isObject(e))throw new TypeError("target must be an object");A=A||new FormData,g=F.toFlatObject(g,{metaTokens:!0,dots:!1,indexes:!1},!1,function(d,c){return!F.isUndefined(c[d])});const Q=g.metaTokens,B=g.visitor||a,o=g.dots,s=g.indexes,i=(g.Blob||typeof Blob<"u"&&Blob)&&F.isSpecCompliantForm(A);if(!F.isFunction(B))throw new TypeError("visitor must be a function");function C(n){if(n===null)return"";if(F.isDate(n))return n.toISOString();if(F.isBoolean(n))return n.toString();if(!i&&F.isBlob(n))throw new W("Blob is not supported. Use a Buffer instead.");return F.isArrayBuffer(n)||F.isTypedArray(n)?i&&typeof Blob=="function"?new Blob([n]):Buffer.from(n):n}function a(n,d,c){let D=n;if(n&&!c&&typeof n=="object"){if(F.endsWith(d,"{}"))d=Q?d:d.slice(0,-2),n=JSON.stringify(n);else if(F.isArray(n)&&nE(n)||(F.isFileList(n)||F.endsWith(d,"[]"))&&(D=F.toArray(n)))return d=hB(d),D.forEach(function(h,m){!(F.isUndefined(h)||h===null)&&A.append(s===!0?QQ([d],m,o):s===null?d:d+"[]",C(h))}),!1}return Bg(n)?!0:(A.append(QQ(c,d,o),C(n)),!1)}const I=[],l=Object.assign(lE,{defaultVisitor:a,convertValue:C,isVisitable:Bg});function r(n,d){if(!F.isUndefined(n)){if(I.indexOf(n)!==-1)throw Error("Circular reference detected in "+d.join("."));I.push(n),F.forEach(n,function(D,N){(!(F.isUndefined(D)||D===null)&&B.call(A,D,F.isString(N)?N.trim():N,d,l))===!0&&r(D,d?d.concat(N):[N])}),I.pop()}}if(!F.isObject(e))throw new TypeError("data must be an object");return r(e),A}function BQ(e){const A={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(Q){return A[Q]})}function Fg(e,A){this._pairs=[],e&&Kt(e,this,A)}const DB=Fg.prototype;DB.append=function(A,g){this._pairs.push([A,g])};DB.toString=function(A){const g=A?function(Q){return A.call(this,Q,BQ)}:BQ;return this._pairs.map(function(B){return g(B[0])+"="+g(B[1])},"").join("&")};function cE(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function wB(e,A,g){if(!A)return e;const Q=g&&g.encode||cE,B=F.isFunction(g)?{serialize:g}:g,o=B&&B.serialize;let s;if(o?s=o(A,B):s=F.isURLSearchParams(A)?A.toString():new Fg(A,B).toString(Q),s){const E=e.indexOf("#");E!==-1&&(e=e.slice(0,E)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class oQ{constructor(){this.handlers=[]}use(A,g,Q){return this.handlers.push({fulfilled:A,rejected:g,synchronous:Q?Q.synchronous:!1,runWhen:Q?Q.runWhen:null}),this.handlers.length-1}eject(A){this.handlers[A]&&(this.handlers[A]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(A){F.forEach(this.handlers,function(Q){Q!==null&&A(Q)})}}const pB={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},dE=typeof URLSearchParams<"u"?URLSearchParams:Fg,uE=typeof FormData<"u"?FormData:null,hE=typeof Blob<"u"?Blob:null,DE={isBrowser:!0,classes:{URLSearchParams:dE,FormData:uE,Blob:hE},protocols:["http","https","file","blob","url","data"]},bg=typeof window<"u"&&typeof document<"u",og=typeof navigator=="object"&&navigator||void 0,wE=bg&&(!og||["ReactNative","NativeScript","NS"].indexOf(og.product)<0),pE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",mE=bg&&window.location.href||"http://localhost",xE=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:bg,hasStandardBrowserEnv:wE,hasStandardBrowserWebWorkerEnv:pE,navigator:og,origin:mE},Symbol.toStringTag,{value:"Module"})),kA={...xE,...DE};function fE(e,A){return Kt(e,new kA.classes.URLSearchParams,{visitor:function(g,Q,B,o){return kA.isNode&&F.isBuffer(g)?(this.append(Q,g.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...A})}function NE(e){return F.matchAll(/\w+|\[(\w*)]/g,e).map(A=>A[0]==="[]"?"":A[1]||A[0])}function kE(e){const A={},g=Object.keys(e);let Q;const B=g.length;let o;for(Q=0;Q<B;Q++)o=g[Q],A[o]=e[o];return A}function mB(e){function A(g,Q,B,o){let s=g[o++];if(s==="__proto__")return!0;const E=Number.isFinite(+s),i=o>=g.length;return s=!s&&F.isArray(B)?B.length:s,i?(F.hasOwnProp(B,s)?B[s]=[B[s],Q]:B[s]=Q,!E):((!B[s]||!F.isObject(B[s]))&&(B[s]=[]),A(g,Q,B[s],o)&&F.isArray(B[s])&&(B[s]=kE(B[s])),!E)}if(F.isFormData(e)&&F.isFunction(e.entries)){const g={};return F.forEachEntry(e,(Q,B)=>{A(NE(Q),B,g,0)}),g}return null}function ME(e,A,g){if(F.isString(e))try{return(A||JSON.parse)(e),F.trim(e)}catch(Q){if(Q.name!=="SyntaxError")throw Q}return(g||JSON.stringify)(e)}const gt={transitional:pB,adapter:["xhr","http","fetch"],transformRequest:[function(A,g){const Q=g.getContentType()||"",B=Q.indexOf("application/json")>-1,o=F.isObject(A);if(o&&F.isHTMLForm(A)&&(A=new FormData(A)),F.isFormData(A))return B?JSON.stringify(mB(A)):A;if(F.isArrayBuffer(A)||F.isBuffer(A)||F.isStream(A)||F.isFile(A)||F.isBlob(A)||F.isReadableStream(A))return A;if(F.isArrayBufferView(A))return A.buffer;if(F.isURLSearchParams(A))return g.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),A.toString();let E;if(o){if(Q.indexOf("application/x-www-form-urlencoded")>-1)return fE(A,this.formSerializer).toString();if((E=F.isFileList(A))||Q.indexOf("multipart/form-data")>-1){const i=this.env&&this.env.FormData;return Kt(E?{"files[]":A}:A,i&&new i,this.formSerializer)}}return o||B?(g.setContentType("application/json",!1),ME(A)):A}],transformResponse:[function(A){const g=this.transitional||gt.transitional,Q=g&&g.forcedJSONParsing,B=this.responseType==="json";if(F.isResponse(A)||F.isReadableStream(A))return A;if(A&&F.isString(A)&&(Q&&!this.responseType||B)){const s=!(g&&g.silentJSONParsing)&&B;try{return JSON.parse(A,this.parseReviver)}catch(E){if(s)throw E.name==="SyntaxError"?W.from(E,W.ERR_BAD_RESPONSE,this,null,this.response):E}}return A}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:kA.classes.FormData,Blob:kA.classes.Blob},validateStatus:function(A){return A>=200&&A<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};F.forEach(["delete","get","head","post","put","patch"],e=>{gt.headers[e]={}});const yE=F.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),GE=e=>{const A={};let g,Q,B;return e&&e.split(`
1
+ import{r as u,j as t,R as aA,e as Ko}from"./react-C7bPzU82.js";import{u as PA,a as nA,b as pA,_ as So,c as Ro,O as Lo,d as mg,r as qo,e as Oo,f as Yo,Q as To,g as vo,R as jo}from"./router-DAZla045.js";import{T as fe,B as Ho,U as xg,A as jQ,X as MA,P as Je,C as fA,a as Be,E as SA,L as uA,b as fg,c as HQ,d as _e,F as le,e as Po,f as Wo,I as PQ,g as Ft,h as zo,i as WQ,j as gg,S as Ke,k as zQ,K as VQ,l as Vo,m as Ng,G as HA,n as XA,M as Zo,o as Xo,p as kg,q as Mg,R as TA,r as Zg,s as Ze,t as _o,u as ZQ,v as ZA,w as $e,x as XQ,y as Xe,z as $o,D as As,H as _Q,J as es,N as $Q,O as ts,Q as gs,V as Qs,W as Xg,Y as Bs,Z as os,_ as ss,$ as Ne,a0 as Es,a1 as _g,a2 as mt,a3 as Cs,a4 as is,a5 as AB,a6 as eB,a7 as tB,a8 as gB,a9 as QB,aa as yg,ab as as,ac as BB,ad as rs,ae as oB,af as Is,ag as ns,ah as ls,ai as cs,aj as ds,ak as sB,al as us,am as hs,an as Ds,ao as $g,ap as ws,aq as ps,ar as ms,as as xs}from"./icons-CauB6tyl.js";import{v as ae,p as re,h as jA}from"./syntax-COWumqTl.js";import{M as EB,a as CB}from"./markdown-DZTI3WvM.js";(function(){const A=document.createElement("link").relList;if(A&&A.supports&&A.supports("modulepreload"))return;for(const B of document.querySelectorAll('link[rel="modulepreload"]'))Q(B);new MutationObserver(B=>{for(const o of B)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&Q(s)}).observe(document,{childList:!0,subtree:!0});function g(B){const o={};return B.integrity&&(o.integrity=B.integrity),B.referrerPolicy&&(o.referrerPolicy=B.referrerPolicy),B.crossOrigin==="use-credentials"?o.credentials="include":B.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function Q(B){if(B.ep)return;B.ep=!0;const o=g(B);fetch(B.href,o)}})();const QA=u.forwardRef(({className:e="",variant:A="primary",size:g="md",...Q},B)=>{const o="inline-flex items-center justify-center rounded font-medium transition-colors focus-visible:outline-none disabled:opacity-50 disabled:cursor-not-allowed",s={primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-muted text-foreground hover:bg-muted/80 border border-border",ghost:"text-muted-foreground hover:text-foreground hover:bg-muted/50"},E={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base",icon:"w-10 h-10 p-0"};return t.jsx("button",{ref:B,className:`${o} ${s[A]} ${E[g]} ${e}`,...Q})});QA.displayName="Button";const AQ=e=>{let A;const g=new Set,Q=(C,a)=>{const I=typeof C=="function"?C(A):C;if(!Object.is(I,A)){const l=A;A=a??(typeof I!="object"||I===null)?I:Object.assign({},A,I),g.forEach(r=>r(A,l))}},B=()=>A,E={setState:Q,getState:B,getInitialState:()=>i,subscribe:C=>(g.add(C),()=>g.delete(C))},i=A=e(Q,B,E);return E},fs=(e=>e?AQ(e):AQ),Ns=e=>e;function ks(e,A=Ns){const g=aA.useSyncExternalStore(e.subscribe,aA.useCallback(()=>A(e.getState()),[e,A]),aA.useCallback(()=>A(e.getInitialState()),[e,A]));return aA.useDebugValue(g),g}const eQ=e=>{const A=fs(e),g=Q=>ks(A,Q);return Object.assign(g,A),g},UA=(e=>e?eQ(e):eQ),Qe=UA(e=>({isExpanded:!1,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(CA.getState().collapseSidebar(),wA.getState().collapseSidebar(),vA.getState().collapseSidebar(),bA.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>e({isExpanded:!0}),collapseSidebar:()=>e({isExpanded:!1})})),vA=UA((e,A)=>({isExpanded:!1,activeResearchSessionId:null,parentSessionId:null,toggleSidebar:()=>{e(g=>{const Q=!g.isExpanded;return Q&&(CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),wA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:Q}})},expandSidebar:()=>{CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),wA.getState().collapseSidebar(),Qe.getState().collapseSidebar(),e({isExpanded:!0})},collapseSidebar:()=>e({isExpanded:!1}),selectResearchSession:g=>e({activeResearchSessionId:g}),setParentSessionId:g=>{A().parentSessionId!==g&&e({parentSessionId:g,activeResearchSessionId:null})},reset:()=>e({activeResearchSessionId:null,parentSessionId:null})})),wA=UA(e=>({isExpanded:!1,selectedFile:null,allOperations:[],selectedOperationIndex:0,isDiffOpen:!1,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>{CA.getState().collapseSidebar(),bA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar(),e({isExpanded:!0})},collapseSidebar:()=>e({isExpanded:!1,isDiffOpen:!1,selectedFile:null,allOperations:[],selectedOperationIndex:0}),openDiff:(A,g)=>e({selectedFile:A,allOperations:g,selectedOperationIndex:g.length-1,isDiffOpen:!0,isExpanded:!0}),selectOperation:A=>e({selectedOperationIndex:A}),closeDiff:()=>e({isDiffOpen:!1,selectedFile:null,allOperations:[],selectedOperationIndex:0})})),CA=UA(e=>({isExpanded:!1,activeSessionId:null,selectedFile:null,selectedFileStaged:!1,isDiffOpen:!1,isCommitModalOpen:!1,commitSessionId:null,wasSessionListCollapsed:!1,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(bA.getState().collapseSidebar(),wA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>e({isExpanded:!0}),collapseSidebar:()=>e({isExpanded:!1,isDiffOpen:!1,selectedFile:null}),openDiff:(A,g)=>e({selectedFile:A,selectedFileStaged:g,isDiffOpen:!0,isExpanded:!0}),closeDiff:()=>e({isDiffOpen:!1,selectedFile:null}),switchFile:(A,g)=>e({selectedFile:A,selectedFileStaged:g}),openCommitModal:()=>e(A=>({isCommitModalOpen:!0,commitSessionId:A.activeSessionId})),openCommitModalForSession:A=>e({isCommitModalOpen:!0,commitSessionId:A}),closeCommitModal:()=>e({isCommitModalOpen:!1,commitSessionId:null}),setActiveSessionId:A=>e({activeSessionId:A}),setSessionListCollapsed:A=>e({wasSessionListCollapsed:A})})),bA=UA(e=>({isExpanded:!1,selectedTerminalId:null,toggleSidebar:()=>{e(A=>{const g=!A.isExpanded;return g&&(CA.getState().collapseSidebar(),wA.getState().collapseSidebar(),vA.getState().collapseSidebar(),Qe.getState().collapseSidebar()),{isExpanded:g}})},expandSidebar:()=>e({isExpanded:!0}),collapseSidebar:()=>e({isExpanded:!1,selectedTerminalId:null}),selectTerminal:A=>e({selectedTerminalId:A})}));var tQ;(function(e){e.OPENAI="openai",e.ANTHROPIC="anthropic",e.GOOGLE="google",e.OPENROUTER="openrouter",e.OPENCODE="opencode",e.ZAI="zai",e.ZAI_CODING="zai-coding",e.MOONSHOT="moonshot",e.COPILOT="copilot",e.SETU="setu"})(tQ||(tQ={}));function iB(e,A){return function(){return e.apply(A,arguments)}}const{toString:Ms}=Object.prototype,{getPrototypeOf:Gg}=Object,{iterator:bt,toStringTag:aB}=Symbol,Ut=(e=>A=>{const g=Ms.call(A);return e[g]||(e[g]=g.slice(8,-1).toLowerCase())})(Object.create(null)),Ae=e=>(e=e.toLowerCase(),A=>Ut(A)===e),Jt=e=>A=>typeof A===e,{isArray:Le}=Array,Se=Jt("undefined");function At(e){return e!==null&&!Se(e)&&e.constructor!==null&&!Se(e.constructor)&&RA(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const rB=Ae("ArrayBuffer");function ys(e){let A;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?A=ArrayBuffer.isView(e):A=e&&e.buffer&&rB(e.buffer),A}const Gs=Jt("string"),RA=Jt("function"),IB=Jt("number"),et=e=>e!==null&&typeof e=="object",Fs=e=>e===!0||e===!1,nt=e=>{if(Ut(e)!=="object")return!1;const A=Gg(e);return(A===null||A===Object.prototype||Object.getPrototypeOf(A)===null)&&!(aB in e)&&!(bt in e)},bs=e=>{if(!et(e)||At(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Us=Ae("Date"),Js=Ae("File"),Ks=Ae("Blob"),Ss=Ae("FileList"),Rs=e=>et(e)&&RA(e.pipe),Ls=e=>{let A;return e&&(typeof FormData=="function"&&e instanceof FormData||RA(e.append)&&((A=Ut(e))==="formdata"||A==="object"&&RA(e.toString)&&e.toString()==="[object FormData]"))},qs=Ae("URLSearchParams"),[Os,Ys,Ts,vs]=["ReadableStream","Request","Response","Headers"].map(Ae),js=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tt(e,A,{allOwnKeys:g=!1}={}){if(e===null||typeof e>"u")return;let Q,B;if(typeof e!="object"&&(e=[e]),Le(e))for(Q=0,B=e.length;Q<B;Q++)A.call(null,e[Q],Q,e);else{if(At(e))return;const o=g?Object.getOwnPropertyNames(e):Object.keys(e),s=o.length;let E;for(Q=0;Q<s;Q++)E=o[Q],A.call(null,e[E],E,e)}}function nB(e,A){if(At(e))return null;A=A.toLowerCase();const g=Object.keys(e);let Q=g.length,B;for(;Q-- >0;)if(B=g[Q],A===B.toLowerCase())return B;return null}const me=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,lB=e=>!Se(e)&&e!==me;function Qg(){const{caseless:e,skipUndefined:A}=lB(this)&&this||{},g={},Q=(B,o)=>{const s=e&&nB(g,o)||o;nt(g[s])&&nt(B)?g[s]=Qg(g[s],B):nt(B)?g[s]=Qg({},B):Le(B)?g[s]=B.slice():(!A||!Se(B))&&(g[s]=B)};for(let B=0,o=arguments.length;B<o;B++)arguments[B]&&tt(arguments[B],Q);return g}const Hs=(e,A,g,{allOwnKeys:Q}={})=>(tt(A,(B,o)=>{g&&RA(B)?Object.defineProperty(e,o,{value:iB(B,g),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,o,{value:B,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:Q}),e),Ps=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Ws=(e,A,g,Q)=>{e.prototype=Object.create(A.prototype,Q),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:A.prototype}),g&&Object.assign(e.prototype,g)},zs=(e,A,g,Q)=>{let B,o,s;const E={};if(A=A||{},e==null)return A;do{for(B=Object.getOwnPropertyNames(e),o=B.length;o-- >0;)s=B[o],(!Q||Q(s,e,A))&&!E[s]&&(A[s]=e[s],E[s]=!0);e=g!==!1&&Gg(e)}while(e&&(!g||g(e,A))&&e!==Object.prototype);return A},Vs=(e,A,g)=>{e=String(e),(g===void 0||g>e.length)&&(g=e.length),g-=A.length;const Q=e.indexOf(A,g);return Q!==-1&&Q===g},Zs=e=>{if(!e)return null;if(Le(e))return e;let A=e.length;if(!IB(A))return null;const g=new Array(A);for(;A-- >0;)g[A]=e[A];return g},Xs=(e=>A=>e&&A instanceof e)(typeof Uint8Array<"u"&&Gg(Uint8Array)),_s=(e,A)=>{const Q=(e&&e[bt]).call(e);let B;for(;(B=Q.next())&&!B.done;){const o=B.value;A.call(e,o[0],o[1])}},$s=(e,A)=>{let g;const Q=[];for(;(g=e.exec(A))!==null;)Q.push(g);return Q},AE=Ae("HTMLFormElement"),eE=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(g,Q,B){return Q.toUpperCase()+B}),gQ=(({hasOwnProperty:e})=>(A,g)=>e.call(A,g))(Object.prototype),tE=Ae("RegExp"),cB=(e,A)=>{const g=Object.getOwnPropertyDescriptors(e),Q={};tt(g,(B,o)=>{let s;(s=A(B,o,e))!==!1&&(Q[o]=s||B)}),Object.defineProperties(e,Q)},gE=e=>{cB(e,(A,g)=>{if(RA(e)&&["arguments","caller","callee"].indexOf(g)!==-1)return!1;const Q=e[g];if(RA(Q)){if(A.enumerable=!1,"writable"in A){A.writable=!1;return}A.set||(A.set=()=>{throw Error("Can not rewrite read-only method '"+g+"'")})}})},QE=(e,A)=>{const g={},Q=B=>{B.forEach(o=>{g[o]=!0})};return Le(e)?Q(e):Q(String(e).split(A)),g},BE=()=>{},oE=(e,A)=>e!=null&&Number.isFinite(e=+e)?e:A;function sE(e){return!!(e&&RA(e.append)&&e[aB]==="FormData"&&e[bt])}const EE=e=>{const A=new Array(10),g=(Q,B)=>{if(et(Q)){if(A.indexOf(Q)>=0)return;if(At(Q))return Q;if(!("toJSON"in Q)){A[B]=Q;const o=Le(Q)?[]:{};return tt(Q,(s,E)=>{const i=g(s,B+1);!Se(i)&&(o[E]=i)}),A[B]=void 0,o}}return Q};return g(e,0)},CE=Ae("AsyncFunction"),iE=e=>e&&(et(e)||RA(e))&&RA(e.then)&&RA(e.catch),dB=((e,A)=>e?setImmediate:A?((g,Q)=>(me.addEventListener("message",({source:B,data:o})=>{B===me&&o===g&&Q.length&&Q.shift()()},!1),B=>{Q.push(B),me.postMessage(g,"*")}))(`axios@${Math.random()}`,[]):g=>setTimeout(g))(typeof setImmediate=="function",RA(me.postMessage)),aE=typeof queueMicrotask<"u"?queueMicrotask.bind(me):typeof process<"u"&&process.nextTick||dB,rE=e=>e!=null&&RA(e[bt]),F={isArray:Le,isArrayBuffer:rB,isBuffer:At,isFormData:Ls,isArrayBufferView:ys,isString:Gs,isNumber:IB,isBoolean:Fs,isObject:et,isPlainObject:nt,isEmptyObject:bs,isReadableStream:Os,isRequest:Ys,isResponse:Ts,isHeaders:vs,isUndefined:Se,isDate:Us,isFile:Js,isBlob:Ks,isRegExp:tE,isFunction:RA,isStream:Rs,isURLSearchParams:qs,isTypedArray:Xs,isFileList:Ss,forEach:tt,merge:Qg,extend:Hs,trim:js,stripBOM:Ps,inherits:Ws,toFlatObject:zs,kindOf:Ut,kindOfTest:Ae,endsWith:Vs,toArray:Zs,forEachEntry:_s,matchAll:$s,isHTMLForm:AE,hasOwnProperty:gQ,hasOwnProp:gQ,reduceDescriptors:cB,freezeMethods:gE,toObjectSet:QE,toCamelCase:eE,noop:BE,toFiniteNumber:oE,findKey:nB,global:me,isContextDefined:lB,isSpecCompliantForm:sE,toJSONObject:EE,isAsyncFn:CE,isThenable:iE,setImmediate:dB,asap:aE,isIterable:rE};let W=class uB extends Error{static from(A,g,Q,B,o,s){const E=new uB(A.message,g||A.code,Q,B,o);return E.cause=A,E.name=A.name,s&&Object.assign(E,s),E}constructor(A,g,Q,B,o){super(A),this.name="AxiosError",this.isAxiosError=!0,g&&(this.code=g),Q&&(this.config=Q),B&&(this.request=B),o&&(this.response=o,this.status=o.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:F.toJSONObject(this.config),code:this.code,status:this.status}}};W.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";W.ERR_BAD_OPTION="ERR_BAD_OPTION";W.ECONNABORTED="ECONNABORTED";W.ETIMEDOUT="ETIMEDOUT";W.ERR_NETWORK="ERR_NETWORK";W.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";W.ERR_DEPRECATED="ERR_DEPRECATED";W.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";W.ERR_BAD_REQUEST="ERR_BAD_REQUEST";W.ERR_CANCELED="ERR_CANCELED";W.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";W.ERR_INVALID_URL="ERR_INVALID_URL";const IE=null;function Bg(e){return F.isPlainObject(e)||F.isArray(e)}function hB(e){return F.endsWith(e,"[]")?e.slice(0,-2):e}function QQ(e,A,g){return e?e.concat(A).map(function(B,o){return B=hB(B),!g&&o?"["+B+"]":B}).join(g?".":""):A}function nE(e){return F.isArray(e)&&!e.some(Bg)}const lE=F.toFlatObject(F,{},null,function(A){return/^is[A-Z]/.test(A)});function Kt(e,A,g){if(!F.isObject(e))throw new TypeError("target must be an object");A=A||new FormData,g=F.toFlatObject(g,{metaTokens:!0,dots:!1,indexes:!1},!1,function(d,c){return!F.isUndefined(c[d])});const Q=g.metaTokens,B=g.visitor||a,o=g.dots,s=g.indexes,i=(g.Blob||typeof Blob<"u"&&Blob)&&F.isSpecCompliantForm(A);if(!F.isFunction(B))throw new TypeError("visitor must be a function");function C(n){if(n===null)return"";if(F.isDate(n))return n.toISOString();if(F.isBoolean(n))return n.toString();if(!i&&F.isBlob(n))throw new W("Blob is not supported. Use a Buffer instead.");return F.isArrayBuffer(n)||F.isTypedArray(n)?i&&typeof Blob=="function"?new Blob([n]):Buffer.from(n):n}function a(n,d,c){let D=n;if(n&&!c&&typeof n=="object"){if(F.endsWith(d,"{}"))d=Q?d:d.slice(0,-2),n=JSON.stringify(n);else if(F.isArray(n)&&nE(n)||(F.isFileList(n)||F.endsWith(d,"[]"))&&(D=F.toArray(n)))return d=hB(d),D.forEach(function(h,m){!(F.isUndefined(h)||h===null)&&A.append(s===!0?QQ([d],m,o):s===null?d:d+"[]",C(h))}),!1}return Bg(n)?!0:(A.append(QQ(c,d,o),C(n)),!1)}const I=[],l=Object.assign(lE,{defaultVisitor:a,convertValue:C,isVisitable:Bg});function r(n,d){if(!F.isUndefined(n)){if(I.indexOf(n)!==-1)throw Error("Circular reference detected in "+d.join("."));I.push(n),F.forEach(n,function(D,N){(!(F.isUndefined(D)||D===null)&&B.call(A,D,F.isString(N)?N.trim():N,d,l))===!0&&r(D,d?d.concat(N):[N])}),I.pop()}}if(!F.isObject(e))throw new TypeError("data must be an object");return r(e),A}function BQ(e){const A={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(Q){return A[Q]})}function Fg(e,A){this._pairs=[],e&&Kt(e,this,A)}const DB=Fg.prototype;DB.append=function(A,g){this._pairs.push([A,g])};DB.toString=function(A){const g=A?function(Q){return A.call(this,Q,BQ)}:BQ;return this._pairs.map(function(B){return g(B[0])+"="+g(B[1])},"").join("&")};function cE(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function wB(e,A,g){if(!A)return e;const Q=g&&g.encode||cE,B=F.isFunction(g)?{serialize:g}:g,o=B&&B.serialize;let s;if(o?s=o(A,B):s=F.isURLSearchParams(A)?A.toString():new Fg(A,B).toString(Q),s){const E=e.indexOf("#");E!==-1&&(e=e.slice(0,E)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class oQ{constructor(){this.handlers=[]}use(A,g,Q){return this.handlers.push({fulfilled:A,rejected:g,synchronous:Q?Q.synchronous:!1,runWhen:Q?Q.runWhen:null}),this.handlers.length-1}eject(A){this.handlers[A]&&(this.handlers[A]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(A){F.forEach(this.handlers,function(Q){Q!==null&&A(Q)})}}const pB={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},dE=typeof URLSearchParams<"u"?URLSearchParams:Fg,uE=typeof FormData<"u"?FormData:null,hE=typeof Blob<"u"?Blob:null,DE={isBrowser:!0,classes:{URLSearchParams:dE,FormData:uE,Blob:hE},protocols:["http","https","file","blob","url","data"]},bg=typeof window<"u"&&typeof document<"u",og=typeof navigator=="object"&&navigator||void 0,wE=bg&&(!og||["ReactNative","NativeScript","NS"].indexOf(og.product)<0),pE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",mE=bg&&window.location.href||"http://localhost",xE=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:bg,hasStandardBrowserEnv:wE,hasStandardBrowserWebWorkerEnv:pE,navigator:og,origin:mE},Symbol.toStringTag,{value:"Module"})),kA={...xE,...DE};function fE(e,A){return Kt(e,new kA.classes.URLSearchParams,{visitor:function(g,Q,B,o){return kA.isNode&&F.isBuffer(g)?(this.append(Q,g.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...A})}function NE(e){return F.matchAll(/\w+|\[(\w*)]/g,e).map(A=>A[0]==="[]"?"":A[1]||A[0])}function kE(e){const A={},g=Object.keys(e);let Q;const B=g.length;let o;for(Q=0;Q<B;Q++)o=g[Q],A[o]=e[o];return A}function mB(e){function A(g,Q,B,o){let s=g[o++];if(s==="__proto__")return!0;const E=Number.isFinite(+s),i=o>=g.length;return s=!s&&F.isArray(B)?B.length:s,i?(F.hasOwnProp(B,s)?B[s]=[B[s],Q]:B[s]=Q,!E):((!B[s]||!F.isObject(B[s]))&&(B[s]=[]),A(g,Q,B[s],o)&&F.isArray(B[s])&&(B[s]=kE(B[s])),!E)}if(F.isFormData(e)&&F.isFunction(e.entries)){const g={};return F.forEachEntry(e,(Q,B)=>{A(NE(Q),B,g,0)}),g}return null}function ME(e,A,g){if(F.isString(e))try{return(A||JSON.parse)(e),F.trim(e)}catch(Q){if(Q.name!=="SyntaxError")throw Q}return(g||JSON.stringify)(e)}const gt={transitional:pB,adapter:["xhr","http","fetch"],transformRequest:[function(A,g){const Q=g.getContentType()||"",B=Q.indexOf("application/json")>-1,o=F.isObject(A);if(o&&F.isHTMLForm(A)&&(A=new FormData(A)),F.isFormData(A))return B?JSON.stringify(mB(A)):A;if(F.isArrayBuffer(A)||F.isBuffer(A)||F.isStream(A)||F.isFile(A)||F.isBlob(A)||F.isReadableStream(A))return A;if(F.isArrayBufferView(A))return A.buffer;if(F.isURLSearchParams(A))return g.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),A.toString();let E;if(o){if(Q.indexOf("application/x-www-form-urlencoded")>-1)return fE(A,this.formSerializer).toString();if((E=F.isFileList(A))||Q.indexOf("multipart/form-data")>-1){const i=this.env&&this.env.FormData;return Kt(E?{"files[]":A}:A,i&&new i,this.formSerializer)}}return o||B?(g.setContentType("application/json",!1),ME(A)):A}],transformResponse:[function(A){const g=this.transitional||gt.transitional,Q=g&&g.forcedJSONParsing,B=this.responseType==="json";if(F.isResponse(A)||F.isReadableStream(A))return A;if(A&&F.isString(A)&&(Q&&!this.responseType||B)){const s=!(g&&g.silentJSONParsing)&&B;try{return JSON.parse(A,this.parseReviver)}catch(E){if(s)throw E.name==="SyntaxError"?W.from(E,W.ERR_BAD_RESPONSE,this,null,this.response):E}}return A}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:kA.classes.FormData,Blob:kA.classes.Blob},validateStatus:function(A){return A>=200&&A<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};F.forEach(["delete","get","head","post","put","patch"],e=>{gt.headers[e]={}});const yE=F.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),GE=e=>{const A={};let g,Q,B;return e&&e.split(`
2
2
  `).forEach(function(s){B=s.indexOf(":"),g=s.substring(0,B).trim().toLowerCase(),Q=s.substring(B+1).trim(),!(!g||A[g]&&yE[g])&&(g==="set-cookie"?A[g]?A[g].push(Q):A[g]=[Q]:A[g]=A[g]?A[g]+", "+Q:Q)}),A},sQ=Symbol("internals");function He(e){return e&&String(e).trim().toLowerCase()}function lt(e){return e===!1||e==null?e:F.isArray(e)?e.map(lt):String(e)}function FE(e){const A=Object.create(null),g=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let Q;for(;Q=g.exec(e);)A[Q[1]]=Q[2];return A}const bE=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Zt(e,A,g,Q,B){if(F.isFunction(Q))return Q.call(this,A,g);if(B&&(A=g),!!F.isString(A)){if(F.isString(Q))return A.indexOf(Q)!==-1;if(F.isRegExp(Q))return Q.test(A)}}function UE(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(A,g,Q)=>g.toUpperCase()+Q)}function JE(e,A){const g=F.toCamelCase(" "+A);["get","set","has"].forEach(Q=>{Object.defineProperty(e,Q+g,{value:function(B,o,s){return this[Q].call(this,A,B,o,s)},configurable:!0})})}let LA=class{constructor(A){A&&this.set(A)}set(A,g,Q){const B=this;function o(E,i,C){const a=He(i);if(!a)throw new Error("header name must be a non-empty string");const I=F.findKey(B,a);(!I||B[I]===void 0||C===!0||C===void 0&&B[I]!==!1)&&(B[I||i]=lt(E))}const s=(E,i)=>F.forEach(E,(C,a)=>o(C,a,i));if(F.isPlainObject(A)||A instanceof this.constructor)s(A,g);else if(F.isString(A)&&(A=A.trim())&&!bE(A))s(GE(A),g);else if(F.isObject(A)&&F.isIterable(A)){let E={},i,C;for(const a of A){if(!F.isArray(a))throw TypeError("Object iterator must return a key-value pair");E[C=a[0]]=(i=E[C])?F.isArray(i)?[...i,a[1]]:[i,a[1]]:a[1]}s(E,g)}else A!=null&&o(g,A,Q);return this}get(A,g){if(A=He(A),A){const Q=F.findKey(this,A);if(Q){const B=this[Q];if(!g)return B;if(g===!0)return FE(B);if(F.isFunction(g))return g.call(this,B,Q);if(F.isRegExp(g))return g.exec(B);throw new TypeError("parser must be boolean|regexp|function")}}}has(A,g){if(A=He(A),A){const Q=F.findKey(this,A);return!!(Q&&this[Q]!==void 0&&(!g||Zt(this,this[Q],Q,g)))}return!1}delete(A,g){const Q=this;let B=!1;function o(s){if(s=He(s),s){const E=F.findKey(Q,s);E&&(!g||Zt(Q,Q[E],E,g))&&(delete Q[E],B=!0)}}return F.isArray(A)?A.forEach(o):o(A),B}clear(A){const g=Object.keys(this);let Q=g.length,B=!1;for(;Q--;){const o=g[Q];(!A||Zt(this,this[o],o,A,!0))&&(delete this[o],B=!0)}return B}normalize(A){const g=this,Q={};return F.forEach(this,(B,o)=>{const s=F.findKey(Q,o);if(s){g[s]=lt(B),delete g[o];return}const E=A?UE(o):String(o).trim();E!==o&&delete g[o],g[E]=lt(B),Q[E]=!0}),this}concat(...A){return this.constructor.concat(this,...A)}toJSON(A){const g=Object.create(null);return F.forEach(this,(Q,B)=>{Q!=null&&Q!==!1&&(g[B]=A&&F.isArray(Q)?Q.join(", "):Q)}),g}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([A,g])=>A+": "+g).join(`
3
3
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(A){return A instanceof this?A:new this(A)}static concat(A,...g){const Q=new this(A);return g.forEach(B=>Q.set(B)),Q}static accessor(A){const Q=(this[sQ]=this[sQ]={accessors:{}}).accessors,B=this.prototype;function o(s){const E=He(s);Q[E]||(JE(B,s),Q[E]=!0)}return F.isArray(A)?A.forEach(o):o(A),this}};LA.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);F.reduceDescriptors(LA.prototype,({value:e},A)=>{let g=A[0].toUpperCase()+A.slice(1);return{get:()=>e,set(Q){this[g]=Q}}});F.freezeMethods(LA);function Xt(e,A){const g=this||gt,Q=A||g,B=LA.from(Q.headers);let o=Q.data;return F.forEach(e,function(E){o=E.call(g,o,B.normalize(),A?A.status:void 0)}),B.normalize(),o}function xB(e){return!!(e&&e.__CANCEL__)}let Qt=class extends W{constructor(A,g,Q){super(A??"canceled",W.ERR_CANCELED,g,Q),this.name="CanceledError",this.__CANCEL__=!0}};function fB(e,A,g){const Q=g.config.validateStatus;!g.status||!Q||Q(g.status)?e(g):A(new W("Request failed with status code "+g.status,[W.ERR_BAD_REQUEST,W.ERR_BAD_RESPONSE][Math.floor(g.status/100)-4],g.config,g.request,g))}function KE(e){const A=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return A&&A[1]||""}function SE(e,A){e=e||10;const g=new Array(e),Q=new Array(e);let B=0,o=0,s;return A=A!==void 0?A:1e3,function(i){const C=Date.now(),a=Q[o];s||(s=C),g[B]=i,Q[B]=C;let I=o,l=0;for(;I!==B;)l+=g[I++],I=I%e;if(B=(B+1)%e,B===o&&(o=(o+1)%e),C-s<A)return;const r=a&&C-a;return r?Math.round(l*1e3/r):void 0}}function RE(e,A){let g=0,Q=1e3/A,B,o;const s=(C,a=Date.now())=>{g=a,B=null,o&&(clearTimeout(o),o=null),e(...C)};return[(...C)=>{const a=Date.now(),I=a-g;I>=Q?s(C,a):(B=C,o||(o=setTimeout(()=>{o=null,s(B)},Q-I)))},()=>B&&s(B)]}const xt=(e,A,g=3)=>{let Q=0;const B=SE(50,250);return RE(o=>{const s=o.loaded,E=o.lengthComputable?o.total:void 0,i=s-Q,C=B(i),a=s<=E;Q=s;const I={loaded:s,total:E,progress:E?s/E:void 0,bytes:i,rate:C||void 0,estimated:C&&E&&a?(E-s)/C:void 0,event:o,lengthComputable:E!=null,[A?"download":"upload"]:!0};e(I)},g)},EQ=(e,A)=>{const g=e!=null;return[Q=>A[0]({lengthComputable:g,total:e,loaded:Q}),A[1]]},CQ=e=>(...A)=>F.asap(()=>e(...A)),LE=kA.hasStandardBrowserEnv?((e,A)=>g=>(g=new URL(g,kA.origin),e.protocol===g.protocol&&e.host===g.host&&(A||e.port===g.port)))(new URL(kA.origin),kA.navigator&&/(msie|trident)/i.test(kA.navigator.userAgent)):()=>!0,qE=kA.hasStandardBrowserEnv?{write(e,A,g,Q,B,o,s){if(typeof document>"u")return;const E=[`${e}=${encodeURIComponent(A)}`];F.isNumber(g)&&E.push(`expires=${new Date(g).toUTCString()}`),F.isString(Q)&&E.push(`path=${Q}`),F.isString(B)&&E.push(`domain=${B}`),o===!0&&E.push("secure"),F.isString(s)&&E.push(`SameSite=${s}`),document.cookie=E.join("; ")},read(e){if(typeof document>"u")return null;const A=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return A?decodeURIComponent(A[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function OE(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function YE(e,A){return A?e.replace(/\/?\/$/,"")+"/"+A.replace(/^\/+/,""):e}function NB(e,A,g){let Q=!OE(A);return e&&(Q||g==!1)?YE(e,A):A}const iQ=e=>e instanceof LA?{...e}:e;function ke(e,A){A=A||{};const g={};function Q(C,a,I,l){return F.isPlainObject(C)&&F.isPlainObject(a)?F.merge.call({caseless:l},C,a):F.isPlainObject(a)?F.merge({},a):F.isArray(a)?a.slice():a}function B(C,a,I,l){if(F.isUndefined(a)){if(!F.isUndefined(C))return Q(void 0,C,I,l)}else return Q(C,a,I,l)}function o(C,a){if(!F.isUndefined(a))return Q(void 0,a)}function s(C,a){if(F.isUndefined(a)){if(!F.isUndefined(C))return Q(void 0,C)}else return Q(void 0,a)}function E(C,a,I){if(I in A)return Q(C,a);if(I in e)return Q(void 0,C)}const i={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:E,headers:(C,a,I)=>B(iQ(C),iQ(a),I,!0)};return F.forEach(Object.keys({...e,...A}),function(a){const I=i[a]||B,l=I(e[a],A[a],a);F.isUndefined(l)&&I!==E||(g[a]=l)}),g}const kB=e=>{const A=ke({},e);let{data:g,withXSRFToken:Q,xsrfHeaderName:B,xsrfCookieName:o,headers:s,auth:E}=A;if(A.headers=s=LA.from(s),A.url=wB(NB(A.baseURL,A.url,A.allowAbsoluteUrls),e.params,e.paramsSerializer),E&&s.set("Authorization","Basic "+btoa((E.username||"")+":"+(E.password?unescape(encodeURIComponent(E.password)):""))),F.isFormData(g)){if(kA.hasStandardBrowserEnv||kA.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(F.isFunction(g.getHeaders)){const i=g.getHeaders(),C=["content-type","content-length"];Object.entries(i).forEach(([a,I])=>{C.includes(a.toLowerCase())&&s.set(a,I)})}}if(kA.hasStandardBrowserEnv&&(Q&&F.isFunction(Q)&&(Q=Q(A)),Q||Q!==!1&&LE(A.url))){const i=B&&o&&qE.read(o);i&&s.set(B,i)}return A},TE=typeof XMLHttpRequest<"u",vE=TE&&function(e){return new Promise(function(g,Q){const B=kB(e);let o=B.data;const s=LA.from(B.headers).normalize();let{responseType:E,onUploadProgress:i,onDownloadProgress:C}=B,a,I,l,r,n;function d(){r&&r(),n&&n(),B.cancelToken&&B.cancelToken.unsubscribe(a),B.signal&&B.signal.removeEventListener("abort",a)}let c=new XMLHttpRequest;c.open(B.method.toUpperCase(),B.url,!0),c.timeout=B.timeout;function D(){if(!c)return;const h=LA.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),y={data:!E||E==="text"||E==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:h,config:e,request:c};fB(function(f){g(f),d()},function(f){Q(f),d()},y),c=null}"onloadend"in c?c.onloadend=D:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(D)},c.onabort=function(){c&&(Q(new W("Request aborted",W.ECONNABORTED,e,c)),c=null)},c.onerror=function(m){const y=m&&m.message?m.message:"Network Error",x=new W(y,W.ERR_NETWORK,e,c);x.event=m||null,Q(x),c=null},c.ontimeout=function(){let m=B.timeout?"timeout of "+B.timeout+"ms exceeded":"timeout exceeded";const y=B.transitional||pB;B.timeoutErrorMessage&&(m=B.timeoutErrorMessage),Q(new W(m,y.clarifyTimeoutError?W.ETIMEDOUT:W.ECONNABORTED,e,c)),c=null},o===void 0&&s.setContentType(null),"setRequestHeader"in c&&F.forEach(s.toJSON(),function(m,y){c.setRequestHeader(y,m)}),F.isUndefined(B.withCredentials)||(c.withCredentials=!!B.withCredentials),E&&E!=="json"&&(c.responseType=B.responseType),C&&([l,n]=xt(C,!0),c.addEventListener("progress",l)),i&&c.upload&&([I,r]=xt(i),c.upload.addEventListener("progress",I),c.upload.addEventListener("loadend",r)),(B.cancelToken||B.signal)&&(a=h=>{c&&(Q(!h||h.type?new Qt(null,e,c):h),c.abort(),c=null)},B.cancelToken&&B.cancelToken.subscribe(a),B.signal&&(B.signal.aborted?a():B.signal.addEventListener("abort",a)));const N=KE(B.url);if(N&&kA.protocols.indexOf(N)===-1){Q(new W("Unsupported protocol "+N+":",W.ERR_BAD_REQUEST,e));return}c.send(o||null)})},jE=(e,A)=>{const{length:g}=e=e?e.filter(Boolean):[];if(A||g){let Q=new AbortController,B;const o=function(C){if(!B){B=!0,E();const a=C instanceof Error?C:this.reason;Q.abort(a instanceof W?a:new Qt(a instanceof Error?a.message:a))}};let s=A&&setTimeout(()=>{s=null,o(new W(`timeout of ${A}ms exceeded`,W.ETIMEDOUT))},A);const E=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(C=>{C.unsubscribe?C.unsubscribe(o):C.removeEventListener("abort",o)}),e=null)};e.forEach(C=>C.addEventListener("abort",o));const{signal:i}=Q;return i.unsubscribe=()=>F.asap(E),i}},HE=function*(e,A){let g=e.byteLength;if(g<A){yield e;return}let Q=0,B;for(;Q<g;)B=Q+A,yield e.slice(Q,B),Q=B},PE=async function*(e,A){for await(const g of WE(e))yield*HE(g,A)},WE=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const A=e.getReader();try{for(;;){const{done:g,value:Q}=await A.read();if(g)break;yield Q}}finally{await A.cancel()}},aQ=(e,A,g,Q)=>{const B=PE(e,A);let o=0,s,E=i=>{s||(s=!0,Q&&Q(i))};return new ReadableStream({async pull(i){try{const{done:C,value:a}=await B.next();if(C){E(),i.close();return}let I=a.byteLength;if(g){let l=o+=I;g(l)}i.enqueue(new Uint8Array(a))}catch(C){throw E(C),C}},cancel(i){return E(i),B.return()}},{highWaterMark:2})},rQ=64*1024,{isFunction:Et}=F,zE=(({Request:e,Response:A})=>({Request:e,Response:A}))(F.global),{ReadableStream:IQ,TextEncoder:nQ}=F.global,lQ=(e,...A)=>{try{return!!e(...A)}catch{return!1}},VE=e=>{e=F.merge.call({skipUndefined:!0},zE,e);const{fetch:A,Request:g,Response:Q}=e,B=A?Et(A):typeof fetch=="function",o=Et(g),s=Et(Q);if(!B)return!1;const E=B&&Et(IQ),i=B&&(typeof nQ=="function"?(n=>d=>n.encode(d))(new nQ):async n=>new Uint8Array(await new g(n).arrayBuffer())),C=o&&E&&lQ(()=>{let n=!1;const d=new g(kA.origin,{body:new IQ,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type");return n&&!d}),a=s&&E&&lQ(()=>F.isReadableStream(new Q("").body)),I={stream:a&&(n=>n.body)};B&&["text","arrayBuffer","blob","formData","stream"].forEach(n=>{!I[n]&&(I[n]=(d,c)=>{let D=d&&d[n];if(D)return D.call(d);throw new W(`Response type '${n}' is not supported`,W.ERR_NOT_SUPPORT,c)})});const l=async n=>{if(n==null)return 0;if(F.isBlob(n))return n.size;if(F.isSpecCompliantForm(n))return(await new g(kA.origin,{method:"POST",body:n}).arrayBuffer()).byteLength;if(F.isArrayBufferView(n)||F.isArrayBuffer(n))return n.byteLength;if(F.isURLSearchParams(n)&&(n=n+""),F.isString(n))return(await i(n)).byteLength},r=async(n,d)=>{const c=F.toFiniteNumber(n.getContentLength());return c??l(d)};return async n=>{let{url:d,method:c,data:D,signal:N,cancelToken:h,timeout:m,onDownloadProgress:y,onUploadProgress:x,responseType:f,headers:M,withCredentials:w="same-origin",fetchOptions:G}=kB(n),p=A||fetch;f=f?(f+"").toLowerCase():"text";let U=jE([N,h&&h.toAbortSignal()],m),k=null;const J=U&&U.unsubscribe&&(()=>{U.unsubscribe()});let S;try{if(x&&C&&c!=="get"&&c!=="head"&&(S=await r(M,D))!==0){let v=new g(d,{method:"POST",body:D,duplex:"half"}),V;if(F.isFormData(D)&&(V=v.headers.get("content-type"))&&M.setContentType(V),v.body){const[_,X]=EQ(S,xt(CQ(x)));D=aQ(v.body,rQ,_,X)}}F.isString(w)||(w=w?"include":"omit");const Y=o&&"credentials"in g.prototype,q={...G,signal:U,method:c.toUpperCase(),headers:M.normalize().toJSON(),body:D,duplex:"half",credentials:Y?w:void 0};k=o&&new g(d,q);let R=await(o?p(k,G):p(d,q));const O=a&&(f==="stream"||f==="response");if(a&&(y||O&&J)){const v={};["status","statusText","headers"].forEach(iA=>{v[iA]=R[iA]});const V=F.toFiniteNumber(R.headers.get("content-length")),[_,X]=y&&EQ(V,xt(CQ(y),!0))||[];R=new Q(aQ(R.body,rQ,_,()=>{X&&X(),J&&J()}),v)}f=f||"text";let K=await I[F.findKey(I,f)||"text"](R,n);return!O&&J&&J(),await new Promise((v,V)=>{fB(v,V,{data:K,headers:LA.from(R.headers),status:R.status,statusText:R.statusText,config:n,request:k})})}catch(Y){throw J&&J(),Y&&Y.name==="TypeError"&&/Load failed|fetch/i.test(Y.message)?Object.assign(new W("Network Error",W.ERR_NETWORK,n,k),{cause:Y.cause||Y}):W.from(Y,Y&&Y.code,n,k)}}},ZE=new Map,MB=e=>{let A=e&&e.env||{};const{fetch:g,Request:Q,Response:B}=A,o=[Q,B,g];let s=o.length,E=s,i,C,a=ZE;for(;E--;)i=o[E],C=a.get(i),C===void 0&&a.set(i,C=E?new Map:VE(A)),a=C;return C};MB();const Ug={http:IE,xhr:vE,fetch:{get:MB}};F.forEach(Ug,(e,A)=>{if(e){try{Object.defineProperty(e,"name",{value:A})}catch{}Object.defineProperty(e,"adapterName",{value:A})}});const cQ=e=>`- ${e}`,XE=e=>F.isFunction(e)||e===null||e===!1;function _E(e,A){e=F.isArray(e)?e:[e];const{length:g}=e;let Q,B;const o={};for(let s=0;s<g;s++){Q=e[s];let E;if(B=Q,!XE(Q)&&(B=Ug[(E=String(Q)).toLowerCase()],B===void 0))throw new W(`Unknown adapter '${E}'`);if(B&&(F.isFunction(B)||(B=B.get(A))))break;o[E||"#"+s]=B}if(!B){const s=Object.entries(o).map(([i,C])=>`adapter ${i} `+(C===!1?"is not supported by the environment":"is not available in the build"));let E=g?s.length>1?`since :
4
4
  `+s.map(cQ).join(`
@@ -27,7 +27,7 @@ For tests, pass a Ghostty instance directly:
27
27
  transition-all duration-150 ease-out cursor-pointer
28
28
  hover:bg-accent/50
29
29
  ${A?"opacity-100 translate-y-0":"opacity-0 translate-y-2"}
30
- `,onClick:B,role:"alert",children:[pi[e.type],t.jsx("span",{className:"text-sm text-foreground",children:e.message}),e.action&&t.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Bt(e.action.href)},className:"ml-auto flex items-center gap-1 text-xs text-primary hover:underline",children:[e.action.label,t.jsx(SA,{className:"h-3 w-3"})]})]})}function xi(){const e=_A(A=>A.toasts);return e.length===0?null:t.jsx("div",{className:"fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 max-w-sm",children:e.map(A=>t.jsx(mi,{toast:A},A.id))})}const Lg=UA(e=>({pendingApprovals:[],addPendingApproval:A=>e(g=>({pendingApprovals:[...g.pendingApprovals,A]})),removePendingApproval:A=>e(g=>({pendingApprovals:g.pendingApprovals.filter(Q=>Q.callId!==A)})),updatePendingApproval:(A,g)=>e(Q=>({pendingApprovals:Q.pendingApprovals.map(B=>B.callId===A?{...B,args:g}:B)})),clearPendingApprovals:()=>e({pendingApprovals:[]}),setPendingApprovals:A=>e({pendingApprovals:A})}));function Ce(e){return Array.isArray?Array.isArray(e):YB(e)==="[object Array]"}function fi(e){if(typeof e=="string")return e;let A=e+"";return A=="0"&&1/e==-1/0?"-0":A}function Ni(e){return e==null?"":fi(e)}function ge(e){return typeof e=="string"}function qB(e){return typeof e=="number"}function ki(e){return e===!0||e===!1||Mi(e)&&YB(e)=="[object Boolean]"}function OB(e){return typeof e=="object"}function Mi(e){return OB(e)&&e!==null}function YA(e){return e!=null}function $t(e){return!e.trim().length}function YB(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const yi="Incorrect 'index' type",Gi=e=>`Invalid value for key ${e}`,Fi=e=>`Pattern length exceeds max of ${e}.`,bi=e=>`Missing ${e} property in key`,Ui=e=>`Property 'weight' in key '${e}' must be a positive integer`,NQ=Object.prototype.hasOwnProperty;class Ji{constructor(A){this._keys=[],this._keyMap={};let g=0;A.forEach(Q=>{let B=TB(Q);this._keys.push(B),this._keyMap[B.id]=B,g+=B.weight}),this._keys.forEach(Q=>{Q.weight/=g})}get(A){return this._keyMap[A]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function TB(e){let A=null,g=null,Q=null,B=1,o=null;if(ge(e)||Ce(e))Q=e,A=kQ(e),g=ag(e);else{if(!NQ.call(e,"name"))throw new Error(bi("name"));const s=e.name;if(Q=s,NQ.call(e,"weight")&&(B=e.weight,B<=0))throw new Error(Ui(s));A=kQ(s),g=ag(s),o=e.getFn}return{path:A,id:g,weight:B,src:Q,getFn:o}}function kQ(e){return Ce(e)?e:e.split(".")}function ag(e){return Ce(e)?e.join("."):e}function Ki(e,A){let g=[],Q=!1;const B=(o,s,E)=>{if(YA(o))if(!s[E])g.push(o);else{let i=s[E];const C=o[i];if(!YA(C))return;if(E===s.length-1&&(ge(C)||qB(C)||ki(C)))g.push(Ni(C));else if(Ce(C)){Q=!0;for(let a=0,I=C.length;a<I;a+=1)B(C[a],s,E+1)}else s.length&&B(C,s,E+1)}};return B(e,ge(A)?A.split("."):A,0),Q?g:g[0]}const Si={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Ri={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,A)=>e.score===A.score?e.idx<A.idx?-1:1:e.score<A.score?-1:1},Li={location:0,threshold:.6,distance:100},qi={useExtendedSearch:!1,getFn:Ki,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var z={...Ri,...Si,...Li,...qi};const Oi=/[^ ]+/g;function Yi(e=1,A=3){const g=new Map,Q=Math.pow(10,A);return{get(B){const o=B.match(Oi).length;if(g.has(o))return g.get(o);const s=1/Math.pow(o,.5*e),E=parseFloat(Math.round(s*Q)/Q);return g.set(o,E),E},clear(){g.clear()}}}class qg{constructor({getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){this.norm=Yi(g,3),this.getFn=A,this.isCreated=!1,this.setIndexRecords()}setSources(A=[]){this.docs=A}setIndexRecords(A=[]){this.records=A}setKeys(A=[]){this.keys=A,this._keysMap={},A.forEach((g,Q)=>{this._keysMap[g.id]=Q})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,ge(this.docs[0])?this.docs.forEach((A,g)=>{this._addString(A,g)}):this.docs.forEach((A,g)=>{this._addObject(A,g)}),this.norm.clear())}add(A){const g=this.size();ge(A)?this._addString(A,g):this._addObject(A,g)}removeAt(A){this.records.splice(A,1);for(let g=A,Q=this.size();g<Q;g+=1)this.records[g].i-=1}getValueForItemAtKeyId(A,g){return A[this._keysMap[g]]}size(){return this.records.length}_addString(A,g){if(!YA(A)||$t(A))return;let Q={v:A,i:g,n:this.norm.get(A)};this.records.push(Q)}_addObject(A,g){let Q={i:g,$:{}};this.keys.forEach((B,o)=>{let s=B.getFn?B.getFn(A):this.getFn(A,B.path);if(YA(s)){if(Ce(s)){let E=[];const i=[{nestedArrIndex:-1,value:s}];for(;i.length;){const{nestedArrIndex:C,value:a}=i.pop();if(YA(a))if(ge(a)&&!$t(a)){let I={v:a,i:C,n:this.norm.get(a)};E.push(I)}else Ce(a)&&a.forEach((I,l)=>{i.push({nestedArrIndex:l,value:I})})}Q.$[o]=E}else if(ge(s)&&!$t(s)){let E={v:s,n:this.norm.get(s)};Q.$[o]=E}}}),this.records.push(Q)}toJSON(){return{keys:this.keys,records:this.records}}}function vB(e,A,{getFn:g=z.getFn,fieldNormWeight:Q=z.fieldNormWeight}={}){const B=new qg({getFn:g,fieldNormWeight:Q});return B.setKeys(e.map(TB)),B.setSources(A),B.create(),B}function Ti(e,{getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){const{keys:Q,records:B}=e,o=new qg({getFn:A,fieldNormWeight:g});return o.setKeys(Q),o.setIndexRecords(B),o}function Ct(e,{errors:A=0,currentLocation:g=0,expectedLocation:Q=0,distance:B=z.distance,ignoreLocation:o=z.ignoreLocation}={}){const s=A/e.length;if(o)return s;const E=Math.abs(Q-g);return B?s+E/B:E?1:s}function vi(e=[],A=z.minMatchCharLength){let g=[],Q=-1,B=-1,o=0;for(let s=e.length;o<s;o+=1){let E=e[o];E&&Q===-1?Q=o:!E&&Q!==-1&&(B=o-1,B-Q+1>=A&&g.push([Q,B]),Q=-1)}return e[o-1]&&o-Q>=A&&g.push([Q,o-1]),g}const pe=32;function ji(e,A,g,{location:Q=z.location,distance:B=z.distance,threshold:o=z.threshold,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,includeMatches:i=z.includeMatches,ignoreLocation:C=z.ignoreLocation}={}){if(A.length>pe)throw new Error(Fi(pe));const a=A.length,I=e.length,l=Math.max(0,Math.min(Q,I));let r=o,n=l;const d=E>1||i,c=d?Array(I):[];let D;for(;(D=e.indexOf(A,n))>-1;){let f=Ct(A,{currentLocation:D,expectedLocation:l,distance:B,ignoreLocation:C});if(r=Math.min(f,r),n=D+a,d){let M=0;for(;M<a;)c[D+M]=1,M+=1}}n=-1;let N=[],h=1,m=a+I;const y=1<<a-1;for(let f=0;f<a;f+=1){let M=0,w=m;for(;M<w;)Ct(A,{errors:f,currentLocation:l+w,expectedLocation:l,distance:B,ignoreLocation:C})<=r?M=w:m=w,w=Math.floor((m-M)/2+M);m=w;let G=Math.max(1,l-w+1),p=s?I:Math.min(l+w,I)+a,U=Array(p+2);U[p+1]=(1<<f)-1;for(let J=p;J>=G;J-=1){let S=J-1,Y=g[e.charAt(S)];if(d&&(c[S]=+!!Y),U[J]=(U[J+1]<<1|1)&Y,f&&(U[J]|=(N[J+1]|N[J])<<1|1|N[J+1]),U[J]&y&&(h=Ct(A,{errors:f,currentLocation:S,expectedLocation:l,distance:B,ignoreLocation:C}),h<=r)){if(r=h,n=S,n<=l)break;G=Math.max(1,2*l-n)}}if(Ct(A,{errors:f+1,currentLocation:l,expectedLocation:l,distance:B,ignoreLocation:C})>r)break;N=U}const x={isMatch:n>=0,score:Math.max(.001,h)};if(d){const f=vi(c,E);f.length?i&&(x.indices=f):x.isMatch=!1}return x}function Hi(e){let A={};for(let g=0,Q=e.length;g<Q;g+=1){const B=e.charAt(g);A[B]=(A[B]||0)|1<<Q-g-1}return A}const Nt=String.prototype.normalize?(e=>e.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"")):(e=>e);class jB{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){if(this.options={location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a},A=i?A:A.toLowerCase(),A=C?Nt(A):A,this.pattern=A,this.chunks=[],!this.pattern.length)return;const I=(r,n)=>{this.chunks.push({pattern:r,alphabet:Hi(r),startIndex:n})},l=this.pattern.length;if(l>pe){let r=0;const n=l%pe,d=l-n;for(;r<d;)I(this.pattern.substr(r,pe),r),r+=pe;if(n){const c=l-pe;I(this.pattern.substr(c),c)}}else I(this.pattern,0)}searchIn(A){const{isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B}=this.options;if(A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern===A){let d={isMatch:!0,score:0};return B&&(d.indices=[[0,A.length-1]]),d}const{location:o,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,ignoreLocation:a}=this.options;let I=[],l=0,r=!1;this.chunks.forEach(({pattern:d,alphabet:c,startIndex:D})=>{const{isMatch:N,score:h,indices:m}=ji(A,d,c,{location:o+D,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,includeMatches:B,ignoreLocation:a});N&&(r=!0),l+=h,N&&m&&(I=[...I,...m])});let n={isMatch:r,score:r?l/this.chunks.length:1};return r&&B&&(n.indices=I),n}}class ce{constructor(A){this.pattern=A}static isMultiMatch(A){return MQ(A,this.multiRegex)}static isSingleMatch(A){return MQ(A,this.singleRegex)}search(){}}function MQ(e,A){const g=e.match(A);return g?g[1]:null}class Pi extends ce{constructor(A){super(A)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(A){const g=A===this.pattern;return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Wi extends ce{constructor(A){super(A)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(A){const Q=A.indexOf(this.pattern)===-1;return{isMatch:Q,score:Q?0:1,indices:[0,A.length-1]}}}class zi extends ce{constructor(A){super(A)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(A){const g=A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Vi extends ce{constructor(A){super(A)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(A){const g=!A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class Zi extends ce{constructor(A){super(A)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(A){const g=A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[A.length-this.pattern.length,A.length-1]}}}class Xi extends ce{constructor(A){super(A)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(A){const g=!A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class HB extends ce{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){super(A),this._bitapSearch=new jB(A,{location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(A){return this._bitapSearch.searchIn(A)}}class PB extends ce{constructor(A){super(A)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(A){let g=0,Q;const B=[],o=this.pattern.length;for(;(Q=A.indexOf(this.pattern,g))>-1;)g=Q+o,B.push([Q,g-1]);const s=!!B.length;return{isMatch:s,score:s?0:1,indices:B}}}const rg=[Pi,PB,zi,Vi,Xi,Zi,Wi,HB],yQ=rg.length,_i=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,$i="|";function Aa(e,A={}){return e.split($i).map(g=>{let Q=g.trim().split(_i).filter(o=>o&&!!o.trim()),B=[];for(let o=0,s=Q.length;o<s;o+=1){const E=Q[o];let i=!1,C=-1;for(;!i&&++C<yQ;){const a=rg[C];let I=a.isMultiMatch(E);I&&(B.push(new a(I,A)),i=!0)}if(!i)for(C=-1;++C<yQ;){const a=rg[C];let I=a.isSingleMatch(E);if(I){B.push(new a(I,A));break}}}return B})}const ea=new Set([HB.type,PB.type]);class ta{constructor(A,{isCaseSensitive:g=z.isCaseSensitive,ignoreDiacritics:Q=z.ignoreDiacritics,includeMatches:B=z.includeMatches,minMatchCharLength:o=z.minMatchCharLength,ignoreLocation:s=z.ignoreLocation,findAllMatches:E=z.findAllMatches,location:i=z.location,threshold:C=z.threshold,distance:a=z.distance}={}){this.query=null,this.options={isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B,minMatchCharLength:o,findAllMatches:E,ignoreLocation:s,location:i,threshold:C,distance:a},A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern=A,this.query=Aa(this.pattern,this.options)}static condition(A,g){return g.useExtendedSearch}searchIn(A){const g=this.query;if(!g)return{isMatch:!1,score:1};const{includeMatches:Q,isCaseSensitive:B,ignoreDiacritics:o}=this.options;A=B?A:A.toLowerCase(),A=o?Nt(A):A;let s=0,E=[],i=0;for(let C=0,a=g.length;C<a;C+=1){const I=g[C];E.length=0,s=0;for(let l=0,r=I.length;l<r;l+=1){const n=I[l],{isMatch:d,indices:c,score:D}=n.search(A);if(d){if(s+=1,i+=D,Q){const N=n.constructor.type;ea.has(N)?E=[...E,...c]:E.push(c)}}else{i=0,s=0,E.length=0;break}}if(s){let l={isMatch:!0,score:i/s};return Q&&(l.indices=E),l}}return{isMatch:!1,score:1}}}const Ig=[];function ga(...e){Ig.push(...e)}function ng(e,A){for(let g=0,Q=Ig.length;g<Q;g+=1){let B=Ig[g];if(B.condition(e,A))return new B(e,A)}return new jB(e,A)}const kt={AND:"$and",OR:"$or"},lg={PATH:"$path",PATTERN:"$val"},cg=e=>!!(e[kt.AND]||e[kt.OR]),Qa=e=>!!e[lg.PATH],Ba=e=>!Ce(e)&&OB(e)&&!cg(e),GQ=e=>({[kt.AND]:Object.keys(e).map(A=>({[A]:e[A]}))});function WB(e,A,{auto:g=!0}={}){const Q=B=>{let o=Object.keys(B);const s=Qa(B);if(!s&&o.length>1&&!cg(B))return Q(GQ(B));if(Ba(B)){const i=s?B[lg.PATH]:o[0],C=s?B[lg.PATTERN]:B[i];if(!ge(C))throw new Error(Gi(i));const a={keyId:ag(i),pattern:C};return g&&(a.searcher=ng(C,A)),a}let E={children:[],operator:o[0]};return o.forEach(i=>{const C=B[i];Ce(C)&&C.forEach(a=>{E.children.push(Q(a))})}),E};return cg(e)||(e=GQ(e)),Q(e)}function oa(e,{ignoreFieldNorm:A=z.ignoreFieldNorm}){e.forEach(g=>{let Q=1;g.matches.forEach(({key:B,norm:o,score:s})=>{const E=B?B.weight:null;Q*=Math.pow(s===0&&E?Number.EPSILON:s,(E||1)*(A?1:o))}),g.score=Q})}function sa(e,A){const g=e.matches;A.matches=[],YA(g)&&g.forEach(Q=>{if(!YA(Q.indices)||!Q.indices.length)return;const{indices:B,value:o}=Q;let s={indices:B,value:o};Q.key&&(s.key=Q.key.src),Q.idx>-1&&(s.refIndex=Q.idx),A.matches.push(s)})}function Ea(e,A){A.score=e.score}function Ca(e,A,{includeMatches:g=z.includeMatches,includeScore:Q=z.includeScore}={}){const B=[];return g&&B.push(sa),Q&&B.push(Ea),e.map(o=>{const{idx:s}=o,E={item:A[s],refIndex:s};return B.length&&B.forEach(i=>{i(o,E)}),E})}class de{constructor(A,g={},Q){this.options={...z,...g},this.options.useExtendedSearch,this._keyStore=new Ji(this.options.keys),this.setCollection(A,Q)}setCollection(A,g){if(this._docs=A,g&&!(g instanceof qg))throw new Error(yi);this._myIndex=g||vB(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(A){YA(A)&&(this._docs.push(A),this._myIndex.add(A))}remove(A=()=>!1){const g=[];for(let Q=0,B=this._docs.length;Q<B;Q+=1){const o=this._docs[Q];A(o,Q)&&(this.removeAt(Q),Q-=1,B-=1,g.push(o))}return g}removeAt(A){this._docs.splice(A,1),this._myIndex.removeAt(A)}getIndex(){return this._myIndex}search(A,{limit:g=-1}={}){const{includeMatches:Q,includeScore:B,shouldSort:o,sortFn:s,ignoreFieldNorm:E}=this.options;let i=ge(A)?ge(this._docs[0])?this._searchStringList(A):this._searchObjectList(A):this._searchLogical(A);return oa(i,{ignoreFieldNorm:E}),o&&i.sort(s),qB(g)&&g>-1&&(i=i.slice(0,g)),Ca(i,this._docs,{includeMatches:Q,includeScore:B})}_searchStringList(A){const g=ng(A,this.options),{records:Q}=this._myIndex,B=[];return Q.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=g.searchIn(o);i&&B.push({item:o,idx:s,matches:[{score:C,value:o,norm:E,indices:a}]})}),B}_searchLogical(A){const g=WB(A,this.options),Q=(E,i,C)=>{if(!E.children){const{keyId:I,searcher:l}=E,r=this._findMatches({key:this._keyStore.get(I),value:this._myIndex.getValueForItemAtKeyId(i,I),searcher:l});return r&&r.length?[{idx:C,item:i,matches:r}]:[]}const a=[];for(let I=0,l=E.children.length;I<l;I+=1){const r=E.children[I],n=Q(r,i,C);if(n.length)a.push(...n);else if(E.operator===kt.AND)return[]}return a},B=this._myIndex.records,o={},s=[];return B.forEach(({$:E,i})=>{if(YA(E)){let C=Q(g,E,i);C.length&&(o[i]||(o[i]={idx:i,item:E,matches:[]},s.push(o[i])),C.forEach(({matches:a})=>{o[i].matches.push(...a)}))}}),s}_searchObjectList(A){const g=ng(A,this.options),{keys:Q,records:B}=this._myIndex,o=[];return B.forEach(({$:s,i:E})=>{if(!YA(s))return;let i=[];Q.forEach((C,a)=>{i.push(...this._findMatches({key:C,value:s[a],searcher:g}))}),i.length&&o.push({idx:E,item:s,matches:i})}),o}_findMatches({key:A,value:g,searcher:Q}){if(!YA(g))return[];let B=[];if(Ce(g))g.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=Q.searchIn(o);i&&B.push({score:C,key:A,value:o,idx:s,norm:E,indices:a})});else{const{v:o,n:s}=g,{isMatch:E,score:i,indices:C}=Q.searchIn(o);E&&B.push({score:i,key:A,value:o,norm:s,indices:C})}return B}}de.version="7.1.0";de.createIndex=vB;de.parseIndex=Ti;de.config=z;de.parseQuery=WB;ga(ta);function ia(e){switch(e.split(".").pop()?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"go":case"rs":case"java":case"c":case"cpp":case"h":case"hpp":return WQ;case"json":case"yaml":case"yml":case"toml":return zo;case"md":case"txt":case"log":return Ft;case"png":case"jpg":case"jpeg":case"gif":case"svg":case"webp":return PQ;case"css":case"scss":case"sass":case"less":return Wo;case"html":case"xml":return Po;default:return le}}function aa(e,A){const g=A.get(e);return g?{added:{icon:Je,label:"Added",className:"text-green-500"},modified:{icon:gg,label:"Modified",className:"text-yellow-500"},untracked:{icon:Je,label:"Untracked",className:"text-blue-500"}}[g]||{icon:gg,label:"Modified",className:"text-yellow-500"}:null}function ra({files:e,changedFiles:A=[],query:g,selectedIndex:Q,onSelect:B,onEnterSelect:o,onClose:s}){const E=u.useMemo(()=>new Map(A?.map(a=>[a.path,a.status])||[]),[A]),i=u.useMemo(()=>new de(e,{threshold:.4,distance:100,ignoreLocation:!0,includeMatches:!0}),[e]),C=u.useMemo(()=>{if(!g)return e.slice(0,20);const a=i.search(g).map(I=>I.item);return a.sort((I,l)=>{const r=E.has(I),n=E.has(l);return r&&!n?-1:!r&&n?1:0}),a.slice(0,20)},[i,g,e,E]);return u.useEffect(()=>{document.getElementById(`file-item-${Q}`)?.scrollIntoView({block:"nearest"})},[Q]),u.useEffect(()=>{o(C[Q])},[C,Q,o]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-file-mention-popup]")||s()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[s]),C.length===0?t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No files found"})}):t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>t.jsx("button",{type:"button",id:`file-item-${I}`,onMouseDown:l=>{l.preventDefault(),B(a)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===Q?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-2 w-full",children:[(()=>{const l=ia(a);return t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-muted-foreground"})})(),t.jsx("span",{className:"font-mono text-sm flex-1 truncate",children:a}),(()=>{const l=aa(a,E);return l&&t.jsx(l.icon,{className:`w-3.5 h-3.5 flex-shrink-0 ${l.className}`,title:l.label})})()]})},a))})}const zB="otto-preferences",ut={vimMode:!1,reasoningEnabled:!0};function Ia(){if(typeof window>"u")return ut;try{const e=window.localStorage.getItem(zB);if(e){const A=JSON.parse(e);return{...ut,...A}}}catch(e){console.warn("Failed to load preferences",e)}return ut}let ht=Ia();const dg=new Set;function na(){return ht}function la(){return ut}function ca(e){return dg.add(e),()=>dg.delete(e)}function da(){for(const e of dg)e()}function ua(e){if(ht={...ht,...e},typeof window<"u")try{window.localStorage.setItem(zB,JSON.stringify(ht))}catch(A){console.warn("Failed to persist preferences",A)}da()}function ot(){const e=u.useSyncExternalStore(ca,na,la),A=u.useCallback(g=>{ua(g)},[]);return u.useMemo(()=>({preferences:e,updatePreferences:A}),[e,A])}function Z(e){if(!e)return"Unknown error";if(typeof e=="string")return e;if(e&&typeof e=="object"){const A=e;if(A.error&&typeof A.error=="object"){const g=A.error;if(typeof g.message=="string")return g.message}if(typeof A.error=="string")return A.error;if(typeof A.message=="string")return A.message;try{return JSON.stringify(e)}catch{return"Error occurred (unable to parse)"}}return"Unknown error"}function ha(){const A=window.OTTO_SERVER_URL||qt;lA.setConfig({baseURL:A})}ha();function Ag(e){return{...e,title:e.title??null,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,lastActiveAt:typeof e.lastActiveAt=="string"?new Date(e.lastActiveAt).getTime():e.lastActiveAt}}function Da(e){return{...e,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,completedAt:e.completedAt?typeof e.completedAt=="string"?new Date(e.completedAt).getTime():e.completedAt:null}}class wa{get baseUrl(){const A=window;return A.OTTO_SERVER_URL?A.OTTO_SERVER_URL:qt}async getSessions(){const A=await uC();if(A.error)throw new Error(Z(A.error));return(A.data||[]).map(Ag)}async createSession(A){const g=await hC({body:A});if(g.error)throw new Error(Z(g.error));if(!g.data)throw new Error("No data returned from create session");return Ag(g.data)}async updateSession(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const o=await Q.json().catch(()=>({error:"Failed to update session"}));throw new Error(Z(o))}const B=await Q.json();return Ag(B)}async deleteSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to delete session"}));throw new Error(Z(Q))}return await g.json()}async abortSession(A){const g=await DC({path:{sessionId:A}});if(g.error)throw new Error(Z(g.error));return g.data}async abortMessage(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/abort`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:g})});if(!B.ok)throw new Error("Failed to abort message");return B.json()}async getQueueState(A){const g=this.baseUrl,Q=await fetch(`${g}/v1/sessions/${A}/queue`);if(!Q.ok)throw new Error("Failed to get queue state");return Q.json()}async removeFromQueue(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/queue/${g}`,{method:"DELETE"});if(!B.ok)throw new Error("Failed to remove from queue");return B.json()}async getMessages(A){const g=await wC({path:{id:A}});if(g.error)throw new Error(Z(g.error));return(g.data||[]).map(Da)}async sendMessage(A,g){const Q=await pC({path:{id:A},body:g});if(Q.error)throw new Error(Z(Q.error));return Q.data}getStreamUrl(A){return`${this.baseUrl}/v1/sessions/${A}/stream`}async getConfig(){const A=await mC();if(A.error)throw new Error(Z(A.error));return A.data}async getModels(A){const g=await xC({path:{provider:A}});if(g.error)throw new Error(Z(g.error));return g.data}async getAllModels(){const A=await fetch(`${this.baseUrl}/v1/config/models`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to fetch models"}));throw new Error(Z(g))}return await A.json()}async updateDefaults(A){const g=await fetch(`${this.baseUrl}/v1/config/defaults`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to update defaults"}));throw new Error(Z(Q))}return await g.json()}async getGitStatus(){const A=await NC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async getGitDiff(A,g=!1){const Q=await kC({query:{file:A,staged:g?"true":"false"}});if(Q.error)throw new Error(Z(Q.error));return Q.data?.data}async generateCommitMessage(A){const g=await bC({body:A?{sessionId:A}:{}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async stageFiles(A){const g=await yC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async unstageFiles(A){const g=await GC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async restoreFiles(A){const g=await JC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async deleteFiles(A){const g=await KC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async commitChanges(A){const g=await FC({body:{message:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async getGitBranch(){const A=await MC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async pushCommits(){const A=await UC({body:{}});if(A.error)throw new Error(Z(A.error));return A.data?.data}async listFiles(){const A=await fC();if(A.error)throw new Error(Z(A.error));return A.data}async getSessionFiles(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/files`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to fetch session files"}));throw new Error(Z(Q))}return await g.json()}async createBranch(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/branch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create branch"}));throw new Error(Z(B))}return await Q.json()}async listBranches(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/branches`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to list branches"}));throw new Error(Z(Q))}return await g.json()}async getParentSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/parent`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to get parent session"}));throw new Error(Z(Q))}return await g.json()}async getSetuBalance(){try{const A=await fetch(`${this.baseUrl}/v1/setu/balance`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():null}catch{return null}}async getSetuWallet(){try{const A=await fetch(`${this.baseUrl}/v1/setu/wallet`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():{configured:!1}}catch{return{configured:!1}}}async getSetuUsdcBalance(A="mainnet"){try{const g=await fetch(`${this.baseUrl}/v1/setu/usdc-balance?network=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async getShareStatus(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{shared:!1}}async shareSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to share session"}));throw new Error(Z(Q))}return await g.json()}async syncSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"PUT",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to sync session"}));throw new Error(Z(Q))}return await g.json()}async approveToolCall(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:g,approved:Q})});if(!B.ok)throw new Error("Failed to send tool approval");return await B.json()}async getPendingApprovals(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval/pending`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{ok:!1,pending:[]}}async getPolarTopupEstimate(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/estimate?amount=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async createPolarCheckout(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/polar`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:A,successUrl:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create checkout"}));throw new Error(Z(B))}return await Q.json()}async selectTopupMethod(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/select`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,method:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to select topup method"}));throw new Error(Z(B))}return await Q.json()}async cancelTopup(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,reason:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to cancel topup"}));throw new Error(Z(B))}return await Q.json()}async getPendingTopup(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/pending?sessionId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{hasPending:!1}}catch{return{hasPending:!1}}}async getPolarTopupStatus(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/status?checkoutId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async retryMessage(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/messages/${g}/retry`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to retry message"}));throw new Error(Z(B))}return await Q.json()}async getAuthStatus(){const A=await fetch(`${this.baseUrl}/v1/auth/status`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to get auth status"}));throw new Error(Z(g))}return await A.json()}async setupSetuWallet(){const A=await fetch(`${this.baseUrl}/v1/auth/setu/setup`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to setup wallet"}));throw new Error(Z(g))}return await A.json()}async importSetuWallet(A){const g=await fetch(`${this.baseUrl}/v1/auth/setu/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({privateKey:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to import wallet"}));throw new Error(Z(Q))}return await g.json()}async addProvider(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to add provider"}));throw new Error(Z(B))}return await Q.json()}async removeProvider(A){const g=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to remove provider"}));throw new Error(Z(Q))}return await g.json()}async completeOnboarding(){const A=await fetch(`${this.baseUrl}/v1/auth/onboarding/complete`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to complete onboarding"}));throw new Error(Z(g))}return await A.json()}getOAuthStartUrl(A,g){const Q=`${this.baseUrl}/v1/auth/${A}/oauth/start`;return g?`${Q}?mode=${g}`:Q}async getOAuthUrl(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to get OAuth URL"}));throw new Error(Z(B))}return await Q.json()}async exchangeOAuthCode(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g,sessionId:Q})});if(!B.ok){const o=await B.json().catch(()=>({error:"Failed to exchange OAuth code"}));throw new Error(Z(o))}return await B.json()}async startCopilotDeviceFlow(){const A=await fetch(`${this.baseUrl}/v1/auth/copilot/device/start`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to start Copilot device flow"}));throw new Error(Z(g))}return await A.json()}async pollCopilotDeviceFlow(A){const g=await fetch(`${this.baseUrl}/v1/auth/copilot/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Poll failed"}));throw new Error(Z(Q))}return await g.json()}}const T=new wa;function Og(e){const{data:A,isLoading:g,error:Q}=PA({queryKey:["share-status",e],queryFn:()=>T.getShareStatus(e),enabled:!!e,staleTime:3e4});return{data:A,isLoading:g,error:Q}}const VB=[{id:"models",label:"/models",description:"Open model selector",icon:Ke},{id:"agents",label:"/agents",description:"Open agent selector",icon:fe},{id:"new",label:"/new",description:"Create new session",icon:Je},{id:"stop",label:"/stop",description:"Stop current generation",icon:zQ},{id:"help",label:"/help",description:"Show keyboard shortcuts and help",icon:VQ},{id:"vim",label:"/vim",description:e=>e.vimModeEnabled?"Disable Vim mode":"Enable Vim mode",icon:Vo},{id:"reasoning",label:"/reasoning",description:e=>e.reasoningEnabled?"Disable extended thinking":"Enable extended thinking",icon:Ng},{id:"stage",label:"/stage",description:"Stage all changes (git add -A)",icon:HA},{id:"commit",label:"/commit",description:"Commit staged changes",icon:XA},{id:"compact",label:"/compact",description:"Compact conversation to reduce context size",icon:Zo},{id:"branch",label:"/branch",description:"Branch session from last message",icon:Xo},{id:"delete",label:"/delete",description:"Delete current session",icon:kg},{id:"share",label:"/share",description:"Share session publicly",icon:Mg},{id:"sync",label:"/sync",description:"Sync new messages to shared session",icon:TA}];function ZB(e,A){return typeof e.description=="function"?e.description(A):e.description}function pa(e,A){const g=VB.filter(o=>!(o.id==="share"&&A.isShared||o.id==="sync"&&!A.isShared));if(!e)return g;const Q=e.toLowerCase(),B=[];for(const o of g){const s=ZB(o,A),E=o.label.toLowerCase().includes(Q),i=s.toLowerCase().includes(Q);if(E||i){const C=E?10:5;B.push({...o,matchScore:C})}}return B.sort((o,s)=>{const E=s.matchScore-o.matchScore;return E!==0?E:o.label.localeCompare(s.label)})}function ma({query:e,selectedIndex:A,onSelect:g,onEnterSelect:Q,onClose:B,sessionId:o}){const{preferences:s}=ot(),{data:E}=Og(o),i=u.useMemo(()=>({vimModeEnabled:s.vimMode,reasoningEnabled:s.reasoningEnabled,isShared:E?.shared}),[s.vimMode,s.reasoningEnabled,E?.shared]),C=u.useMemo(()=>pa(e,i),[e,i]);return u.useEffect(()=>{document.getElementById(`command-item-${A}`)?.scrollIntoView({block:"nearest"})},[A]),u.useEffect(()=>{Q(C[A]?.id)},[C,A,Q]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-command-popup]")||B()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[B]),C.length===0?t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No commands found"})}):t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>{const l=a.icon;return t.jsx("button",{type:"button",id:`command-item-${I}`,onMouseDown:r=>{r.preventDefault(),g(a.id)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===A?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-3 w-full",children:[t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-primary"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-mono text-sm font-medium text-foreground",children:a.label}),t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ZB(a,i)})]})]})},a.id)})})}const xa={sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-xl","2xl":"max-w-2xl"};function qe({isOpen:e,onClose:A,title:g,children:Q,showCloseButton:B=!0,closeOnBackdropClick:o=!0,closeOnEscape:s=!0,maxWidth:E="md"}){if(u.useEffect(()=>{if(!e||!s)return;const C=a=>{const I=a.target,l=I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable;(a.key==="Escape"||a.key==="q"&&!l)&&(a.preventDefault(),a.stopPropagation(),A())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,s,A]),u.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),!e)return null;const i=C=>{o&&C.target===C.currentTarget&&A()};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] cursor-default",onClick:i,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&i(C)},"aria-label":"Close modal"}),t.jsx("div",{className:`fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[9999] w-full ${xa[E]} px-4`,children:t.jsxs("div",{className:"bg-background border border-border rounded-lg shadow-lg",children:[(g||B)&&t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[g&&t.jsx("div",{className:"text-lg font-semibold text-foreground",children:g}),B&&t.jsx("button",{type:"button",onClick:A,className:"text-muted-foreground hover:text-foreground transition-colors ml-auto","aria-label":"Close",children:t.jsx(MA,{className:"h-5 w-5"})})]}),t.jsx("div",{className:"p-6",children:Q})]})})]})}const fa=[{keys:["Ctrl","H"],description:"Navigate to left sidebar (sessions)",category:"Navigation"},{keys:["Ctrl","L"],description:"Navigate to right sidebar (git)",category:"Navigation"},{keys:["Ctrl","/"],description:"Toggle left sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","\\"],description:"Toggle right sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","N"],description:"Create new session",category:"Navigation"},{keys:["ESC"],description:"Close sidebar and return to center",category:"Navigation"},{keys:["J"],description:"Navigate to next item (in focused list)",category:"List Navigation"},{keys:["K"],description:"Navigate to previous item (in focused list)",category:"List Navigation"},{keys:["Enter"],description:"Select focused item and return to input",category:"List Navigation"},{keys:["Space"],description:"Toggle stage/unstage for focused file (git panel)",category:"Git Operations"},{keys:["A"],description:"Stage all unstaged files",category:"Git Operations"},{keys:["U"],description:"Unstage all staged files",category:"Git Operations"},{keys:["C"],description:"Open commit modal (if files are staged)",category:"Git Operations"},{keys:["Tab"],description:"Toggle plan mode",category:"Chat"},{keys:["Enter"],description:"Send message",category:"Chat"},{keys:["Shift","Enter"],description:"New line in message",category:"Chat"},{keys:["@"],description:"Mention file (opens file picker)",category:"Chat"},{keys:["/"],description:"Slash command (opens command menu)",category:"Chat"}],Na=[{keys:["i"],description:"Enter insert mode at cursor (vim mode)",category:"Vim Mode"},{keys:["a"],description:"Enter insert mode after cursor (vim mode)",category:"Vim Mode"},{keys:["I"],description:"Enter insert mode at line start (vim mode)",category:"Vim Mode"},{keys:["A"],description:"Enter insert mode at line end (vim mode)",category:"Vim Mode"},{keys:["o"],description:"New line below and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["O"],description:"New line above and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["ESC"],description:"Return to normal mode (vim mode)",category:"Vim Mode"},{keys:["Enter"],description:"Send message in normal mode (vim mode)",category:"Vim Mode"},{keys:["w"],description:"Jump to next word start (vim mode)",category:"Vim Mode"},{keys:["e"],description:"Jump to next word end (vim mode)",category:"Vim Mode"},{keys:["b"],description:"Jump to previous word start (vim mode)",category:"Vim Mode"},{keys:["x"],description:"Delete character under cursor (vim mode)",category:"Vim Mode"},{keys:["s"],description:"Delete character and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["S"],description:"Delete line and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["f","{char}"],description:"Find and jump to next character on line (vim mode)",category:"Vim Mode"},{keys:["d","d"],description:"Delete current line (vim mode)",category:"Vim Mode"},{keys:["0"],description:"Jump to line start (vim mode)",category:"Vim Mode"},{keys:["$"],description:"Jump to line end (vim mode)",category:"Vim Mode"}],ka=[{command:"/models",description:"Open model selector"},{command:"/agents",description:"Open agent selector"},{command:"/new",description:"Create new session"},{command:"/help",description:"Show keyboard shortcuts and help (this modal)"},{command:"/compact",description:"Compact conversation to reduce context size"}];function Ma(e){const A={};for(const g of e)A[g.category]||(A[g.category]=[]),A[g.category].push(g);return A}function ya({isOpen:e,onClose:A}){const g=[...fa,...Na],Q=Ma(g),B=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{e?(o.current=document.activeElement,o.current&&o.current.blur()):o.current&&(o.current.focus(),o.current=null)},[e]),u.useEffect(()=>{if(!e)return;const s=E=>{const i=E.target;if(!(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable))if(E.key==="j"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:100,behavior:"smooth"})}else if(E.key==="k"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:-100,behavior:"smooth"})}else E.key==="Enter"&&(E.preventDefault(),A())};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,A]),t.jsx(qe,{isOpen:e,onClose:A,title:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(VQ,{className:"w-5 h-5"}),t.jsx("span",{children:"Keyboard Shortcuts & Help"})]}),maxWidth:"2xl",closeOnEscape:!0,closeOnBackdropClick:!0,children:t.jsxs("div",{ref:B,className:"space-y-6 max-h-[70vh] overflow-y-auto",children:[Object.entries(Q).map(([s,E])=>t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),s]}),t.jsx("div",{className:"space-y-2",children:E.map((i,C)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:i.description}),t.jsx("div",{className:"flex items-center gap-1",children:i.keys.map(a=>t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:a}),i.keys.indexOf(a)<i.keys.length-1&&t.jsx("span",{className:"text-muted-foreground",children:"+"})]},a))})]},`${s}-${i.description}`))})]},s)),t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),"Slash Commands"]}),t.jsx("div",{className:"space-y-2",children:ka.map((s,E)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:s.description}),t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:s.command})]},s.command))})]}),t.jsx("div",{className:"pt-4 border-t border-border",children:t.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.jsx("strong",{children:"Tip:"})," Shortcuts are disabled when typing in input fields. Press ",t.jsx("kbd",{className:"text-xs",children:"ESC"})," to close popups and return focus to chat input."]})})]})})}const Ga=`<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
30
+ `,onClick:B,role:"alert",children:[pi[e.type],t.jsx("span",{className:"text-sm text-foreground",children:e.message}),e.action&&t.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Bt(e.action.href)},className:"ml-auto flex items-center gap-1 text-xs text-primary hover:underline",children:[e.action.label,t.jsx(SA,{className:"h-3 w-3"})]})]})}function xi(){const e=_A(A=>A.toasts);return e.length===0?null:t.jsx("div",{className:"fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 max-w-sm",children:e.map(A=>t.jsx(mi,{toast:A},A.id))})}const Lg=UA(e=>({pendingApprovals:[],addPendingApproval:A=>e(g=>({pendingApprovals:[...g.pendingApprovals,A]})),removePendingApproval:A=>e(g=>({pendingApprovals:g.pendingApprovals.filter(Q=>Q.callId!==A)})),updatePendingApproval:(A,g)=>e(Q=>({pendingApprovals:Q.pendingApprovals.map(B=>B.callId===A?{...B,args:g}:B)})),clearPendingApprovals:()=>e({pendingApprovals:[]}),setPendingApprovals:A=>e({pendingApprovals:A})}));function Ce(e){return Array.isArray?Array.isArray(e):YB(e)==="[object Array]"}function fi(e){if(typeof e=="string")return e;let A=e+"";return A=="0"&&1/e==-1/0?"-0":A}function Ni(e){return e==null?"":fi(e)}function ge(e){return typeof e=="string"}function qB(e){return typeof e=="number"}function ki(e){return e===!0||e===!1||Mi(e)&&YB(e)=="[object Boolean]"}function OB(e){return typeof e=="object"}function Mi(e){return OB(e)&&e!==null}function YA(e){return e!=null}function $t(e){return!e.trim().length}function YB(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const yi="Incorrect 'index' type",Gi=e=>`Invalid value for key ${e}`,Fi=e=>`Pattern length exceeds max of ${e}.`,bi=e=>`Missing ${e} property in key`,Ui=e=>`Property 'weight' in key '${e}' must be a positive integer`,NQ=Object.prototype.hasOwnProperty;class Ji{constructor(A){this._keys=[],this._keyMap={};let g=0;A.forEach(Q=>{let B=TB(Q);this._keys.push(B),this._keyMap[B.id]=B,g+=B.weight}),this._keys.forEach(Q=>{Q.weight/=g})}get(A){return this._keyMap[A]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function TB(e){let A=null,g=null,Q=null,B=1,o=null;if(ge(e)||Ce(e))Q=e,A=kQ(e),g=ag(e);else{if(!NQ.call(e,"name"))throw new Error(bi("name"));const s=e.name;if(Q=s,NQ.call(e,"weight")&&(B=e.weight,B<=0))throw new Error(Ui(s));A=kQ(s),g=ag(s),o=e.getFn}return{path:A,id:g,weight:B,src:Q,getFn:o}}function kQ(e){return Ce(e)?e:e.split(".")}function ag(e){return Ce(e)?e.join("."):e}function Ki(e,A){let g=[],Q=!1;const B=(o,s,E)=>{if(YA(o))if(!s[E])g.push(o);else{let i=s[E];const C=o[i];if(!YA(C))return;if(E===s.length-1&&(ge(C)||qB(C)||ki(C)))g.push(Ni(C));else if(Ce(C)){Q=!0;for(let a=0,I=C.length;a<I;a+=1)B(C[a],s,E+1)}else s.length&&B(C,s,E+1)}};return B(e,ge(A)?A.split("."):A,0),Q?g:g[0]}const Si={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Ri={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,A)=>e.score===A.score?e.idx<A.idx?-1:1:e.score<A.score?-1:1},Li={location:0,threshold:.6,distance:100},qi={useExtendedSearch:!1,getFn:Ki,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var z={...Ri,...Si,...Li,...qi};const Oi=/[^ ]+/g;function Yi(e=1,A=3){const g=new Map,Q=Math.pow(10,A);return{get(B){const o=B.match(Oi).length;if(g.has(o))return g.get(o);const s=1/Math.pow(o,.5*e),E=parseFloat(Math.round(s*Q)/Q);return g.set(o,E),E},clear(){g.clear()}}}class qg{constructor({getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){this.norm=Yi(g,3),this.getFn=A,this.isCreated=!1,this.setIndexRecords()}setSources(A=[]){this.docs=A}setIndexRecords(A=[]){this.records=A}setKeys(A=[]){this.keys=A,this._keysMap={},A.forEach((g,Q)=>{this._keysMap[g.id]=Q})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,ge(this.docs[0])?this.docs.forEach((A,g)=>{this._addString(A,g)}):this.docs.forEach((A,g)=>{this._addObject(A,g)}),this.norm.clear())}add(A){const g=this.size();ge(A)?this._addString(A,g):this._addObject(A,g)}removeAt(A){this.records.splice(A,1);for(let g=A,Q=this.size();g<Q;g+=1)this.records[g].i-=1}getValueForItemAtKeyId(A,g){return A[this._keysMap[g]]}size(){return this.records.length}_addString(A,g){if(!YA(A)||$t(A))return;let Q={v:A,i:g,n:this.norm.get(A)};this.records.push(Q)}_addObject(A,g){let Q={i:g,$:{}};this.keys.forEach((B,o)=>{let s=B.getFn?B.getFn(A):this.getFn(A,B.path);if(YA(s)){if(Ce(s)){let E=[];const i=[{nestedArrIndex:-1,value:s}];for(;i.length;){const{nestedArrIndex:C,value:a}=i.pop();if(YA(a))if(ge(a)&&!$t(a)){let I={v:a,i:C,n:this.norm.get(a)};E.push(I)}else Ce(a)&&a.forEach((I,l)=>{i.push({nestedArrIndex:l,value:I})})}Q.$[o]=E}else if(ge(s)&&!$t(s)){let E={v:s,n:this.norm.get(s)};Q.$[o]=E}}}),this.records.push(Q)}toJSON(){return{keys:this.keys,records:this.records}}}function vB(e,A,{getFn:g=z.getFn,fieldNormWeight:Q=z.fieldNormWeight}={}){const B=new qg({getFn:g,fieldNormWeight:Q});return B.setKeys(e.map(TB)),B.setSources(A),B.create(),B}function Ti(e,{getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){const{keys:Q,records:B}=e,o=new qg({getFn:A,fieldNormWeight:g});return o.setKeys(Q),o.setIndexRecords(B),o}function Ct(e,{errors:A=0,currentLocation:g=0,expectedLocation:Q=0,distance:B=z.distance,ignoreLocation:o=z.ignoreLocation}={}){const s=A/e.length;if(o)return s;const E=Math.abs(Q-g);return B?s+E/B:E?1:s}function vi(e=[],A=z.minMatchCharLength){let g=[],Q=-1,B=-1,o=0;for(let s=e.length;o<s;o+=1){let E=e[o];E&&Q===-1?Q=o:!E&&Q!==-1&&(B=o-1,B-Q+1>=A&&g.push([Q,B]),Q=-1)}return e[o-1]&&o-Q>=A&&g.push([Q,o-1]),g}const pe=32;function ji(e,A,g,{location:Q=z.location,distance:B=z.distance,threshold:o=z.threshold,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,includeMatches:i=z.includeMatches,ignoreLocation:C=z.ignoreLocation}={}){if(A.length>pe)throw new Error(Fi(pe));const a=A.length,I=e.length,l=Math.max(0,Math.min(Q,I));let r=o,n=l;const d=E>1||i,c=d?Array(I):[];let D;for(;(D=e.indexOf(A,n))>-1;){let f=Ct(A,{currentLocation:D,expectedLocation:l,distance:B,ignoreLocation:C});if(r=Math.min(f,r),n=D+a,d){let M=0;for(;M<a;)c[D+M]=1,M+=1}}n=-1;let N=[],h=1,m=a+I;const y=1<<a-1;for(let f=0;f<a;f+=1){let M=0,w=m;for(;M<w;)Ct(A,{errors:f,currentLocation:l+w,expectedLocation:l,distance:B,ignoreLocation:C})<=r?M=w:m=w,w=Math.floor((m-M)/2+M);m=w;let G=Math.max(1,l-w+1),p=s?I:Math.min(l+w,I)+a,U=Array(p+2);U[p+1]=(1<<f)-1;for(let J=p;J>=G;J-=1){let S=J-1,Y=g[e.charAt(S)];if(d&&(c[S]=+!!Y),U[J]=(U[J+1]<<1|1)&Y,f&&(U[J]|=(N[J+1]|N[J])<<1|1|N[J+1]),U[J]&y&&(h=Ct(A,{errors:f,currentLocation:S,expectedLocation:l,distance:B,ignoreLocation:C}),h<=r)){if(r=h,n=S,n<=l)break;G=Math.max(1,2*l-n)}}if(Ct(A,{errors:f+1,currentLocation:l,expectedLocation:l,distance:B,ignoreLocation:C})>r)break;N=U}const x={isMatch:n>=0,score:Math.max(.001,h)};if(d){const f=vi(c,E);f.length?i&&(x.indices=f):x.isMatch=!1}return x}function Hi(e){let A={};for(let g=0,Q=e.length;g<Q;g+=1){const B=e.charAt(g);A[B]=(A[B]||0)|1<<Q-g-1}return A}const Nt=String.prototype.normalize?(e=>e.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"")):(e=>e);class jB{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){if(this.options={location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a},A=i?A:A.toLowerCase(),A=C?Nt(A):A,this.pattern=A,this.chunks=[],!this.pattern.length)return;const I=(r,n)=>{this.chunks.push({pattern:r,alphabet:Hi(r),startIndex:n})},l=this.pattern.length;if(l>pe){let r=0;const n=l%pe,d=l-n;for(;r<d;)I(this.pattern.substr(r,pe),r),r+=pe;if(n){const c=l-pe;I(this.pattern.substr(c),c)}}else I(this.pattern,0)}searchIn(A){const{isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B}=this.options;if(A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern===A){let d={isMatch:!0,score:0};return B&&(d.indices=[[0,A.length-1]]),d}const{location:o,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,ignoreLocation:a}=this.options;let I=[],l=0,r=!1;this.chunks.forEach(({pattern:d,alphabet:c,startIndex:D})=>{const{isMatch:N,score:h,indices:m}=ji(A,d,c,{location:o+D,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,includeMatches:B,ignoreLocation:a});N&&(r=!0),l+=h,N&&m&&(I=[...I,...m])});let n={isMatch:r,score:r?l/this.chunks.length:1};return r&&B&&(n.indices=I),n}}class ce{constructor(A){this.pattern=A}static isMultiMatch(A){return MQ(A,this.multiRegex)}static isSingleMatch(A){return MQ(A,this.singleRegex)}search(){}}function MQ(e,A){const g=e.match(A);return g?g[1]:null}class Pi extends ce{constructor(A){super(A)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(A){const g=A===this.pattern;return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Wi extends ce{constructor(A){super(A)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(A){const Q=A.indexOf(this.pattern)===-1;return{isMatch:Q,score:Q?0:1,indices:[0,A.length-1]}}}class zi extends ce{constructor(A){super(A)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(A){const g=A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Vi extends ce{constructor(A){super(A)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(A){const g=!A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class Zi extends ce{constructor(A){super(A)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(A){const g=A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[A.length-this.pattern.length,A.length-1]}}}class Xi extends ce{constructor(A){super(A)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(A){const g=!A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class HB extends ce{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){super(A),this._bitapSearch=new jB(A,{location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(A){return this._bitapSearch.searchIn(A)}}class PB extends ce{constructor(A){super(A)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(A){let g=0,Q;const B=[],o=this.pattern.length;for(;(Q=A.indexOf(this.pattern,g))>-1;)g=Q+o,B.push([Q,g-1]);const s=!!B.length;return{isMatch:s,score:s?0:1,indices:B}}}const rg=[Pi,PB,zi,Vi,Xi,Zi,Wi,HB],yQ=rg.length,_i=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,$i="|";function Aa(e,A={}){return e.split($i).map(g=>{let Q=g.trim().split(_i).filter(o=>o&&!!o.trim()),B=[];for(let o=0,s=Q.length;o<s;o+=1){const E=Q[o];let i=!1,C=-1;for(;!i&&++C<yQ;){const a=rg[C];let I=a.isMultiMatch(E);I&&(B.push(new a(I,A)),i=!0)}if(!i)for(C=-1;++C<yQ;){const a=rg[C];let I=a.isSingleMatch(E);if(I){B.push(new a(I,A));break}}}return B})}const ea=new Set([HB.type,PB.type]);class ta{constructor(A,{isCaseSensitive:g=z.isCaseSensitive,ignoreDiacritics:Q=z.ignoreDiacritics,includeMatches:B=z.includeMatches,minMatchCharLength:o=z.minMatchCharLength,ignoreLocation:s=z.ignoreLocation,findAllMatches:E=z.findAllMatches,location:i=z.location,threshold:C=z.threshold,distance:a=z.distance}={}){this.query=null,this.options={isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B,minMatchCharLength:o,findAllMatches:E,ignoreLocation:s,location:i,threshold:C,distance:a},A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern=A,this.query=Aa(this.pattern,this.options)}static condition(A,g){return g.useExtendedSearch}searchIn(A){const g=this.query;if(!g)return{isMatch:!1,score:1};const{includeMatches:Q,isCaseSensitive:B,ignoreDiacritics:o}=this.options;A=B?A:A.toLowerCase(),A=o?Nt(A):A;let s=0,E=[],i=0;for(let C=0,a=g.length;C<a;C+=1){const I=g[C];E.length=0,s=0;for(let l=0,r=I.length;l<r;l+=1){const n=I[l],{isMatch:d,indices:c,score:D}=n.search(A);if(d){if(s+=1,i+=D,Q){const N=n.constructor.type;ea.has(N)?E=[...E,...c]:E.push(c)}}else{i=0,s=0,E.length=0;break}}if(s){let l={isMatch:!0,score:i/s};return Q&&(l.indices=E),l}}return{isMatch:!1,score:1}}}const Ig=[];function ga(...e){Ig.push(...e)}function ng(e,A){for(let g=0,Q=Ig.length;g<Q;g+=1){let B=Ig[g];if(B.condition(e,A))return new B(e,A)}return new jB(e,A)}const kt={AND:"$and",OR:"$or"},lg={PATH:"$path",PATTERN:"$val"},cg=e=>!!(e[kt.AND]||e[kt.OR]),Qa=e=>!!e[lg.PATH],Ba=e=>!Ce(e)&&OB(e)&&!cg(e),GQ=e=>({[kt.AND]:Object.keys(e).map(A=>({[A]:e[A]}))});function WB(e,A,{auto:g=!0}={}){const Q=B=>{let o=Object.keys(B);const s=Qa(B);if(!s&&o.length>1&&!cg(B))return Q(GQ(B));if(Ba(B)){const i=s?B[lg.PATH]:o[0],C=s?B[lg.PATTERN]:B[i];if(!ge(C))throw new Error(Gi(i));const a={keyId:ag(i),pattern:C};return g&&(a.searcher=ng(C,A)),a}let E={children:[],operator:o[0]};return o.forEach(i=>{const C=B[i];Ce(C)&&C.forEach(a=>{E.children.push(Q(a))})}),E};return cg(e)||(e=GQ(e)),Q(e)}function oa(e,{ignoreFieldNorm:A=z.ignoreFieldNorm}){e.forEach(g=>{let Q=1;g.matches.forEach(({key:B,norm:o,score:s})=>{const E=B?B.weight:null;Q*=Math.pow(s===0&&E?Number.EPSILON:s,(E||1)*(A?1:o))}),g.score=Q})}function sa(e,A){const g=e.matches;A.matches=[],YA(g)&&g.forEach(Q=>{if(!YA(Q.indices)||!Q.indices.length)return;const{indices:B,value:o}=Q;let s={indices:B,value:o};Q.key&&(s.key=Q.key.src),Q.idx>-1&&(s.refIndex=Q.idx),A.matches.push(s)})}function Ea(e,A){A.score=e.score}function Ca(e,A,{includeMatches:g=z.includeMatches,includeScore:Q=z.includeScore}={}){const B=[];return g&&B.push(sa),Q&&B.push(Ea),e.map(o=>{const{idx:s}=o,E={item:A[s],refIndex:s};return B.length&&B.forEach(i=>{i(o,E)}),E})}class de{constructor(A,g={},Q){this.options={...z,...g},this.options.useExtendedSearch,this._keyStore=new Ji(this.options.keys),this.setCollection(A,Q)}setCollection(A,g){if(this._docs=A,g&&!(g instanceof qg))throw new Error(yi);this._myIndex=g||vB(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(A){YA(A)&&(this._docs.push(A),this._myIndex.add(A))}remove(A=()=>!1){const g=[];for(let Q=0,B=this._docs.length;Q<B;Q+=1){const o=this._docs[Q];A(o,Q)&&(this.removeAt(Q),Q-=1,B-=1,g.push(o))}return g}removeAt(A){this._docs.splice(A,1),this._myIndex.removeAt(A)}getIndex(){return this._myIndex}search(A,{limit:g=-1}={}){const{includeMatches:Q,includeScore:B,shouldSort:o,sortFn:s,ignoreFieldNorm:E}=this.options;let i=ge(A)?ge(this._docs[0])?this._searchStringList(A):this._searchObjectList(A):this._searchLogical(A);return oa(i,{ignoreFieldNorm:E}),o&&i.sort(s),qB(g)&&g>-1&&(i=i.slice(0,g)),Ca(i,this._docs,{includeMatches:Q,includeScore:B})}_searchStringList(A){const g=ng(A,this.options),{records:Q}=this._myIndex,B=[];return Q.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=g.searchIn(o);i&&B.push({item:o,idx:s,matches:[{score:C,value:o,norm:E,indices:a}]})}),B}_searchLogical(A){const g=WB(A,this.options),Q=(E,i,C)=>{if(!E.children){const{keyId:I,searcher:l}=E,r=this._findMatches({key:this._keyStore.get(I),value:this._myIndex.getValueForItemAtKeyId(i,I),searcher:l});return r&&r.length?[{idx:C,item:i,matches:r}]:[]}const a=[];for(let I=0,l=E.children.length;I<l;I+=1){const r=E.children[I],n=Q(r,i,C);if(n.length)a.push(...n);else if(E.operator===kt.AND)return[]}return a},B=this._myIndex.records,o={},s=[];return B.forEach(({$:E,i})=>{if(YA(E)){let C=Q(g,E,i);C.length&&(o[i]||(o[i]={idx:i,item:E,matches:[]},s.push(o[i])),C.forEach(({matches:a})=>{o[i].matches.push(...a)}))}}),s}_searchObjectList(A){const g=ng(A,this.options),{keys:Q,records:B}=this._myIndex,o=[];return B.forEach(({$:s,i:E})=>{if(!YA(s))return;let i=[];Q.forEach((C,a)=>{i.push(...this._findMatches({key:C,value:s[a],searcher:g}))}),i.length&&o.push({idx:E,item:s,matches:i})}),o}_findMatches({key:A,value:g,searcher:Q}){if(!YA(g))return[];let B=[];if(Ce(g))g.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=Q.searchIn(o);i&&B.push({score:C,key:A,value:o,idx:s,norm:E,indices:a})});else{const{v:o,n:s}=g,{isMatch:E,score:i,indices:C}=Q.searchIn(o);E&&B.push({score:i,key:A,value:o,norm:s,indices:C})}return B}}de.version="7.1.0";de.createIndex=vB;de.parseIndex=Ti;de.config=z;de.parseQuery=WB;ga(ta);function ia(e){switch(e.split(".").pop()?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"go":case"rs":case"java":case"c":case"cpp":case"h":case"hpp":return WQ;case"json":case"yaml":case"yml":case"toml":return zo;case"md":case"txt":case"log":return Ft;case"png":case"jpg":case"jpeg":case"gif":case"svg":case"webp":return PQ;case"css":case"scss":case"sass":case"less":return Wo;case"html":case"xml":return Po;default:return le}}function aa(e,A){const g=A.get(e);return g?{added:{icon:Je,label:"Added",className:"text-green-500"},modified:{icon:gg,label:"Modified",className:"text-yellow-500"},untracked:{icon:Je,label:"Untracked",className:"text-blue-500"}}[g]||{icon:gg,label:"Modified",className:"text-yellow-500"}:null}function ra({files:e,changedFiles:A=[],query:g,selectedIndex:Q,onSelect:B,onEnterSelect:o,onClose:s}){const E=u.useMemo(()=>new Map(A?.map(a=>[a.path,a.status])||[]),[A]),i=u.useMemo(()=>new de(e.map(a=>({path:a,filename:a.split("/").pop()||a,normalized:a.replace(/[.\-_/]/g,"")})),{keys:[{name:"filename",weight:2},{name:"normalized",weight:1.5},{name:"path",weight:1}],threshold:.3,distance:200,ignoreLocation:!0,includeScore:!0}),[e]),C=u.useMemo(()=>{if(!g)return e.slice(0,20);const a=g.replace(/[.\-_/]/g,""),I=i.search(a);return I.sort((l,r)=>{const n=l.score??1,d=r.score??1;if(Math.abs(n-d)<.05){const D=E.has(l.item.path),N=E.has(r.item.path);if(D&&!N)return-1;if(!D&&N)return 1}return n-d}),I.slice(0,20).map(l=>l.item.path)},[i,g,e,E]);return u.useEffect(()=>{document.getElementById(`file-item-${Q}`)?.scrollIntoView({block:"nearest"})},[Q]),u.useEffect(()=>{o(C[Q])},[C,Q,o]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-file-mention-popup]")||s()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[s]),C.length===0?t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No files found"})}):t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>t.jsx("button",{type:"button",id:`file-item-${I}`,onMouseDown:l=>{l.preventDefault(),B(a)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===Q?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-2 w-full",children:[(()=>{const l=ia(a);return t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-muted-foreground"})})(),t.jsx("span",{className:"font-mono text-sm flex-1 truncate",children:a}),(()=>{const l=aa(a,E);return l&&t.jsx(l.icon,{className:`w-3.5 h-3.5 flex-shrink-0 ${l.className}`,title:l.label})})()]})},a))})}const zB="otto-preferences",ut={vimMode:!1,reasoningEnabled:!0};function Ia(){if(typeof window>"u")return ut;try{const e=window.localStorage.getItem(zB);if(e){const A=JSON.parse(e);return{...ut,...A}}}catch(e){console.warn("Failed to load preferences",e)}return ut}let ht=Ia();const dg=new Set;function na(){return ht}function la(){return ut}function ca(e){return dg.add(e),()=>dg.delete(e)}function da(){for(const e of dg)e()}function ua(e){if(ht={...ht,...e},typeof window<"u")try{window.localStorage.setItem(zB,JSON.stringify(ht))}catch(A){console.warn("Failed to persist preferences",A)}da()}function ot(){const e=u.useSyncExternalStore(ca,na,la),A=u.useCallback(g=>{ua(g)},[]);return u.useMemo(()=>({preferences:e,updatePreferences:A}),[e,A])}function Z(e){if(!e)return"Unknown error";if(typeof e=="string")return e;if(e&&typeof e=="object"){const A=e;if(A.error&&typeof A.error=="object"){const g=A.error;if(typeof g.message=="string")return g.message}if(typeof A.error=="string")return A.error;if(typeof A.message=="string")return A.message;try{return JSON.stringify(e)}catch{return"Error occurred (unable to parse)"}}return"Unknown error"}function ha(){const A=window.OTTO_SERVER_URL||qt;lA.setConfig({baseURL:A})}ha();function Ag(e){return{...e,title:e.title??null,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,lastActiveAt:typeof e.lastActiveAt=="string"?new Date(e.lastActiveAt).getTime():e.lastActiveAt}}function Da(e){return{...e,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,completedAt:e.completedAt?typeof e.completedAt=="string"?new Date(e.completedAt).getTime():e.completedAt:null}}class wa{get baseUrl(){const A=window;return A.OTTO_SERVER_URL?A.OTTO_SERVER_URL:qt}async getSessions(){const A=await uC();if(A.error)throw new Error(Z(A.error));return(A.data||[]).map(Ag)}async createSession(A){const g=await hC({body:A});if(g.error)throw new Error(Z(g.error));if(!g.data)throw new Error("No data returned from create session");return Ag(g.data)}async updateSession(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const o=await Q.json().catch(()=>({error:"Failed to update session"}));throw new Error(Z(o))}const B=await Q.json();return Ag(B)}async deleteSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to delete session"}));throw new Error(Z(Q))}return await g.json()}async abortSession(A){const g=await DC({path:{sessionId:A}});if(g.error)throw new Error(Z(g.error));return g.data}async abortMessage(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/abort`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:g})});if(!B.ok)throw new Error("Failed to abort message");return B.json()}async getQueueState(A){const g=this.baseUrl,Q=await fetch(`${g}/v1/sessions/${A}/queue`);if(!Q.ok)throw new Error("Failed to get queue state");return Q.json()}async removeFromQueue(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/queue/${g}`,{method:"DELETE"});if(!B.ok)throw new Error("Failed to remove from queue");return B.json()}async getMessages(A){const g=await wC({path:{id:A}});if(g.error)throw new Error(Z(g.error));return(g.data||[]).map(Da)}async sendMessage(A,g){const Q=await pC({path:{id:A},body:g});if(Q.error)throw new Error(Z(Q.error));return Q.data}getStreamUrl(A){return`${this.baseUrl}/v1/sessions/${A}/stream`}async getConfig(){const A=await mC();if(A.error)throw new Error(Z(A.error));return A.data}async getModels(A){const g=await xC({path:{provider:A}});if(g.error)throw new Error(Z(g.error));return g.data}async getAllModels(){const A=await fetch(`${this.baseUrl}/v1/config/models`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to fetch models"}));throw new Error(Z(g))}return await A.json()}async updateDefaults(A){const g=await fetch(`${this.baseUrl}/v1/config/defaults`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to update defaults"}));throw new Error(Z(Q))}return await g.json()}async getGitStatus(){const A=await NC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async getGitDiff(A,g=!1){const Q=await kC({query:{file:A,staged:g?"true":"false"}});if(Q.error)throw new Error(Z(Q.error));return Q.data?.data}async generateCommitMessage(A){const g=await bC({body:A?{sessionId:A}:{}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async stageFiles(A){const g=await yC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async unstageFiles(A){const g=await GC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async restoreFiles(A){const g=await JC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async deleteFiles(A){const g=await KC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async commitChanges(A){const g=await FC({body:{message:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async getGitBranch(){const A=await MC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async pushCommits(){const A=await UC({body:{}});if(A.error)throw new Error(Z(A.error));return A.data?.data}async listFiles(){const A=await fC();if(A.error)throw new Error(Z(A.error));return A.data}async getSessionFiles(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/files`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to fetch session files"}));throw new Error(Z(Q))}return await g.json()}async createBranch(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/branch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create branch"}));throw new Error(Z(B))}return await Q.json()}async listBranches(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/branches`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to list branches"}));throw new Error(Z(Q))}return await g.json()}async getParentSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/parent`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to get parent session"}));throw new Error(Z(Q))}return await g.json()}async getSetuBalance(){try{const A=await fetch(`${this.baseUrl}/v1/setu/balance`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():null}catch{return null}}async getSetuWallet(){try{const A=await fetch(`${this.baseUrl}/v1/setu/wallet`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():{configured:!1}}catch{return{configured:!1}}}async getSetuUsdcBalance(A="mainnet"){try{const g=await fetch(`${this.baseUrl}/v1/setu/usdc-balance?network=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async getShareStatus(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{shared:!1}}async shareSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to share session"}));throw new Error(Z(Q))}return await g.json()}async syncSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"PUT",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to sync session"}));throw new Error(Z(Q))}return await g.json()}async approveToolCall(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:g,approved:Q})});if(!B.ok)throw new Error("Failed to send tool approval");return await B.json()}async getPendingApprovals(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval/pending`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{ok:!1,pending:[]}}async getPolarTopupEstimate(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/estimate?amount=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async createPolarCheckout(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/polar`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:A,successUrl:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create checkout"}));throw new Error(Z(B))}return await Q.json()}async selectTopupMethod(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/select`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,method:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to select topup method"}));throw new Error(Z(B))}return await Q.json()}async cancelTopup(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,reason:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to cancel topup"}));throw new Error(Z(B))}return await Q.json()}async getPendingTopup(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/pending?sessionId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{hasPending:!1}}catch{return{hasPending:!1}}}async getPolarTopupStatus(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/status?checkoutId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async retryMessage(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/messages/${g}/retry`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to retry message"}));throw new Error(Z(B))}return await Q.json()}async getAuthStatus(){const A=await fetch(`${this.baseUrl}/v1/auth/status`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to get auth status"}));throw new Error(Z(g))}return await A.json()}async setupSetuWallet(){const A=await fetch(`${this.baseUrl}/v1/auth/setu/setup`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to setup wallet"}));throw new Error(Z(g))}return await A.json()}async importSetuWallet(A){const g=await fetch(`${this.baseUrl}/v1/auth/setu/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({privateKey:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to import wallet"}));throw new Error(Z(Q))}return await g.json()}async addProvider(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to add provider"}));throw new Error(Z(B))}return await Q.json()}async removeProvider(A){const g=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to remove provider"}));throw new Error(Z(Q))}return await g.json()}async completeOnboarding(){const A=await fetch(`${this.baseUrl}/v1/auth/onboarding/complete`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to complete onboarding"}));throw new Error(Z(g))}return await A.json()}getOAuthStartUrl(A,g){const Q=`${this.baseUrl}/v1/auth/${A}/oauth/start`;return g?`${Q}?mode=${g}`:Q}async getOAuthUrl(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to get OAuth URL"}));throw new Error(Z(B))}return await Q.json()}async exchangeOAuthCode(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g,sessionId:Q})});if(!B.ok){const o=await B.json().catch(()=>({error:"Failed to exchange OAuth code"}));throw new Error(Z(o))}return await B.json()}async startCopilotDeviceFlow(){const A=await fetch(`${this.baseUrl}/v1/auth/copilot/device/start`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to start Copilot device flow"}));throw new Error(Z(g))}return await A.json()}async pollCopilotDeviceFlow(A){const g=await fetch(`${this.baseUrl}/v1/auth/copilot/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Poll failed"}));throw new Error(Z(Q))}return await g.json()}}const T=new wa;function Og(e){const{data:A,isLoading:g,error:Q}=PA({queryKey:["share-status",e],queryFn:()=>T.getShareStatus(e),enabled:!!e,staleTime:3e4});return{data:A,isLoading:g,error:Q}}const VB=[{id:"models",label:"/models",description:"Open model selector",icon:Ke},{id:"agents",label:"/agents",description:"Open agent selector",icon:fe},{id:"new",label:"/new",description:"Create new session",icon:Je},{id:"stop",label:"/stop",description:"Stop current generation",icon:zQ},{id:"help",label:"/help",description:"Show keyboard shortcuts and help",icon:VQ},{id:"vim",label:"/vim",description:e=>e.vimModeEnabled?"Disable Vim mode":"Enable Vim mode",icon:Vo},{id:"reasoning",label:"/reasoning",description:e=>e.reasoningEnabled?"Disable extended thinking":"Enable extended thinking",icon:Ng},{id:"stage",label:"/stage",description:"Stage all changes (git add -A)",icon:HA},{id:"commit",label:"/commit",description:"Commit staged changes",icon:XA},{id:"compact",label:"/compact",description:"Compact conversation to reduce context size",icon:Zo},{id:"branch",label:"/branch",description:"Branch session from last message",icon:Xo},{id:"delete",label:"/delete",description:"Delete current session",icon:kg},{id:"share",label:"/share",description:"Share session publicly",icon:Mg},{id:"sync",label:"/sync",description:"Sync new messages to shared session",icon:TA}];function ZB(e,A){return typeof e.description=="function"?e.description(A):e.description}function pa(e,A){const g=VB.filter(o=>!(o.id==="share"&&A.isShared||o.id==="sync"&&!A.isShared));if(!e)return g;const Q=e.toLowerCase(),B=[];for(const o of g){const s=ZB(o,A),E=o.label.toLowerCase().includes(Q),i=s.toLowerCase().includes(Q);if(E||i){const C=E?10:5;B.push({...o,matchScore:C})}}return B.sort((o,s)=>{const E=s.matchScore-o.matchScore;return E!==0?E:o.label.localeCompare(s.label)})}function ma({query:e,selectedIndex:A,onSelect:g,onEnterSelect:Q,onClose:B,sessionId:o}){const{preferences:s}=ot(),{data:E}=Og(o),i=u.useMemo(()=>({vimModeEnabled:s.vimMode,reasoningEnabled:s.reasoningEnabled,isShared:E?.shared}),[s.vimMode,s.reasoningEnabled,E?.shared]),C=u.useMemo(()=>pa(e,i),[e,i]);return u.useEffect(()=>{document.getElementById(`command-item-${A}`)?.scrollIntoView({block:"nearest"})},[A]),u.useEffect(()=>{Q(C[A]?.id)},[C,A,Q]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-command-popup]")||B()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[B]),C.length===0?t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No commands found"})}):t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>{const l=a.icon;return t.jsx("button",{type:"button",id:`command-item-${I}`,onMouseDown:r=>{r.preventDefault(),g(a.id)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===A?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-3 w-full",children:[t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-primary"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-mono text-sm font-medium text-foreground",children:a.label}),t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ZB(a,i)})]})]})},a.id)})})}const xa={sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-xl","2xl":"max-w-2xl"};function qe({isOpen:e,onClose:A,title:g,children:Q,showCloseButton:B=!0,closeOnBackdropClick:o=!0,closeOnEscape:s=!0,maxWidth:E="md"}){if(u.useEffect(()=>{if(!e||!s)return;const C=a=>{const I=a.target,l=I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable;(a.key==="Escape"||a.key==="q"&&!l)&&(a.preventDefault(),a.stopPropagation(),A())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,s,A]),u.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),!e)return null;const i=C=>{o&&C.target===C.currentTarget&&A()};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] cursor-default",onClick:i,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&i(C)},"aria-label":"Close modal"}),t.jsx("div",{className:`fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[9999] w-full ${xa[E]} px-4`,children:t.jsxs("div",{className:"bg-background border border-border rounded-lg shadow-lg",children:[(g||B)&&t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[g&&t.jsx("div",{className:"text-lg font-semibold text-foreground",children:g}),B&&t.jsx("button",{type:"button",onClick:A,className:"text-muted-foreground hover:text-foreground transition-colors ml-auto","aria-label":"Close",children:t.jsx(MA,{className:"h-5 w-5"})})]}),t.jsx("div",{className:"p-6",children:Q})]})})]})}const fa=[{keys:["Ctrl","H"],description:"Navigate to left sidebar (sessions)",category:"Navigation"},{keys:["Ctrl","L"],description:"Navigate to right sidebar (git)",category:"Navigation"},{keys:["Ctrl","/"],description:"Toggle left sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","\\"],description:"Toggle right sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","N"],description:"Create new session",category:"Navigation"},{keys:["ESC"],description:"Close sidebar and return to center",category:"Navigation"},{keys:["J"],description:"Navigate to next item (in focused list)",category:"List Navigation"},{keys:["K"],description:"Navigate to previous item (in focused list)",category:"List Navigation"},{keys:["Enter"],description:"Select focused item and return to input",category:"List Navigation"},{keys:["Space"],description:"Toggle stage/unstage for focused file (git panel)",category:"Git Operations"},{keys:["A"],description:"Stage all unstaged files",category:"Git Operations"},{keys:["U"],description:"Unstage all staged files",category:"Git Operations"},{keys:["C"],description:"Open commit modal (if files are staged)",category:"Git Operations"},{keys:["Tab"],description:"Toggle plan mode",category:"Chat"},{keys:["Enter"],description:"Send message",category:"Chat"},{keys:["Shift","Enter"],description:"New line in message",category:"Chat"},{keys:["@"],description:"Mention file (opens file picker)",category:"Chat"},{keys:["/"],description:"Slash command (opens command menu)",category:"Chat"}],Na=[{keys:["i"],description:"Enter insert mode at cursor (vim mode)",category:"Vim Mode"},{keys:["a"],description:"Enter insert mode after cursor (vim mode)",category:"Vim Mode"},{keys:["I"],description:"Enter insert mode at line start (vim mode)",category:"Vim Mode"},{keys:["A"],description:"Enter insert mode at line end (vim mode)",category:"Vim Mode"},{keys:["o"],description:"New line below and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["O"],description:"New line above and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["ESC"],description:"Return to normal mode (vim mode)",category:"Vim Mode"},{keys:["Enter"],description:"Send message in normal mode (vim mode)",category:"Vim Mode"},{keys:["w"],description:"Jump to next word start (vim mode)",category:"Vim Mode"},{keys:["e"],description:"Jump to next word end (vim mode)",category:"Vim Mode"},{keys:["b"],description:"Jump to previous word start (vim mode)",category:"Vim Mode"},{keys:["x"],description:"Delete character under cursor (vim mode)",category:"Vim Mode"},{keys:["s"],description:"Delete character and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["S"],description:"Delete line and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["f","{char}"],description:"Find and jump to next character on line (vim mode)",category:"Vim Mode"},{keys:["d","d"],description:"Delete current line (vim mode)",category:"Vim Mode"},{keys:["0"],description:"Jump to line start (vim mode)",category:"Vim Mode"},{keys:["$"],description:"Jump to line end (vim mode)",category:"Vim Mode"}],ka=[{command:"/models",description:"Open model selector"},{command:"/agents",description:"Open agent selector"},{command:"/new",description:"Create new session"},{command:"/help",description:"Show keyboard shortcuts and help (this modal)"},{command:"/compact",description:"Compact conversation to reduce context size"}];function Ma(e){const A={};for(const g of e)A[g.category]||(A[g.category]=[]),A[g.category].push(g);return A}function ya({isOpen:e,onClose:A}){const g=[...fa,...Na],Q=Ma(g),B=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{e?(o.current=document.activeElement,o.current&&o.current.blur()):o.current&&(o.current.focus(),o.current=null)},[e]),u.useEffect(()=>{if(!e)return;const s=E=>{const i=E.target;if(!(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable))if(E.key==="j"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:100,behavior:"smooth"})}else if(E.key==="k"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:-100,behavior:"smooth"})}else E.key==="Enter"&&(E.preventDefault(),A())};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,A]),t.jsx(qe,{isOpen:e,onClose:A,title:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(VQ,{className:"w-5 h-5"}),t.jsx("span",{children:"Keyboard Shortcuts & Help"})]}),maxWidth:"2xl",closeOnEscape:!0,closeOnBackdropClick:!0,children:t.jsxs("div",{ref:B,className:"space-y-6 max-h-[70vh] overflow-y-auto",children:[Object.entries(Q).map(([s,E])=>t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),s]}),t.jsx("div",{className:"space-y-2",children:E.map((i,C)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:i.description}),t.jsx("div",{className:"flex items-center gap-1",children:i.keys.map(a=>t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:a}),i.keys.indexOf(a)<i.keys.length-1&&t.jsx("span",{className:"text-muted-foreground",children:"+"})]},a))})]},`${s}-${i.description}`))})]},s)),t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),"Slash Commands"]}),t.jsx("div",{className:"space-y-2",children:ka.map((s,E)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:s.description}),t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:s.command})]},s.command))})]}),t.jsx("div",{className:"pt-4 border-t border-border",children:t.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.jsx("strong",{children:"Tip:"})," Shortcuts are disabled when typing in input fields. Press ",t.jsx("kbd",{className:"text-xs",children:"ESC"})," to close popups and return focus to chat input."]})})]})})}const Ga=`<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
31
31
  <path d="M26.9568 9.88184H22.1265L30.7753 31.7848H35.4917L26.9568 9.88184ZM13.028 9.88184L4.4917 31.7848H9.32203L11.2305 27.1793H20.2166L22.0126 31.6724H26.8444L18.0832 9.88184H13.028ZM12.5783 23.1361L15.4987 15.3853L18.5315 23.1361H12.5783Z" fill="currentColor"/>
32
32
  </svg>`,Fa=`<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
33
33
  <path d="M32.8377 17.282C33.2127 16.25 33.3072 15.218 33.2127 14.1875C33.1197 13.1571 32.7447 12.1251 32.2752 11.1876C31.4322 9.78209 30.2127 8.6571 28.8072 8.0001C27.3072 7.34461 25.7127 7.15711 24.1197 7.53211C23.3698 6.78212 22.5253 6.12512 21.5878 5.65713C20.6503 5.18913 19.5253 5.00013 18.4948 5.00013C16.8851 4.99074 15.3125 5.48246 13.9948 6.40712C12.6824 7.34311 11.7449 8.6571 11.2754 10.1571C10.1504 10.4376 9.21289 10.9071 8.27539 11.4696C7.4324 12.1251 6.77541 12.9696 6.21291 13.8126C5.36992 15.2195 5.08792 16.8125 5.27542 18.407C5.46399 19.9968 6.11605 21.496 7.1504 22.718C6.79608 23.7086 6.66795 24.7659 6.77541 25.8124C6.86991 26.8444 7.2449 27.8749 7.7129 28.8124C8.55739 30.2194 9.77538 31.3444 11.1824 31.9999C12.6824 32.6569 14.2753 32.8444 15.8698 32.4694C16.6198 33.2194 17.4628 33.8749 18.4003 34.3444C19.3378 34.8139 20.4628 34.9999 21.4948 34.9999C23.1043 35.0097 24.6769 34.5185 25.9947 33.5944C27.3072 32.6569 28.2447 31.3444 28.7127 29.8444C29.7719 29.6432 30.7682 29.1934 31.6197 28.5319C32.4627 27.8749 33.2127 27.1249 33.6822 26.1874C34.5251 24.7819 34.8071 23.1875 34.6196 21.5945C34.4322 20 33.8697 18.5015 32.8377 17.282ZM21.5878 33.0304C20.0878 33.0304 18.9628 32.5609 17.9323 31.7179C17.9323 31.7179 18.0253 31.6234 18.1198 31.6234L24.1197 28.1554C24.2862 28.0803 24.4196 27.9469 24.4947 27.7804C24.5698 27.636 24.6021 27.4731 24.5877 27.3109V18.875L27.1197 20.375V27.3124C27.1455 28.0547 27.0215 28.7945 26.755 29.4878C26.4885 30.181 26.085 30.8134 25.5687 31.3473C25.0523 31.8811 24.4337 32.3054 23.7497 32.5949C23.0658 32.8843 22.3305 33.0314 21.5878 33.0304ZM9.49488 27.8749C8.83789 26.7499 8.55739 25.4374 8.83789 24.125C8.83789 24.125 8.93239 24.2195 9.02539 24.2195L15.0253 27.6874C15.1693 27.7638 15.3325 27.7966 15.4948 27.7819C15.6823 27.7819 15.8698 27.7819 15.9628 27.6874L23.2753 23.4695V26.3749L17.1823 29.9374C16.5506 30.3042 15.8527 30.5427 15.1287 30.6393C14.4046 30.7358 13.6686 30.6884 12.9629 30.4999C11.4629 30.1249 10.2449 29.1874 9.49488 27.8749ZM7.9004 14.8445C8.56239 13.7234 9.58826 12.8627 10.8074 12.4056V19.532C10.8074 19.718 10.8074 19.907 10.9004 20C10.9755 20.1665 11.1089 20.2998 11.2754 20.375L18.5878 24.5944L16.0573 26.0944L10.0574 22.625C9.41842 22.2639 8.85742 21.7797 8.40684 21.2004C7.95627 20.6211 7.62506 19.9582 7.4324 19.25C7.05741 17.8445 7.1504 16.157 7.9004 14.8445ZM28.6197 19.625L21.3073 15.407L23.8377 13.9071L29.8377 17.375C30.7752 17.9375 31.5252 18.6875 31.9947 19.625C32.4642 20.5625 32.7447 21.5945 32.6502 22.7195C32.5603 23.7755 32.1699 24.7837 31.5252 25.6249C30.8697 26.4694 30.0252 27.1249 28.9947 27.4999V20.375C28.9947 20.1875 28.9947 20 28.9002 19.907C28.9002 19.907 28.8072 19.718 28.6197 19.625ZM31.1502 15.875C31.1502 15.875 31.0572 15.782 30.9627 15.782L24.9627 12.3126C24.7752 12.2196 24.6822 12.2196 24.4947 12.2196C24.3072 12.2196 24.1197 12.2196 24.0252 12.3126L16.7128 16.532V13.6251L22.8073 10.0626C23.7448 9.50009 24.7752 9.31259 25.9002 9.31259C26.9322 9.31259 27.9627 9.68759 28.9002 10.3446C29.7447 11.0001 30.4947 11.8446 30.8697 12.7821C31.2447 13.7196 31.3377 14.8445 31.1502 15.875ZM15.4003 21.125L12.8699 19.625V12.5946C12.8699 11.5626 13.1503 10.4376 13.7128 9.59459C14.2753 8.6571 15.1198 8.0001 16.0573 7.53211C17.0127 7.05249 18.0956 6.88812 19.1503 7.06261C20.1823 7.15711 21.2128 7.62511 22.0573 8.2821C22.0573 8.2821 21.9628 8.3751 21.8698 8.3751L15.8698 11.8446C15.7033 11.9197 15.57 12.0531 15.4948 12.2196C15.4003 12.4071 15.4003 12.5001 15.4003 12.6876V21.125ZM16.7128 18.125L19.9948 16.25L23.2753 18.125V21.875L19.9948 23.75L16.7128 21.875V18.125Z" fill="currentColor"/>
@@ -79,7 +79,7 @@ ${d.slice(c)}`;return Q(D),setTimeout(()=>{r.setSelectionRange(c,c)},0),!0}if(s=
79
79
  `,c-1)+1;if(D>0){const N=c-D,h=D-1,m=d.lastIndexOf(`
80
80
  `,h-1)+1,y=h-m,x=m+Math.min(N,y);r.setSelectionRange(x,x)}return!0}return!1},[s,A,g,Q,i,C,a]);return{vimMode:B,setVimMode:o,handleVimNormalMode:I}}function va(){const[e,A]=u.useState(!1),[g,Q]=u.useState(""),[B,o]=u.useState(0),[s,E]=u.useState(),i=u.useCallback((I,l,r)=>{const n=l.current;if(!n)return;const d=n.value,c=n.selectionStart,N=d.slice(0,c).match(/@(\S*)$/);if(!N)return;const h=c-N[0].length,m=`${d.slice(0,h)}@${I} ${d.slice(c)}`;r(m),A(!1),setTimeout(()=>{const y=h+I.length+2;n.setSelectionRange(y,y),n.focus()},0)},[]),C=u.useCallback(I=>{E(I)},[]),a=u.useCallback((I,l)=>{const n=I.slice(0,l).match(/@(\S*)$/);n?(A(!0),Q(n[1]),o(0)):A(!1)},[]);return{showFileMention:e,mentionQuery:g,mentionSelectedIndex:B,currentFileToSelect:s,setShowFileMention:A,setMentionQuery:Q,setMentionSelectedIndex:o,setCurrentFileToSelect:E,handleFileSelect:i,handleEnterSelect:C,checkForMention:a}}function ja({onCommand:e,updatePreferences:A,vimModeEnabled:g,reasoningEnabled:Q,textareaRef:B,setMessage:o,setShowShortcutsModal:s,sessionId:E}){const[i,C]=u.useState(!1),[a,I]=u.useState(""),[l,r]=u.useState(0),[n,d]=u.useState(),c=u.useCallback(async h=>{const m=()=>{o(""),C(!1),B.current&&(B.current.style.height="auto"),B.current?.focus()};if(h==="help"){s(!0),m();return}if(h==="vim"){A({vimMode:!g}),m();return}if(h==="reasoning"){A({reasoningEnabled:!Q}),m();return}if(h==="stop"){if(E)try{await T.abortSession(E)}catch(y){console.error("Failed to stop generation:",y)}m();return}e&&e(h),m()},[e,g,Q,A,B,o,s,E]),D=u.useCallback(h=>{d(h)},[]),N=u.useCallback(h=>{h.startsWith("/")&&!h.includes(" ")?(C(!0),I(h.slice(1)),r(0)):C(!1)},[]);return{showCommandSuggestions:i,commandQuery:a,commandSelectedIndex:l,currentCommandToSelect:n,setShowCommandSuggestions:C,setCommandQuery:I,setCommandSelectedIndex:r,setCurrentCommandToSelect:d,handleCommandSelect:c,handleCommandEnterSelect:D,checkForCommand:N}}function Ha(e){return A=>{const{showFileMention:g,showCommandSuggestions:Q,mentionSelectedIndex:B,commandSelectedIndex:o,currentFileToSelect:s,currentCommandToSelect:E,isPlanMode:i,vimModeEnabled:C,vimMode:a,setMentionSelectedIndex:I,setCommandSelectedIndex:l,setShowFileMention:r,setShowCommandSuggestions:n,setIsPlanMode:d,setVimMode:c,handleFileSelect:D,handleCommandSelect:N,handleSend:h,handleVimNormalMode:m,onPlanModeToggle:y}=e;if(Q){const x=VB.length;A.key==="ArrowDown"||A.ctrlKey&&A.key==="j"?(A.preventDefault(),l((o+1)%x)):A.key==="ArrowUp"||A.ctrlKey&&A.key==="k"?(A.preventDefault(),l((o-1+x)%x)):A.key==="Enter"?(A.preventDefault(),E&&N(E)):A.key==="Escape"&&(A.preventDefault(),n(!1));return}if(g){A.key==="ArrowDown"||A.ctrlKey&&A.key==="j"?(A.preventDefault(),I((B+1)%20)):A.key==="ArrowUp"||A.ctrlKey&&A.key==="k"?(A.preventDefault(),I((B-1+20)%20)):A.key==="Enter"?(A.preventDefault(),s&&D(s)):A.key==="Escape"&&(A.preventDefault(),r(!1),C&&c("normal"));return}if(!(C&&a==="normal"&&m(A))){if(C&&a==="insert"&&A.key==="Escape"){A.preventDefault(),c("normal");return}if(A.key==="Tab"){A.preventDefault();const x=!i;d(x),y?.(x)}else A.key==="Enter"&&!A.shiftKey&&(!C||a==="normal")&&(A.preventDefault(),h())}}}const sA=UA(e=>({balance:null,usdcBalance:null,network:"mainnet",isPaymentPending:!1,lastPaymentAmount:null,walletAddress:null,isLoading:!1,isTopupModalOpen:!1,setBalance:A=>e({balance:A}),setUsdcBalance:A=>e({usdcBalance:A}),setNetwork:A=>e({network:A}),setPaymentPending:A=>e({isPaymentPending:A}),setLastPaymentAmount:A=>e({lastPaymentAmount:A}),setWalletAddress:A=>e({walletAddress:A}),setLoading:A=>e({isLoading:A}),openTopupModal:()=>e({isTopupModalOpen:!0}),closeTopupModal:()=>e({isTopupModalOpen:!1})})),Pa=u.memo(u.forwardRef(function({onSend:A,onCommand:g,disabled:Q,onConfigClick:B,onPlanModeToggle:o,isPlanMode:s,reasoningEnabled:E,sessionId:i,images:C=[],documents:a=[],onFileRemove:I,isDragging:l=!1,onPaste:r,visionEnabled:n=!1,modelName:d,providerName:c,authType:D,researchContexts:N=[],onResearchContextRemove:h,onRefreshBalance:m,isBalanceLoading:y=!1,onModelInfoClick:x},f){const[M,w]=u.useState(""),[G,p]=u.useState(s||!1),[U,k]=u.useState(!1),J=u.useRef(null),{data:S,isLoading:Y}=Ya(),{preferences:q,updatePreferences:R}=ot(),O=S?.files||[],K=S?.changedFiles||[],v=sA(gA=>gA.balance),V=c==="setu",_=u.useRef(()=>{}),{showFileMention:X,mentionQuery:iA,mentionSelectedIndex:mA,currentFileToSelect:j,setShowFileMention:L,setMentionSelectedIndex:AA,setCurrentFileToSelect:EA,handleFileSelect:NA,handleEnterSelect:DA,checkForMention:yA}=va(),{showCommandSuggestions:ue,commandQuery:Te,commandSelectedIndex:oe,currentCommandToSelect:Ie,setShowCommandSuggestions:KA,setCommandSelectedIndex:he,setCurrentCommandToSelect:zA,handleCommandSelect:De,handleCommandEnterSelect:H,checkForCommand:oA}=ja({onCommand:g,updatePreferences:R,vimModeEnabled:q.vimMode,reasoningEnabled:q.reasoningEnabled,textareaRef:J,setMessage:w,setShowShortcutsModal:k,sessionId:i}),{vimMode:eA,setVimMode:GA,handleVimNormalMode:ee}=Ta({enabled:q.vimMode,onSend:()=>_.current(),textareaRef:J,setMessage:w});u.useEffect(()=>{J.current?.focus()},[]),u.useEffect(()=>{s!==void 0&&p(s)},[s]),u.useImperativeHandle(f,()=>({focus:()=>{J.current?.focus()},setValue:gA=>{w(gA),J.current?.focus()}}));const Ge=u.useCallback(()=>{const gA=J.current;gA&&(gA.style.height="auto",gA.style.height=`${gA.scrollHeight}px`)},[]);u.useEffect(()=>{Ge()},[Ge,M]);const OA=u.useCallback(()=>{L(!1),EA(void 0)},[L,EA]),ve=u.useCallback(()=>{KA(!1),zA(void 0)},[KA,zA]),je=u.useCallback(gA=>{NA(gA,J,w)},[NA]),we=u.useCallback(()=>{!M.trim()||Q||(A(M),w(""),L(!1),KA(!1),EA(void 0),zA(void 0),J.current&&(J.current.style.height="auto"),q.vimMode&&GA("normal"),J.current?.focus())},[M,Q,A,q.vimMode,L,KA,EA,zA,GA]);u.useEffect(()=>{_.current=we},[we]);const zt=u.useCallback(gA=>{if(q.vimMode&&eA==="normal")return;const se=gA.target.value;w(se),oA(se),se.startsWith("/")&&!se.includes(" ")?(L(!1),EA(void 0)):(KA(!1),zA(void 0),yA(se,gA.target.selectionStart))},[q.vimMode,eA,oA,L,EA,KA,zA,yA]),Fe=u.useMemo(()=>Ha({showFileMention:X,showCommandSuggestions:ue,mentionSelectedIndex:mA,commandSelectedIndex:oe,currentFileToSelect:j,currentCommandToSelect:Ie,isPlanMode:G,vimModeEnabled:q.vimMode,vimMode:eA,setMentionSelectedIndex:AA,setCommandSelectedIndex:he,setShowFileMention:L,setShowCommandSuggestions:KA,setIsPlanMode:p,setVimMode:GA,handleFileSelect:je,handleCommandSelect:De,handleSend:we,handleVimNormalMode:ee,onPlanModeToggle:o}),[X,ue,mA,oe,j,Ie,G,q.vimMode,eA,AA,he,L,KA,GA,je,De,we,ee,o]);u.useEffect(()=>{q.vimMode||GA("insert")},[q.vimMode,GA]);const Vt=u.useCallback(gA=>{r?.(gA)},[r]),P=C.length>0,dA=a.length>0,FA=P||dA;return t.jsxs(t.Fragment,{children:[l&&t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm pointer-events-none",children:t.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 rounded-2xl bg-card border-2 border-dashed border-primary/50",children:[t.jsx("div",{className:"p-4 rounded-full bg-primary/10",children:t.jsx(le,{className:"w-12 h-12 text-primary"})}),t.jsxs("div",{className:"text-center",children:[t.jsx("p",{className:"text-lg font-medium text-foreground",children:"Drop files here"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"Images, PDF, Markdown, Text up to 10MB"})]})]})}),t.jsx("div",{className:"absolute bottom-0 left-0 right-0 pt-16 pb-6 md:pb-8 px-2 md:px-4 bg-gradient-to-t from-background via-background to-transparent pointer-events-none z-20 safe-area-inset-bottom",children:t.jsxs("div",{className:"max-w-3xl mx-auto pointer-events-auto mb-2 md:mb-0 relative",children:[q.vimMode&&eA==="normal"&&t.jsx("div",{className:"absolute -top-6 right-0 px-2 py-0.5 text-xs font-mono font-semibold bg-amber-500/90 text-white rounded shadow-sm",children:"NORMAL"}),q.vimMode&&eA==="insert"&&t.jsx("div",{className:"absolute -top-6 right-0 px-2 py-0.5 text-xs font-mono font-semibold bg-green-500/90 text-white rounded shadow-sm",children:"INSERT"}),t.jsxs("div",{className:`relative flex flex-col rounded-3xl p-1 transition-all touch-manipulation ${G?"bg-slate-100 dark:bg-slate-900/40 border border-slate-300 dark:border-slate-700 focus-within:border-slate-400 dark:focus-within:border-slate-600 focus-within:ring-1 focus-within:ring-slate-300 dark:focus-within:ring-slate-700":"bg-card border border-border focus-within:border-primary/60 focus-within:ring-1 focus-within:ring-primary/40"}`,children:[FA&&t.jsxs("div",{className:"flex flex-wrap gap-2 px-3 pt-2 pb-1",children:[C.map(gA=>t.jsxs("div",{className:"relative group w-12 h-12 rounded-lg overflow-hidden bg-muted",children:[t.jsx("img",{src:gA.preview,alt:"Attachment",className:"w-full h-full object-cover"}),t.jsx("button",{type:"button",onClick:()=>I?.(gA.id),className:"absolute top-0 right-0 p-0.5 bg-black/60 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity",children:t.jsx(MA,{className:"w-3 h-3 text-white"})})]},gA.id)),a.map(gA=>t.jsxs("div",{className:"relative group flex items-center gap-2 px-3 py-2 rounded-lg bg-muted max-w-[200px]",children:[gA.type==="pdf"?t.jsx(le,{className:"w-4 h-4 text-red-500 flex-shrink-0"}):t.jsx(Ft,{className:"w-4 h-4 text-blue-500 flex-shrink-0"}),t.jsx("span",{className:"text-xs truncate",children:gA.name}),t.jsx("button",{type:"button",onClick:()=>I?.(gA.id),className:"absolute top-0 right-0 p-0.5 bg-black/60 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity",children:t.jsx(MA,{className:"w-3 h-3 text-white"})})]},gA.id))]}),N.length>0&&t.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-2 pb-1",children:N.map(gA=>t.jsxs("div",{className:"relative group flex items-center gap-2 px-3 py-2 rounded-lg bg-teal-500/10 border border-teal-500/30 max-w-[200px]",children:[t.jsx(Ze,{className:"w-4 h-4 text-teal-500 flex-shrink-0"}),t.jsx("span",{className:"text-xs truncate text-teal-600 dark:text-teal-400",children:gA.label}),h&&t.jsx("button",{type:"button",onClick:()=>h(gA.id),className:"absolute top-0 right-0 p-0.5 bg-black/60 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity",children:t.jsx(MA,{className:"w-3 h-3 text-white"})})]},gA.id))}),t.jsxs("div",{className:"flex items-end gap-1",children:[B&&t.jsx("button",{type:"button",onClick:B,className:"flex items-center justify-center w-10 h-10 rounded-full hover:bg-background/50 active:bg-background/70 transition-colors text-muted-foreground hover:text-foreground flex-shrink-0 touch-manipulation",children:t.jsx(_o,{className:"w-4 h-4"})}),t.jsx(Ot,{ref:J,value:M,onChange:zt,onKeyDown:Fe,onPaste:Vt,placeholder:G?"Plan mode - Type a message...":"Type a message...",disabled:Q,rows:1,className:`border-0 bg-transparent pl-1 pr-2 py-2 max-h-[200px] overflow-y-auto leading-normal resize-none scrollbar-hide text-base ${q.vimMode&&eA==="normal"?"caret-[6px]":""}`,style:{height:"2.5rem"}}),t.jsx("button",{type:"button",onClick:we,disabled:Q||!M.trim()&&!FA,className:`flex items-center justify-center w-10 h-10 rounded-full transition-colors flex-shrink-0 touch-manipulation ${M.trim()||FA?"bg-primary hover:bg-primary/90 active:bg-primary/80 text-primary-foreground":"bg-transparent text-muted-foreground"}`,children:t.jsx(ZQ,{className:"w-4 h-4"})})]})]}),(E||n||d||c||D)&&t.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto] items-center mt-1 px-3",children:[t.jsx("div",{className:"justify-self-start flex-shrink-0",children:E&&t.jsxs("span",{className:"text-[10px] text-indigo-600 dark:text-indigo-300 flex items-center gap-1",children:[t.jsx(Ng,{className:"h-3 w-3"}),"thinking"]})}),t.jsx("div",{className:"justify-self-center",children:(c||d||D)&&t.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center gap-1 px-2 py-0.5",children:[t.jsxs("button",{type:"button",onClick:x,className:"flex items-center gap-1 transition-colors hover:text-foreground cursor-pointer",children:[c&&t.jsxs(t.Fragment,{children:[t.jsx(WA,{provider:c,size:12,className:"opacity-70"}),t.jsx("span",{className:"opacity-40",children:"/"})]}),d&&t.jsx("span",{children:d}),D&&D==="oauth"&&t.jsx("span",{className:"opacity-50",children:"(pro)"})]}),V&&v!==null&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400",children:["$",v.toFixed(2)]}),m&&t.jsx("button",{type:"button",onClick:gA=>{gA.stopPropagation(),m()},disabled:y,className:"p-0.5 hover:bg-background/50 rounded transition-colors disabled:opacity-50",children:t.jsx(TA,{className:`h-2.5 w-2.5 text-muted-foreground ${y?"animate-spin":""}`})})]})]})}),t.jsx("div",{className:"justify-self-end flex-shrink-0",children:n&&t.jsxs("span",{className:"text-[10px] text-emerald-600 dark:text-emerald-400 flex items-center gap-1",children:[t.jsx(PQ,{className:"h-3 w-3"}),"images"]})})]}),X&&!Y&&t.jsx(ra,{files:O,changedFiles:K,query:iA,selectedIndex:mA,onSelect:je,onEnterSelect:DA,onClose:OA}),ue&&t.jsx(ma,{query:Te,selectedIndex:oe,onSelect:De,onEnterSelect:H,onClose:ve,sessionId:i}),t.jsx(ya,{isOpen:U,onClose:()=>k(!1)})]})})]})}));function Mt(e){return PA({queryKey:["messages",e],queryFn:()=>{if(!e)throw new Error("Session ID is required");return T.getMessages(e)},enabled:!!e})}function Wa(e){const A=nA();return pA({mutationFn:g=>T.sendMessage(e,g),onSuccess:()=>{A.invalidateQueries({queryKey:["messages",e]}),A.invalidateQueries({queryKey:["sessions"]})}})}function Yt(){return PA({queryKey:["sessions"],queryFn:()=>T.getSessions(),refetchInterval:5e3,staleTime:5e3})}function XB(e){const{data:A}=Yt();return A?.find(g=>g.id===e)}function za(){const e=nA();return pA({mutationFn:A=>T.createSession(A),onSuccess:()=>{e.invalidateQueries({queryKey:["sessions"]})}})}function _B(e){const A=nA();return pA({mutationFn:g=>T.updateSession(e,g),onSuccess:async()=>{await A.invalidateQueries({queryKey:["sessions"]}),await A.invalidateQueries({queryKey:["session",e]})}})}function Va(){const e=nA();return pA({mutationFn:A=>T.deleteSession(A),onSuccess:()=>{e.invalidateQueries({queryKey:["sessions"]})}})}function Yg(){return PA({queryKey:["config"],queryFn:()=>T.getConfig(),staleTime:3e4})}function Tt(){return PA({queryKey:["models","all"],queryFn:()=>T.getAllModels()})}function Za(){const e=nA();return pA({mutationFn:A=>T.updateDefaults(A),onSuccess:()=>{e.invalidateQueries({queryKey:["config"]})}})}function vt(){const e=CA(A=>A.isExpanded);return PA({queryKey:["git","status"],queryFn:()=>T.getGitStatus(),refetchInterval:e?5e3:!1,retry:1,staleTime:3e3})}function Xa(e,A=!1){return PA({queryKey:["git","diff",e,A],queryFn:()=>e?T.getGitDiff(e,A):null,enabled:!!e,retry:1,refetchInterval:!1})}function _a(e){return pA({mutationFn:()=>T.generateCommitMessage(e??void 0)})}function jt(){const e=nA();return pA({mutationFn:A=>T.stageFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function Tg(){const e=nA();return pA({mutationFn:A=>T.unstageFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function $B(){const e=nA();return pA({mutationFn:A=>T.restoreFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function Ao(){const e=nA();return pA({mutationFn:A=>T.deleteFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function $a(){const e=nA();return pA({mutationFn:A=>T.commitChanges(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]}),e.invalidateQueries({queryKey:["git","branch"]})}})}function Ar(){const e=nA();return pA({mutationFn:()=>T.pushCommits(),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]}),e.invalidateQueries({queryKey:["git","branch"]})}})}const eo=["image/png","image/jpeg","image/gif","image/webp"],to=["application/pdf"],go=["text/plain","text/markdown","text/x-markdown"],Qo=[".txt",".md",".markdown"],er=[...eo,...to,...go];function tr(){return`file-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function gr(e){if(eo.includes(e.type))return"image";if(to.includes(e.type))return"pdf";if(go.includes(e.type))return"text";const A=e.name.toLowerCase().slice(e.name.lastIndexOf("."));return Qo.includes(A)?"text":null}function it(e){if(er.includes(e.type))return!0;const A=e.name.toLowerCase().slice(e.name.lastIndexOf("."));return Qo.includes(A)}async function bQ(e){return new Promise((A,g)=>{const Q=new FileReader;Q.onload=()=>{const o=Q.result.split(",")[1];A(o)},Q.onerror=g,Q.readAsDataURL(e)})}async function Qr(e){return new Promise((A,g)=>{const Q=new FileReader;Q.onload=()=>A(Q.result),Q.onerror=g,Q.readAsText(e)})}async function Br(e){return new Promise((A,g)=>{const Q=new FileReader;Q.onload=()=>A(Q.result),Q.onerror=g,Q.readAsDataURL(e)})}function or(e={}){const{maxFiles:A=10,maxSizeMB:g=10,pageWide:Q=!0}=e,[B,o]=u.useState([]),[s,E]=u.useState(!1),[i,C]=u.useState(null),a=g*1024*1024,I=u.useCallback(x=>it(x)?x.size>a?`File too large: ${(x.size/1024/1024).toFixed(1)}MB. Max: ${g}MB`:null:`Unsupported file type: ${x.type||x.name}. Supported: images, PDF, markdown, text`,[a,g]),l=u.useCallback(async x=>{C(null);const f=Array.from(x),M=A-B.length;if(M<=0){C(`Maximum ${A} files allowed`);return}const w=f.slice(0,M),G=[];for(const p of w){const U=I(p);if(U){C(U);continue}const k=gr(p);if(k)try{let J,S,Y,q=p.type;if(k==="image")[J,S]=await Promise.all([Br(p),bQ(p)]);else if(k==="pdf")S=await bQ(p),q="application/pdf";else if(Y=await Qr(p),S=Y,!q){const R=p.name.toLowerCase();q=R.endsWith(".md")||R.endsWith(".markdown")?"text/markdown":"text/plain"}G.push({id:tr(),file:p,type:k,name:p.name,preview:J,data:S,mediaType:q,textContent:Y})}catch{C(`Failed to process file: ${p.name}`)}}G.length>0&&o(p=>[...p,...G])},[B.length,A,I]),r=u.useCallback(x=>{o(f=>f.filter(M=>M.id!==x)),C(null)},[]),n=u.useCallback(()=>{o([]),C(null)},[]),d=u.useCallback(x=>{x.preventDefault(),x.stopPropagation(),x.dataTransfer.types.includes("Files")&&E(!0)},[]),c=u.useCallback(x=>{x.preventDefault(),x.stopPropagation();const f=x.currentTarget.getBoundingClientRect(),M=x.clientX,w=x.clientY;(M<f.left||M>f.right||w<f.top||w>f.bottom)&&E(!1)},[]),D=u.useCallback(x=>{x.preventDefault(),x.stopPropagation()},[]),N=u.useCallback(x=>{x.preventDefault(),x.stopPropagation(),E(!1);const f=x.dataTransfer.files;if(f.length>0){const M=Array.from(f).filter(it);M.length>0&&l(M)}},[l]),h=u.useCallback(x=>{const f=x.clipboardData?.items;if(!f)return;const M=[];for(const w of Array.from(f))if(w.kind==="file"){const G=w.getAsFile();G&&it(G)&&M.push(G)}M.length>0&&(x.preventDefault(),l(M))},[l]);u.useEffect(()=>{if(!Q)return;let x=0;const f=p=>{p.preventDefault(),p.dataTransfer?.types.includes("Files")&&(x++,x===1&&E(!0))},M=p=>{p.preventDefault(),x--,x===0&&E(!1)},w=p=>{p.preventDefault()},G=p=>{p.preventDefault(),x=0,E(!1);const U=p.dataTransfer?.files;if(U&&U.length>0){const k=Array.from(U).filter(it);k.length>0&&l(k)}};return document.addEventListener("dragenter",f),document.addEventListener("dragleave",M),document.addEventListener("dragover",w),document.addEventListener("drop",G),()=>{document.removeEventListener("dragenter",f),document.removeEventListener("dragleave",M),document.removeEventListener("dragover",w),document.removeEventListener("drop",G)}},[Q,l]);const m=B.filter(x=>x.type==="image"),y=B.filter(x=>x.type==="pdf"||x.type==="text");return{files:B,images:m,documents:y,isDragging:s,error:i,addFiles:l,removeFile:r,clearFiles:n,handleDragEnter:d,handleDragLeave:c,handleDragOver:D,handleDrop:N,handlePaste:h}}const ug=UA((e,A)=>({pendingRestoreText:null,setPendingRestoreText:g=>e({pendingRestoreText:g}),consumeRestoreText:()=>{const g=A().pendingRestoreText;return e({pendingRestoreText:null}),g}})),Dt=UA((e,A)=>({pendingContexts:new Map,addContext:(g,Q)=>{e(B=>{const o=new Map(B.pendingContexts),s=o.get(g)||[];return s.some(E=>E.id===Q.id)||o.set(g,[...s,Q]),{pendingContexts:o}})},removeContext:(g,Q)=>{e(B=>{const o=new Map(B.pendingContexts),s=o.get(g)||[];return o.set(g,s.filter(E=>E.id!==Q)),{pendingContexts:o}})},getContexts:g=>A().pendingContexts.get(g)||[],clearContexts:g=>{e(Q=>{const B=new Map(Q.pendingContexts);return B.delete(g),{pendingContexts:B}})},consumeContexts:g=>{const Q=A().getContexts(g);return A().clearContexts(g),Q}})),sr=/<research-context\s+from="([^"]+)"\s+label="([^"]+)"[^>]*>([\s\S]*?)<\/research-context>/g;function Er(e){const A=[];let g=e;const Q=new RegExp(sr);let B=Q.exec(e);for(;B!==null;){const[o,s,E,i]=B;A.push({id:s,from:s,label:E,content:i.trim()}),g=g.replace(o,""),B=Q.exec(e)}return g=g.trim(),{researchContexts:A,cleanContent:g}}function Cr(e){return e.length===0?"":e.map(A=>A.content).join(`
81
81
 
82
- `)}function Ht(e){const A=sA(C=>C.setBalance),g=sA(C=>C.setUsdcBalance),Q=sA(C=>C.setWalletAddress),B=sA(C=>C.setLoading),o=sA(C=>C.balance),s=sA(C=>C.usdcBalance),E=sA(C=>C.network),i=u.useCallback(async()=>{if(e==="setu"){B(!0);try{const[C,a,I]=await Promise.all([T.getSetuBalance(),T.getSetuUsdcBalance(E),T.getSetuWallet()]);C?(A(C.balance),Q(C.walletAddress)):I?.configured&&I.publicKey&&Q(I.publicKey),a&&(g(a.usdcBalance),!C&&a.walletAddress&&Q(a.walletAddress))}catch{}finally{B(!1)}}},[e,E,A,g,Q,B]);return u.useEffect(()=>{e==="setu"&&(o===null||s===null)&&i()},[e,o,s,i]),{fetchBalance:i}}const Bo=u.forwardRef(function({provider:A,model:g,onChange:Q,disabled:B=!1},o){const{data:s,isLoading:E}=Tt(),[i,C]=u.useState(!1),[a,I]=u.useState(""),[l,r]=u.useState(0),n=u.useRef(null),d=u.useRef(null),c=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{C(!0)}}));const D=u.useMemo(()=>{if(!s)return[];const w=[];for(const[G,p]of Object.entries(s))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[s]),N=u.useMemo(()=>new de(D,{keys:[{name:"modelLabel",weight:1},{name:"modelId",weight:.5},{name:"providerLabel",weight:.3}],threshold:.5,ignoreLocation:!0,includeScore:!0,distance:100,minMatchCharLength:1,findAllMatches:!0}),[D]),h=u.useMemo(()=>{if(!s)return{};if(!a.trim())return s;const G=N.search(a).sort((U,k)=>{const J=U.score??1,S=k.score??1;if(Math.abs(J-S)<.001){const Y=U.item.modelLabel.toLowerCase(),q=k.item.modelLabel.toLowerCase(),R=a.toLowerCase(),O=Y.indexOf(R),K=q.indexOf(R);if(O>=0&&K<0)return-1;if(K>=0&&O<0)return 1;if(O>=0&&K>=0)return O-K}return J-S}),p={};for(const U of G){const k=U.item;p[k.providerKey]||(p[k.providerKey]={label:k.providerLabel,models:[]}),p[k.providerKey].models.find(S=>S.id===k.modelId)||p[k.providerKey].models.push({id:k.modelId,label:k.modelLabel,toolCall:k.toolCall,reasoningText:k.reasoningText})}return p},[s,a,N]),m=u.useMemo(()=>{const w=[];for(const[G,p]of Object.entries(h))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[h]);u.useEffect(()=>{i&&r(0)},[i]),u.useEffect(()=>{i&&l>=0&&l<c.current.length&&c.current[l]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[l,i]),u.useEffect(()=>{const w=p=>{n.current&&!n.current.contains(p.target)&&C(!1)},G=p=>{const U=p.target,k=U.tagName==="INPUT"||U.tagName==="TEXTAREA"||U.isContentEditable;(p.key==="Escape"||p.key==="q"&&!k)&&C(!1)};return i&&(document.addEventListener("mousedown",w),document.addEventListener("keydown",G),setTimeout(()=>d.current?.focus(),0)),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",G)}},[i]);const y=(w,G)=>{Q(w,G),C(!1),I("")},x=w=>{if(m.length!==0){if(w.key==="ArrowDown"||w.ctrlKey&&w.key==="j")w.preventDefault(),r(G=>G<m.length-1?G+1:0);else if(w.key==="ArrowUp"||w.ctrlKey&&w.key==="k")w.preventDefault(),r(G=>G>0?G-1:m.length-1);else if(w.key==="Enter"){w.preventDefault();const G=m[l];G&&y(G.providerKey,G.modelId)}}},f=s?.[A]?.label||A,M=s?.[A]?.models.find(w=>w.id===g)?.label||g;return t.jsxs("div",{ref:n,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&C(!i),disabled:B||E,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsxs("span",{className:"flex items-center gap-2 text-sm truncate",children:[t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]",children:f}),t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]/50",children:"/"}),t.jsx("span",{className:"text-[hsl(var(--foreground))]",children:M})]}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${i?"rotate-180":""}`})]}),i&&!E&&s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:d,type:"text",value:a,onChange:w=>I(w.target.value),onKeyDown:x,placeholder:"Search providers and models...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:Object.keys(h).length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No models found"}):Object.entries(h).map(([w,G])=>t.jsxs("div",{className:"border-b border-[hsl(var(--border))] last:border-0",children:[t.jsx("div",{className:"sticky top-0 px-3 py-2 text-xs font-semibold text-[hsl(var(--muted-foreground))] uppercase tracking-wider bg-[hsl(var(--muted))] z-10",children:G.label}),t.jsx("div",{children:G.models.map(p=>{const U=w===A&&p.id===g,k=m.findIndex(S=>S.providerKey===w&&S.modelId===p.id),J=k===l;return t.jsxs("button",{ref:S=>{k>=0&&(c.current[k]=S)},type:"button",onClick:()=>y(w,p.id),onMouseEnter:()=>r(k),className:`w-full text-left px-4 py-2 text-sm flex items-center justify-between transition-colors ${J?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${U?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:[t.jsx("span",{className:"truncate",children:p.label}),(p.toolCall||p.reasoningText)&&t.jsxs("div",{className:"flex gap-1 ml-2 flex-shrink-0",children:[p.toolCall&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-green-600/20 text-green-400 rounded",children:"Tools"}),p.reasoningText&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-purple-600/20 text-purple-400 rounded",children:"Reasoning"})]})]},p.id)})})]},w))})]})]})}),ir=u.forwardRef(function({agent:A,agents:g,onChange:Q,disabled:B=!1},o){const[s,E]=u.useState(!1),[i,C]=u.useState(""),[a,I]=u.useState(0),l=u.useRef(null),r=u.useRef(null),n=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{E(!0)}}));const d=u.useMemo(()=>new de(g,{threshold:.4,ignoreLocation:!0}),[g]),c=u.useMemo(()=>i.trim()?d.search(i).map(m=>m.item):g,[g,i,d]);u.useEffect(()=>{s&&I(0)},[s]),u.useEffect(()=>{s&&a>=0&&a<n.current.length&&n.current[a]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[a,s]),u.useEffect(()=>{const h=y=>{l.current&&!l.current.contains(y.target)&&E(!1)},m=y=>{const x=y.target,f=x.tagName==="INPUT"||x.tagName==="TEXTAREA"||x.isContentEditable;(y.key==="Escape"||y.key==="q"&&!f)&&E(!1)};return s&&(document.addEventListener("mousedown",h),document.addEventListener("keydown",m),setTimeout(()=>r.current?.focus(),0)),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",m)}},[s]);const D=h=>{Q(h),E(!1),C("")},N=h=>{if(c.length!==0){if(h.key==="ArrowDown"||h.ctrlKey&&h.key==="j")h.preventDefault(),I(m=>m<c.length-1?m+1:0);else if(h.key==="ArrowUp"||h.ctrlKey&&h.key==="k")h.preventDefault(),I(m=>m>0?m-1:c.length-1);else if(h.key==="Enter"){h.preventDefault();const m=c[a];m&&D(m)}}};return t.jsxs("div",{ref:l,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&E(!s),disabled:B,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsx("span",{className:"text-sm text-[hsl(var(--foreground))] truncate",children:A}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${s?"rotate-180":""}`})]}),s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:r,type:"text",value:i,onChange:h=>C(h.target.value),onKeyDown:N,placeholder:"Search agents...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:c.length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No agents found"}):c.map((h,m)=>{const y=h===A,x=m===a;return t.jsx("button",{ref:f=>{n.current[m]=f},type:"button",onClick:()=>D(h),onMouseEnter:()=>I(m),className:`w-full text-left px-4 py-2 text-sm transition-colors ${x?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${y?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:t.jsx("span",{className:"truncate",children:h})},h)})})]})]})});function ar({isOpen:e,onClose:A,initialFocus:g,chatInputRef:Q,agent:B,provider:o,model:s,modelSupportsReasoning:E,onAgentChange:i,onProviderChange:C,onModelChange:a,onModelSelectorChange:I}){const{data:l,isLoading:r}=Yg(),{preferences:n,updatePreferences:d}=ot(),c=u.useRef(null),D=u.useRef(null);u.useEffect(()=>{e&&g&&setTimeout(()=>{g==="agent"?c.current?.openAndFocus():g==="model"&&D.current?.openAndFocus()},100)},[e,g]);const N=()=>{A(),setTimeout(()=>{Q?.current?.focus()},100)},h=(m,y)=>{I?I(m,y):(C(m),a(y))};return t.jsx(qe,{isOpen:e,onClose:N,title:"Configuration",closeOnEscape:!0,closeOnBackdropClick:!0,children:r?t.jsx("div",{className:"text-center text-muted-foreground py-8",children:"Loading configuration..."}):l?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Agent"}),t.jsx(ir,{ref:c,agent:B,agents:l.agents,onChange:i})]}),t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Provider / Model"}),t.jsx(Bo,{ref:D,provider:o,model:s,onChange:h})]}),E&&t.jsxs("div",{className:"flex items-center justify-between py-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-foreground",children:"Extended Thinking"}),t.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable reasoning for deeper analysis"})]}),t.jsx("button",{type:"button",role:"switch","aria-checked":n.reasoningEnabled,onClick:()=>d({reasoningEnabled:!n.reasoningEnabled}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${n.reasoningEnabled?"bg-primary":"bg-muted"}`,children:t.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full transition-transform ${n.reasoningEnabled?"translate-x-6":"translate-x-1"} ${n.reasoningEnabled?"bg-primary-foreground":"bg-foreground"}`})})]})]}):null})}const rr=u.memo(u.forwardRef(function({sessionId:A,userContext:g,onNewSession:Q,onDeleteSession:B},o){const s=XB(A),[E,i]=u.useState(""),[C,a]=u.useState(""),[I,l]=u.useState(""),[r,n]=u.useState(!1),[d,c]=u.useState(null),[D,N]=u.useState(0),h=u.useRef(null),m=Wa(A);Mt(A);const y=_B(A),x=Va(),{data:f}=Tt(),{preferences:M}=ot(),{data:w}=vt(),G=jt(),p=CA(H=>H.openCommitModalForSession),U=CA(H=>H.setActiveSessionId),k=nA(),{images:J,documents:S,isDragging:Y,removeFile:q,clearFiles:R,handlePaste:O}=or(),K=f?.[C]?.models?.find(H=>H.id===I)?.reasoningText,v=f?.[C]?.models?.find(H=>H.id===I)?.vision,V=Dt(H=>H.pendingContexts),_=Dt(H=>H.removeContext),X=Dt(H=>H.consumeContexts),iA=V.get(A)||[],mA=u.useMemo(()=>iA.map(H=>({id:H.id,label:H.label})),[iA]),j=u.useCallback(H=>{_(A,H)},[A,_]),L=f?.[C]?.authType,{fetchBalance:AA}=Ht(C),EA=sA(H=>H.isLoading);u.useEffect(()=>{s&&(i(s.agent),a(s.provider),l(s.model))},[s]),u.useEffect(()=>(U(A),()=>U(null)),[A,U]),u.useEffect(()=>{N(H=>H+1)},[]);const NA=ug(H=>H.pendingRestoreText),DA=ug(H=>H.consumeRestoreText);u.useEffect(()=>{if(NA){const H=DA();H&&h.current?.setValue(H)}},[NA,DA]),u.useImperativeHandle(o,()=>({focus:()=>{h.current?.focus()}}));const yA=u.useCallback(async H=>{try{const oA=X(A),eA=Cr(oA),GA=eA?`${eA}
82
+ `)}function Ht(e){const A=sA(C=>C.setBalance),g=sA(C=>C.setUsdcBalance),Q=sA(C=>C.setWalletAddress),B=sA(C=>C.setLoading),o=sA(C=>C.balance),s=sA(C=>C.usdcBalance),E=sA(C=>C.network),i=u.useCallback(async()=>{if(e==="setu"){B(!0);try{const[C,a,I]=await Promise.all([T.getSetuBalance(),T.getSetuUsdcBalance(E),T.getSetuWallet()]);C?(A(C.balance),Q(C.walletAddress)):I?.configured&&I.publicKey&&Q(I.publicKey),a&&(g(a.usdcBalance),!C&&a.walletAddress&&Q(a.walletAddress))}catch{}finally{B(!1)}}},[e,E,A,g,Q,B]);return u.useEffect(()=>{e==="setu"&&(o===null||s===null)&&i()},[e,o,s,i]),{fetchBalance:i}}const Bo=u.forwardRef(function({provider:A,model:g,onChange:Q,disabled:B=!1},o){const{data:s,isLoading:E}=Tt(),[i,C]=u.useState(!1),[a,I]=u.useState(""),[l,r]=u.useState(0),n=u.useRef(null),d=u.useRef(null),c=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{C(!0)}}));const D=u.useMemo(()=>{if(!s)return[];const w=[];for(const[G,p]of Object.entries(s))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[s]),N=u.useMemo(()=>new de(D,{keys:[{name:"modelLabel",weight:2},{name:"modelId",weight:1},{name:"providerLabel",weight:.5}],threshold:.3,ignoreLocation:!0,includeScore:!0,distance:100,minMatchCharLength:1}),[D]),h=u.useMemo(()=>{if(!s)return{};if(!a.trim())return s;const G=N.search(a).sort((U,k)=>{const J=U.score??1,S=k.score??1;if(Math.abs(J-S)<.001){const Y=U.item.modelLabel.toLowerCase(),q=k.item.modelLabel.toLowerCase(),R=a.toLowerCase(),O=Y.indexOf(R),K=q.indexOf(R);if(O>=0&&K<0)return-1;if(K>=0&&O<0)return 1;if(O>=0&&K>=0)return O-K}return J-S}),p={};for(const U of G){const k=U.item;p[k.providerKey]||(p[k.providerKey]={label:k.providerLabel,models:[]}),p[k.providerKey].models.find(S=>S.id===k.modelId)||p[k.providerKey].models.push({id:k.modelId,label:k.modelLabel,toolCall:k.toolCall,reasoningText:k.reasoningText})}return p},[s,a,N]),m=u.useMemo(()=>{const w=[];for(const[G,p]of Object.entries(h))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[h]);u.useEffect(()=>{i&&r(0)},[i]),u.useEffect(()=>{i&&l>=0&&l<c.current.length&&c.current[l]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[l,i]),u.useEffect(()=>{const w=p=>{n.current&&!n.current.contains(p.target)&&C(!1)},G=p=>{const U=p.target,k=U.tagName==="INPUT"||U.tagName==="TEXTAREA"||U.isContentEditable;(p.key==="Escape"||p.key==="q"&&!k)&&C(!1)};return i&&(document.addEventListener("mousedown",w),document.addEventListener("keydown",G),setTimeout(()=>d.current?.focus(),0)),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",G)}},[i]);const y=(w,G)=>{Q(w,G),C(!1),I("")},x=w=>{if(m.length!==0){if(w.key==="ArrowDown"||w.ctrlKey&&w.key==="j")w.preventDefault(),r(G=>G<m.length-1?G+1:0);else if(w.key==="ArrowUp"||w.ctrlKey&&w.key==="k")w.preventDefault(),r(G=>G>0?G-1:m.length-1);else if(w.key==="Enter"){w.preventDefault();const G=m[l];G&&y(G.providerKey,G.modelId)}}},f=s?.[A]?.label||A,M=s?.[A]?.models.find(w=>w.id===g)?.label||g;return t.jsxs("div",{ref:n,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&C(!i),disabled:B||E,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsxs("span",{className:"flex items-center gap-2 text-sm truncate",children:[t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]",children:f}),t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]/50",children:"/"}),t.jsx("span",{className:"text-[hsl(var(--foreground))]",children:M})]}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${i?"rotate-180":""}`})]}),i&&!E&&s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:d,type:"text",value:a,onChange:w=>I(w.target.value),onKeyDown:x,placeholder:"Search providers and models...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:Object.keys(h).length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No models found"}):Object.entries(h).map(([w,G])=>t.jsxs("div",{className:"border-b border-[hsl(var(--border))] last:border-0",children:[t.jsx("div",{className:"sticky top-0 px-3 py-2 text-xs font-semibold text-[hsl(var(--muted-foreground))] uppercase tracking-wider bg-[hsl(var(--muted))] z-10",children:G.label}),t.jsx("div",{children:G.models.map(p=>{const U=w===A&&p.id===g,k=m.findIndex(S=>S.providerKey===w&&S.modelId===p.id),J=k===l;return t.jsxs("button",{ref:S=>{k>=0&&(c.current[k]=S)},type:"button",onClick:()=>y(w,p.id),onMouseEnter:()=>r(k),className:`w-full text-left px-4 py-2 text-sm flex items-center justify-between transition-colors ${J?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${U?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:[t.jsx("span",{className:"truncate",children:p.label}),(p.toolCall||p.reasoningText)&&t.jsxs("div",{className:"flex gap-1 ml-2 flex-shrink-0",children:[p.toolCall&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-green-600/20 text-green-400 rounded",children:"Tools"}),p.reasoningText&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-purple-600/20 text-purple-400 rounded",children:"Reasoning"})]})]},p.id)})})]},w))})]})]})}),ir=u.forwardRef(function({agent:A,agents:g,onChange:Q,disabled:B=!1},o){const[s,E]=u.useState(!1),[i,C]=u.useState(""),[a,I]=u.useState(0),l=u.useRef(null),r=u.useRef(null),n=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{E(!0)}}));const d=u.useMemo(()=>new de(g,{threshold:.4,ignoreLocation:!0}),[g]),c=u.useMemo(()=>i.trim()?d.search(i).map(m=>m.item):g,[g,i,d]);u.useEffect(()=>{s&&I(0)},[s]),u.useEffect(()=>{s&&a>=0&&a<n.current.length&&n.current[a]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[a,s]),u.useEffect(()=>{const h=y=>{l.current&&!l.current.contains(y.target)&&E(!1)},m=y=>{const x=y.target,f=x.tagName==="INPUT"||x.tagName==="TEXTAREA"||x.isContentEditable;(y.key==="Escape"||y.key==="q"&&!f)&&E(!1)};return s&&(document.addEventListener("mousedown",h),document.addEventListener("keydown",m),setTimeout(()=>r.current?.focus(),0)),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",m)}},[s]);const D=h=>{Q(h),E(!1),C("")},N=h=>{if(c.length!==0){if(h.key==="ArrowDown"||h.ctrlKey&&h.key==="j")h.preventDefault(),I(m=>m<c.length-1?m+1:0);else if(h.key==="ArrowUp"||h.ctrlKey&&h.key==="k")h.preventDefault(),I(m=>m>0?m-1:c.length-1);else if(h.key==="Enter"){h.preventDefault();const m=c[a];m&&D(m)}}};return t.jsxs("div",{ref:l,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&E(!s),disabled:B,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsx("span",{className:"text-sm text-[hsl(var(--foreground))] truncate",children:A}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${s?"rotate-180":""}`})]}),s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:r,type:"text",value:i,onChange:h=>C(h.target.value),onKeyDown:N,placeholder:"Search agents...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:c.length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No agents found"}):c.map((h,m)=>{const y=h===A,x=m===a;return t.jsx("button",{ref:f=>{n.current[m]=f},type:"button",onClick:()=>D(h),onMouseEnter:()=>I(m),className:`w-full text-left px-4 py-2 text-sm transition-colors ${x?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${y?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:t.jsx("span",{className:"truncate",children:h})},h)})})]})]})});function ar({isOpen:e,onClose:A,initialFocus:g,chatInputRef:Q,agent:B,provider:o,model:s,modelSupportsReasoning:E,onAgentChange:i,onProviderChange:C,onModelChange:a,onModelSelectorChange:I}){const{data:l,isLoading:r}=Yg(),{preferences:n,updatePreferences:d}=ot(),c=u.useRef(null),D=u.useRef(null);u.useEffect(()=>{e&&g&&setTimeout(()=>{g==="agent"?c.current?.openAndFocus():g==="model"&&D.current?.openAndFocus()},100)},[e,g]);const N=()=>{A(),setTimeout(()=>{Q?.current?.focus()},100)},h=(m,y)=>{I?I(m,y):(C(m),a(y))};return t.jsx(qe,{isOpen:e,onClose:N,title:"Configuration",closeOnEscape:!0,closeOnBackdropClick:!0,children:r?t.jsx("div",{className:"text-center text-muted-foreground py-8",children:"Loading configuration..."}):l?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Agent"}),t.jsx(ir,{ref:c,agent:B,agents:l.agents,onChange:i})]}),t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Provider / Model"}),t.jsx(Bo,{ref:D,provider:o,model:s,onChange:h})]}),E&&t.jsxs("div",{className:"flex items-center justify-between py-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-foreground",children:"Extended Thinking"}),t.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable reasoning for deeper analysis"})]}),t.jsx("button",{type:"button",role:"switch","aria-checked":n.reasoningEnabled,onClick:()=>d({reasoningEnabled:!n.reasoningEnabled}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${n.reasoningEnabled?"bg-primary":"bg-muted"}`,children:t.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full transition-transform ${n.reasoningEnabled?"translate-x-6":"translate-x-1"} ${n.reasoningEnabled?"bg-primary-foreground":"bg-foreground"}`})})]})]}):null})}const rr=u.memo(u.forwardRef(function({sessionId:A,userContext:g,onNewSession:Q,onDeleteSession:B},o){const s=XB(A),[E,i]=u.useState(""),[C,a]=u.useState(""),[I,l]=u.useState(""),[r,n]=u.useState(!1),[d,c]=u.useState(null),[D,N]=u.useState(0),h=u.useRef(null),m=Wa(A);Mt(A);const y=_B(A),x=Va(),{data:f}=Tt(),{preferences:M}=ot(),{data:w}=vt(),G=jt(),p=CA(H=>H.openCommitModalForSession),U=CA(H=>H.setActiveSessionId),k=nA(),{images:J,documents:S,isDragging:Y,removeFile:q,clearFiles:R,handlePaste:O}=or(),K=f?.[C]?.models?.find(H=>H.id===I)?.reasoningText,v=f?.[C]?.models?.find(H=>H.id===I)?.vision,V=Dt(H=>H.pendingContexts),_=Dt(H=>H.removeContext),X=Dt(H=>H.consumeContexts),iA=V.get(A)||[],mA=u.useMemo(()=>iA.map(H=>({id:H.id,label:H.label})),[iA]),j=u.useCallback(H=>{_(A,H)},[A,_]),L=f?.[C]?.authType,{fetchBalance:AA}=Ht(C),EA=sA(H=>H.isLoading);u.useEffect(()=>{s&&(i(s.agent),a(s.provider),l(s.model))},[s]),u.useEffect(()=>(U(A),()=>U(null)),[A,U]),u.useEffect(()=>{N(H=>H+1)},[]);const NA=ug(H=>H.pendingRestoreText),DA=ug(H=>H.consumeRestoreText);u.useEffect(()=>{if(NA){const H=DA();H&&h.current?.setValue(H)}},[NA,DA]),u.useImperativeHandle(o,()=>({focus:()=>{h.current?.focus()}}));const yA=u.useCallback(async H=>{try{const oA=X(A),eA=Cr(oA),GA=eA?`${eA}
83
83
 
84
84
  ${H}`:H,ee=J.length>0?J.map(OA=>({data:OA.data,mediaType:OA.mediaType})):void 0,Ge=S.length>0?S.map(OA=>({type:OA.type,name:OA.name,data:OA.data,mediaType:OA.mediaType,textContent:OA.textContent})):void 0;await m.mutateAsync({content:GA,images:ee,files:Ge,agent:E||void 0,provider:C||void 0,model:I||void 0,userContext:g||void 0,reasoningText:K&&M.reasoningEnabled?!0:void 0}),R()}catch(oA){console.error("Failed to send message:",oA)}},[m,S,J,R,E,C,I,g,K,M.reasoningEnabled,A,X]),ue=u.useCallback(()=>{n(H=>!H)},[]),Te=u.useCallback(()=>{n(!1),c(null)},[]),oe=u.useCallback(async H=>{if(H==="models")c("model"),n(!0);else if(H==="agents")c("agent"),n(!0);else if(H==="new")Q?.();else if(H==="stage"){const oA=w?.unstaged?.map(ee=>ee.path)??[],eA=w?.untracked?.map(ee=>ee.path)??[],GA=[...oA,...eA];GA.length>0&&G.mutate(GA)}else if(H==="commit")p(A);else if(H==="compact")yA("/compact");else if(H==="delete")x.mutate(A,{onSuccess:()=>{B?.()}});else if(H==="share"){const oA=tA.loading("Sharing session...");try{const eA=await T.shareSession(A);eA.shared&&(tA.successWithAction(eA.message==="Already shared"?"Already shared":"Session shared!",{label:"Open",href:eA.url}),k.invalidateQueries({queryKey:["share-status",A]}))}catch(eA){tA.error(eA instanceof Error?eA.message:"Failed to share")}finally{_A.getState().removeToast(oA)}}else if(H==="sync"){const oA=tA.loading("Syncing session...");try{const eA=await T.syncSession(A);if(eA.synced){const GA=eA.newMessages>0?`Synced ${eA.newMessages} new messages`:"Already synced";tA.successWithAction(GA,{label:"Open",href:eA.url}),k.invalidateQueries({queryKey:["share-status",A]})}}catch(eA){tA.error(eA instanceof Error?eA.message:"Failed to sync")}finally{_A.getState().removeToast(oA)}}},[Q,w,G,p,yA,x,A,B,k]),Ie=u.useCallback(async H=>{i(H);try{await y.mutateAsync({agent:H})}catch(oA){console.error("Failed to update agent:",oA)}},[y]),KA=u.useCallback(async(H,oA)=>{a(H),l(oA);try{await y.mutateAsync({provider:H,model:oA})}catch(eA){console.error("Failed to update model:",eA)}},[y]),he=u.useCallback(async H=>{if(a(H),I)try{await y.mutateAsync({provider:H,model:I})}catch(oA){console.error("Failed to update provider:",oA)}},[I,y]),zA=u.useCallback(async H=>{l(H);try{await y.mutateAsync({provider:C,model:H})}catch(oA){console.error("Failed to update model:",oA)}},[C,y]),De=u.useCallback(async H=>{const oA=H?"plan":"build";i(oA);try{await y.mutateAsync({agent:oA})}catch(eA){console.error("Failed to switch agent:",eA)}},[y]);return t.jsxs(t.Fragment,{children:[t.jsx(ar,{isOpen:r,onClose:Te,initialFocus:d,chatInputRef:h,agent:E,provider:C,model:I,modelSupportsReasoning:K,onAgentChange:Ie,onProviderChange:he,onModelChange:zA,onModelSelectorChange:KA}),t.jsx(Pa,{ref:h,onSend:yA,onCommand:oe,disabled:m.isPending,onConfigClick:ue,onPlanModeToggle:De,isPlanMode:E==="plan",reasoningEnabled:K&&M.reasoningEnabled,sessionId:A,images:J,documents:S,onFileRemove:q,isDragging:Y,onPaste:O,visionEnabled:v,modelName:I,providerName:C,authType:L,researchContexts:mA,onResearchContextRemove:j,onRefreshBalance:C==="setu"?AA:void 0,isBalanceLoading:EA,onModelInfoClick:()=>{c("model"),n(!0)}},D)]})}));function Ir({sessionId:e,onStop:A,disabled:g}){const[Q,B]=u.useState(!1),o=async()=>{if(!Q){B(!0);try{await T.abortSession(e),A?.()}catch(s){console.error("Failed to abort stream:",s)}finally{setTimeout(()=>B(!1),1e3)}}};return t.jsxs("button",{type:"button",onClick:o,disabled:g||Q,className:"flex items-center gap-1.5 text-sm text-destructive hover:text-destructive/80 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",title:"Stop generation",children:[t.jsx(zQ,{className:"w-4 h-4"}),t.jsx("span",{className:"font-medium",children:Q?"Stopping...":"Stop"})]})}function nr(e){const A=e.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"text",svelte:"svelte"}[A||""]||"javascript"}function lr(e){const A=e.split(`
85
85
  `),g=[];let Q=0,B=0,o=!1,s="";for(const E of A){if(E.startsWith("*** Update File:")||E.startsWith("*** Add File:")){const C=E.match(/\*\*\* (?:Update|Add) File: (.+)/);C&&(s=C[1]),o=!0,B=1,Q=1}if(E.startsWith("+++")||E.startsWith("*** Update File:")){const C=E.match(/\+\+\+ b\/(.+)/)||E.match(/\*\*\* Update File: (.+)/);C&&(s=C[1])}const i=E.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(i){Q=Number.parseInt(i[1],10),B=Number.parseInt(i[2],10),o=!0,g.push({content:E,codeContent:E,type:"header"});continue}if(E.startsWith("@@")&&!E.match(/^@@ -\d+/)){o=!0,g.push({content:E,codeContent:E,type:"header"});continue}if(E.startsWith("***")||E.startsWith("diff ")||E.startsWith("index ")||E.startsWith("---")||E.startsWith("+++")){g.push({content:E,codeContent:E,type:"meta"});continue}o?E.startsWith("+")?g.push({content:E,codeContent:E.slice(1),type:"add",newLineNum:B++}):E.startsWith("-")?g.push({content:E,codeContent:E.slice(1),type:"remove",oldLineNum:Q++}):E.startsWith(" ")||E===""?g.push({content:E,codeContent:E.startsWith(" ")?E.slice(1):E,type:"context",oldLineNum:Q++,newLineNum:B++}):g.push({content:E,codeContent:E,type:"context"}):g.push({content:E,codeContent:E,type:"meta"})}return{lines:g,filePath:s}}function Re({patch:e}){const{lines:A,filePath:g}=lr(e),Q=nr(g),B=document?.documentElement.classList.contains("dark")?ae:re;return t.jsx("div",{className:"bg-card/60 border border-border rounded-lg overflow-hidden max-h-96 max-w-full",children:t.jsx("div",{className:"overflow-x-auto overflow-y-auto max-h-96 text-xs font-mono",children:A.map((o,s)=>{const E=`line-${s}-${o.content.slice(0,20)}`;if(o.type==="meta"||o.type==="header")return t.jsx("div",{className:`px-3 py-0.5 whitespace-pre-wrap break-all ${o.type==="header"?"text-muted-foreground/80 bg-muted/20":"text-muted-foreground/80"}`,children:o.content},E);let i="",C="";switch(o.type){case"add":i="text-emerald-700 dark:text-emerald-300",C="bg-emerald-500/10";break;case"remove":i="text-red-600 dark:text-red-300",C="bg-red-500/10";break;default:i="text-foreground/80"}let a=o.content;return o.codeContent.trim()&&Q!=="text"&&(a=t.jsx(jA,{language:Q,style:B,customStyle:{margin:0,padding:0,background:"transparent",display:"inline",fontSize:"inherit",lineHeight:"inherit"},codeTagProps:{style:{fontFamily:"inherit",background:"transparent"}},PreTag:"span",children:o.codeContent}),o.type==="add"?a=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:"+"}),a]}):o.type==="remove"?a=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:"-"}),a]}):o.type==="context"&&(a=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:" "}),a]}))),t.jsxs("div",{className:`flex ${C}`,children:[t.jsx("div",{className:"px-2 py-0.5 text-right text-muted-foreground/40 select-none w-12 flex-shrink-0",children:o.oldLineNum||""}),t.jsx("div",{className:"px-2 py-0.5 text-right text-muted-foreground/40 select-none w-12 flex-shrink-0 border-r border-border/50",children:o.newLineNum||""}),t.jsx("div",{className:`px-3 py-0.5 flex-1 min-w-0 whitespace-pre-wrap break-all ${i}`,children:a})]},E)})})})}function cr(e){const A=e.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"text",svelte:"svelte"}[A||""]||"javascript"}function dr(e,A){if(!A)return null;const Q={read:["path"],write:["path"],edit:["path"],apply_patch:["path"],glob:["pattern"],grep:["query","pattern"],ripgrep:["query","pattern"],bash:["cmd","command"],terminal:["command"],git_commit:["message"],git_diff:["file"],tree:["path"],ls:["path"],web_search:["query","url"],skill:["name"]}[e];if(!Q){for(const[B,o]of Object.entries(A))if(typeof o=="string"&&o.length>0&&o.length<200)return{key:B,value:o};return null}for(const B of Q){const o=A[B];if(typeof o=="string"&&o.length>0)return{key:B,value:o}}return null}function ur(e){if(!e)return null;const A=e.cmd??e.command;return typeof A=="string"&&A.length>0?A:null}const hr=u.memo(function({toolName:A,args:g,pendingApproval:Q,onApprove:B,onReject:o}){const[s,E]=u.useState(!1),i=A.replace(/_/g," "),C=dr(A,g),I=(A==="bash"?ur(g):null)||C?.value,l=typeof g?.path=="string"?g.path:"",r=cr(l),n=document?.documentElement.classList.contains("dark")?ae:re,d=()=>{E(!0),B(Q.callId)},c=()=>{E(!0),o(Q.callId)},D=()=>{if(A==="apply_patch"&&g?.patch)return t.jsx("div",{className:"ml-6 max-w-full overflow-hidden",children:t.jsx(Re,{patch:String(g.patch)})});if(A==="write"&&g?.content){const N=String(g.content);return t.jsx("div",{className:"ml-6 max-w-full overflow-hidden",children:t.jsx("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-lg overflow-hidden max-h-96",children:t.jsx("div",{className:"overflow-x-auto overflow-y-auto max-h-96 text-xs",children:t.jsx(jA,{language:r,style:n,customStyle:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"inherit"},showLineNumbers:!0,lineNumberStyle:{minWidth:"2.5em",paddingRight:"1em",color:"var(--muted-foreground)",opacity:.4,userSelect:"none"},children:N})})})})}if(A==="bash"&&g?.cmd){const N=String(g.cmd);return t.jsx("div",{className:"ml-6 max-w-full overflow-hidden",children:t.jsx("div",{className:"bg-card/60 border border-border rounded-lg overflow-hidden",children:t.jsx("div",{className:"overflow-x-auto text-xs",children:t.jsx(jA,{language:"bash",style:n,customStyle:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"inherit"},children:N})})})})}return null};return t.jsxs("div",{className:"flex flex-col gap-2 py-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx(XQ,{className:"h-4 w-4 text-amber-500 flex-shrink-0"}),t.jsx("span",{className:"font-medium text-foreground text-sm",children:i}),I&&A!=="bash"&&t.jsx("code",{className:"text-xs font-mono text-foreground/80 bg-muted/50 px-1.5 py-0.5 rounded truncate max-w-xs",children:I}),t.jsx("span",{className:"text-amber-600 dark:text-amber-400 font-medium text-sm",children:"requires approval"})]}),D(),t.jsxs("div",{className:"flex items-center gap-2 ml-6",children:[t.jsxs("button",{type:"button",onClick:c,disabled:s,title:"Reject (N or Esc)",className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded border border-border bg-background hover:bg-muted transition-colors disabled:opacity-50",children:[t.jsx(MA,{className:"w-3 h-3"}),"Reject",t.jsx("kbd",{className:"ml-1 text-[10px] text-muted-foreground opacity-70",children:"N"})]}),t.jsxs("button",{type:"button",onClick:d,disabled:s,title:"Approve (Y)",className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded bg-amber-600 text-white hover:bg-amber-700 transition-colors disabled:opacity-50",children:[t.jsx(XA,{className:"w-3 h-3"}),s?"Approving...":"Approve",!s&&t.jsx("kbd",{className:"ml-1 text-[10px] opacity-70",children:"Y"})]})]})]})});function JA(e){return e?e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`:""}function Oe(e){if(!e||typeof e!="object")return!1;const A=e;return A.ok===!1||"error"in A||A.success===!1}function Ye(e){if(!e||typeof e!="object")return null;const A=e,g=["error","stderr","message","detail","details","reason"];for(const Q of g){const B=A[Q];if(typeof B=="string"){const o=B.trim();if(o.length)return o}}return null}function qA({error:e,stack:A,showStack:g=!1}){return t.jsx("div",{className:"mt-2 ml-5 p-3 bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded text-sm",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Be,{className:"h-4 w-4 flex-shrink-0 text-red-600 dark:text-red-400 mt-0.5"}),t.jsxs("div",{className:"flex-1 space-y-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:"Tool Error:"}),t.jsx("div",{className:"mt-1 text-red-900 dark:text-red-200 whitespace-pre-wrap",children:e})]}),g&&A&&t.jsxs("details",{className:"mt-2",children:[t.jsx("summary",{className:"cursor-pointer text-xs text-red-700 dark:text-red-300 hover:text-red-600 dark:hover:text-red-200",children:"View stack trace"}),t.jsx("pre",{className:"mt-2 p-2 bg-red-100/50 dark:bg-red-900/20 rounded text-xs overflow-x-auto text-red-800 dark:text-red-300",children:A})]})]})]})})}function Dr(e){const A=e.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"text"}[A||""]||"text"}function wr(e){if(!e)return;const A=e.match(/@(\d+)-(\d+)/);if(A)return Number.parseInt(A[1],10)}function pr({contentJson:e,toolDurationMs:A,isExpanded:g,onToggle:Q,compact:B}){const o=e.result||{},s=e.args||{},E=typeof o=="object"&&"ok"in o&&o.ok===!1,i=E&&"error"in o&&typeof o.error=="string"?o.error:null,C=E&&"stack"in o&&typeof o.stack=="string"?o.stack:void 0,a=String(o.path||s.path||""),I=String(o.content||""),l=o.lineRange,r=I.split(`
@@ -99,9 +99,7 @@ ${c.url}`).join(`
99
99
  `);let I="message",l="";for(const r of a)r.startsWith("event: ")?I=r.slice(7).trim():r.startsWith("data: ")?l+=(l?`
100
100
  `:"")+r.slice(6):r.startsWith(":");if(l)try{const r=JSON.parse(l);this.emit({type:I,payload:r})}catch(r){console.error(`[SSE] Failed to parse ${I}:`,r)}i=o.indexOf(`
101
101
 
102
- `)}}}catch(g){g instanceof Error&&g.name==="AbortError"||console.error("[SSE] Connection error:",g)}}disconnect(){this.running=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}on(A,g){return this.handlers.has(A)||this.handlers.set(A,new Set),this.handlers.get(A)?.add(g),()=>{this.off(A,g)}}off(A,g){const Q=this.handlers.get(A);Q&&(Q.delete(g),Q.size===0&&this.handlers.delete(A))}emit(A){const g=this.handlers.get(A.type);if(g)for(const B of g)B(A);const Q=this.handlers.get("*");if(Q)for(const B of Q)B(A)}}function co(e){const A=nA(),g=u.useRef(null),Q=u.useRef(null),B=u.useRef(0),{addPendingApproval:o,removePendingApproval:s,updatePendingApproval:E,setPendingApprovals:i}=Lg();u.useEffect(()=>{if(!e){console.log("[useSessionStream] No sessionId, skipping");return}Q.current=null,T.getPendingApprovals(e).then(x=>{x.ok&&x.pending.length>0?i(x.pending):i([])}).catch(()=>{i([])});const C=new lo;g.current=C;const a=T.getStreamUrl(e);console.log("[useSessionStream] Connecting to stream:",a),C.connect(a);const I=x=>{if(Q.current){const f=x.findIndex(M=>M.id===Q.current);if(f!==-1)return f}for(let f=x.length-1;f>=0;f-=1){const M=x[f];if(M.role==="assistant"&&M.status!=="complete")return f}return-1},l=x=>{if(x.contentJson&&typeof x.contentJson=="object"&&!Array.isArray(x.contentJson)&&"text"in x.contentJson)return String(x.contentJson.text??"");if(typeof x.content=="string"){try{const f=JSON.parse(x.content);if(f&&typeof f.text=="string")return f.text}catch{}return x.content}return""},r=x=>{const f=typeof x?.messageId=="string"?x.messageId:null,M=typeof x?.partId=="string"?x.partId:null,w=typeof x?.delta=="string"?x.delta:null;!f||!M||w===null||A.setQueryData(["messages",e],G=>{if(!G)return G;const p=[...G],U=p.findIndex(q=>q.id===f);if(U===-1)return G;const k=p[U],J=k.parts?[...k.parts]:[];let S=J.findIndex(q=>q.id===M);const Y=typeof x?.stepIndex=="number"?x.stepIndex:null;if(S===-1){const q={id:M,messageId:f,index:J.length,stepIndex:Y,type:"reasoning",content:JSON.stringify({text:w}),contentJson:{text:w},agent:k.agent,provider:k.provider,model:k.model,startedAt:Date.now(),completedAt:null,toolName:null,toolCallId:null,toolDurationMs:null};J.push(q),S=J.length-1}else{const q=J[S],O=`${l(q)}${w}`;J[S]={...q,content:JSON.stringify({text:O}),contentJson:{text:O},stepIndex:Y??q.stepIndex??null,completedAt:null}}return p[U]={...k,parts:J},p})},n=x=>{const f=typeof x?.messageId=="string"?x.messageId:null,M=typeof x?.partId=="string"?x.partId:null,w=typeof x?.delta=="string"?x.delta:null;!f||!M||w===null||A.setQueryData(["messages",e],G=>{if(!G)return G;const p=[...G],U=p.findIndex(q=>q.id===f);if(U===-1)return G;const k=p[U],J=k.parts?[...k.parts]:[];let S=J.findIndex(q=>q.id===M);const Y=typeof x?.stepIndex=="number"?x.stepIndex:null;if(S===-1){const q={id:M,messageId:f,index:J.length,stepIndex:Y,type:"text",content:JSON.stringify({text:w}),contentJson:{text:w},agent:k.agent,provider:k.provider,model:k.model,startedAt:Date.now(),completedAt:null,toolName:null,toolCallId:null,toolDurationMs:null};J.push(q),S=J.length-1}else{const q=J[S],O=`${l(q)}${w}`;J[S]={...q,content:JSON.stringify({text:O}),contentJson:{text:O},stepIndex:Y??q.stepIndex??null,completedAt:null}}return p[U]={...k,parts:J},p})},d=x=>{if(!x)return;const f=typeof x.callId=="string"?x.callId:null,M=typeof x.name=="string"?x.name:null;M&&A.setQueryData(["messages",e],w=>{if(!w)return w;const G=[...w];let p=I(G);if(typeof x.messageId=="string"){const R=G.findIndex(O=>O.id===x.messageId);R!==-1&&(p=R)}if(p===-1)return w;const U=G[p],k=U.parts?[...U.parts]:[];let J=-1;f&&(J=k.findIndex(R=>R.toolCallId===f&&R.ephemeral)),J===-1&&!f&&(J=k.findIndex(R=>R.ephemeral&&R.toolName===M));const S=x.args,Y=typeof x.stepIndex=="number"?x.stepIndex:null,q={name:M};if(f&&(q.callId=f),S!==void 0&&(q.args=S),J===-1){const R={id:f?`ephemeral-tool-call-${f}`:`ephemeral-tool-call-${M}-${Date.now()}`,messageId:U.id,index:k.length,stepIndex:Y,type:"tool_call",content:JSON.stringify(q),contentJson:q,agent:U.agent,provider:U.provider,model:U.model,startedAt:Date.now(),completedAt:null,toolName:M,toolCallId:f,toolDurationMs:null,ephemeral:!0};k.push(R)}else{const R=k[J],O={...typeof R.contentJson=="object"&&!Array.isArray(R.contentJson)?R.contentJson:{},name:M};f&&(O.callId=f),S!==void 0&&(O.args=S),k[J]={...R,content:JSON.stringify(O),contentJson:O,stepIndex:Y??R.stepIndex??null,toolCallId:f??R.toolCallId,toolName:M}}return G[p]={...U,parts:k},G})},c=x=>{const f=typeof x?.callId=="string"?x.callId:null;f&&A.setQueryData(["messages",e],M=>{if(!M)return M;let w=!1;const G=M.map(p=>{if(!p.parts?.length)return p;const U=p.parts.filter(k=>!(k.ephemeral&&k.toolCallId===f));return U.length===p.parts.length?p:(w=!0,{...p,parts:U})});return w?G:M})},D=x=>{x&&A.setQueryData(["messages",e],f=>{if(!f)return f;const M=f.findIndex(p=>p.id===x);if(M===-1)return f;const w=f[M];if(!w.parts?.some(p=>p.ephemeral))return f;const G=[...f];return G[M]={...w,parts:w.parts?.filter(p=>!p.ephemeral)??[]},G})},N=x=>{const f=typeof x?.id=="string"?x.id:null;f&&A.setQueryData(["messages",e],M=>{if(!M)return M;const w=[...M],G=w.findIndex(U=>U.id===f);if(G===-1)return M;const p=w[G];return w[G]={...p,status:"complete",completedAt:Date.now()},w})},h=()=>{const x=Date.now();x-B.current<500||(B.current=x,A.invalidateQueries({queryKey:["messages",e]}))},m=new Set(["message.completed","tool.result","finish-step","error"]),y=C.on("*",x=>{const f=x.payload;switch(x.type){case"message.created":{const M=typeof f?.role=="string"?f.role:null,w=typeof f?.id=="string"?f.id:null;M==="assistant"&&w&&(Q.current=w);break}case"message.part.delta":{n(f);break}case"reasoning.delta":{r(f);break}case"message.completed":{const M=typeof f?.id=="string"?f.id:null;M&&Q.current===M&&(Q.current=null),N(f),D(M),A.invalidateQueries({queryKey:["sessions"]});break}case"tool.delta":{(typeof f?.channel=="string"?f.channel:null)==="input"&&d(f);break}case"tool.call":{d(f);break}case"tool.result":{c(f);break}case"tool.approval.required":{const M=typeof f?.callId=="string"?f.callId:null,w=typeof f?.toolName=="string"?f.toolName:null,G=typeof f?.messageId=="string"?f.messageId:null,p=f?.args;M&&w&&G&&o({callId:M,toolName:w,args:p,messageId:G,createdAt:Date.now()});break}case"tool.approval.resolved":{const M=typeof f?.callId=="string"?f.callId:null;M&&s(M);break}case"tool.approval.updated":{const M=typeof f?.callId=="string"?f.callId:null,w=f?.args;M&&E(M,w);break}case"error":{c(f);const M=typeof f?.messageId=="string"?f.messageId:null;M&&D(M);break}case"queue.updated":{const M={currentMessageId:f?.currentMessageId,queuedMessages:f?.queuedMessages??[],queueLength:f?.queueLength??0};A.setQueryData(["queueState",e],M);break}}m.has(x.type)&&h()});return()=>{y(),C.disconnect()}},[e,A,o,s,i,E])}function uI(e){const{pendingApprovals:A,removePendingApproval:g}=Lg(),Q=A,B=u.useCallback(async E=>{if(e)try{await T.approveToolCall(e,E,!0),g(E)}catch(i){console.error("Failed to approve tool call:",i)}},[e,g]),o=u.useCallback(async E=>{if(e)try{await T.approveToolCall(e,E,!1),g(E)}catch(i){console.error("Failed to reject tool call:",i)}},[e,g]),s=u.useCallback(async()=>{if(e)try{await Promise.all(Q.map(E=>T.approveToolCall(e,E.callId,!0)));for(const E of Q)g(E.callId)}catch(E){console.error("Failed to approve all tool calls:",E)}},[e,Q,g]);u.useEffect(()=>{if(!e||Q.length===0)return;const E=i=>{if(i.target instanceof HTMLInputElement||i.target instanceof HTMLTextAreaElement||i.target?.isContentEditable)return;const C=Q[0];i.key==="y"||i.key==="Y"?(i.preventDefault(),B(C.callId)):i.key==="n"||i.key==="N"||i.key==="Escape"?(i.preventDefault(),o(C.callId)):(i.key==="a"||i.key==="A")&&(i.preventDefault(),s())};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e,Q,B,o,s])}const hI=({size:e=22})=>t.jsx("span",{className:"inline-flex items-center justify-center text-foreground",style:{width:e,height:e},dangerouslySetInnerHTML:{__html:`<svg width="${e}" height="${e}" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
103
- <path d="M55.0151 11H45.7732C42.9871 11 41.594 11 40.5458 11.7564C39.4977 12.5128 39.0587 13.8349 38.1807 16.479L28.4934 45.6545C26.899 50.4561 26.1019 52.8569 27.2993 54.5162C28.4967 56.1754 31.0264 56.1754 36.0858 56.1754H38.1307C41.9554 56.1754 43.8677 56.1754 45.0206 57.2527C45.2855 57.5002 45.5155 57.7825 45.7043 58.092C46.5262 59.4389 46.1395 61.3117 45.3662 65.0574C42.291 79.9519 40.7534 87.3991 43.0079 88.8933C43.4871 89.2109 44.0292 89.4215 44.5971 89.5107C47.2691 89.9303 51.1621 83.398 58.9481 70.3336L70.7118 50.5949C72.8831 46.9517 73.9687 45.13 73.6853 43.639C73.5201 42.7697 73.0712 41.9797 72.4091 41.3927C71.2734 40.386 69.1528 40.386 64.9115 40.386C61.2258 40.386 59.3829 40.386 58.2863 39.5068C57.6438 38.9916 57.176 38.2907 56.9467 37.4998C56.5553 36.1498 57.2621 34.4479 58.6757 31.044L62.4033 22.0683C64.4825 17.0618 65.5221 14.5585 64.3345 12.7793C63.1468 11 60.4362 11 55.0151 11Z" fill="currentColor"/>
104
- </svg>`}}),DI={sm:{ring:48,icon:20,iconSize:16},md:{ring:72,icon:32,iconSize:24},lg:{ring:96,icon:40,iconSize:32}},OQ=u.memo(function({status:A,label:g,sublabel:Q,size:B="md"}){const{ring:o,icon:s,iconSize:E}=DI[B],i={position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:o,height:o},C={content:'""',position:"absolute",inset:0,borderRadius:"50%"},a=()=>A==="success"?"rgb(34, 197, 94)":A==="error"?"rgb(239, 68, 68)":"currentColor";return t.jsxs("div",{className:"flex flex-col items-center justify-center gap-5",children:[t.jsxs("div",{style:i,children:[t.jsx("div",{style:{...C,border:"2px solid hsl(var(--muted))"}}),A==="loading"&&t.jsx("div",{className:"animate-spin",style:{...C,border:"2px solid transparent",borderTopColor:"hsl(var(--foreground))",animation:"spin 1s cubic-bezier(0.4, 0, 0.2, 1) infinite"}}),A==="success"&&t.jsx("div",{style:{...C,border:`2px solid ${a()}`,opacity:.3}}),A==="error"&&t.jsx("div",{style:{...C,border:`2px solid ${a()}`,opacity:.3}}),t.jsxs("div",{style:{position:"relative",zIndex:1},children:[A==="loading"&&t.jsx(hI,{size:s}),A==="success"&&t.jsx(HQ,{className:"text-green-500",style:{width:E,height:E}}),A==="error"&&t.jsx(fg,{className:"text-red-500",style:{width:E,height:E}})]})]}),g&&t.jsxs("div",{className:"flex flex-col items-center gap-1",children:[t.jsx("span",{className:"text-sm font-medium text-foreground",children:g}),Q&&t.jsx("span",{className:"text-xs text-muted-foreground",children:Q})]})]})}),wI=[10,25,50,100],be=5,Pe=500,pI=5e3,mI="https://share.ottocode.io/checkout/success",Hg=u.memo(function(){const A=sA(j=>j.isTopupModalOpen),g=sA(j=>j.closeTopupModal),Q=sA(j=>j.balance),B=sA(j=>j.setBalance),o=sA(j=>j.usdcBalance),[s,E]=u.useState("amount"),[i,C]=u.useState(25),[a,I]=u.useState(""),[l,r]=u.useState(!1),[n,d]=u.useState(null),[c,D]=u.useState(!1),[N,h]=u.useState(!1),[m,y]=u.useState(null),[x,f]=u.useState(!1),[M,w]=u.useState(null),[G,p]=u.useState(0),[U,k]=u.useState(!1),J=u.useRef(null),S=l?parseFloat(a)||0:i,Y=u.useCallback(async j=>{if(j<be||j>Pe){d(null);return}D(!0);try{const L=await T.getPolarTopupEstimate(j);d(L)}catch{d(null)}finally{D(!1)}},[]);u.useEffect(()=>{if(A&&S>=be&&s==="amount"){const j=setTimeout(()=>Y(S),300);return()=>clearTimeout(j)}},[A,S,Y,s]);const q=u.useCallback(()=>{J.current&&(clearInterval(J.current),J.current=null),f(!1)},[]);u.useEffect(()=>{A||(q(),E("amount"),y(null),w(null),p(0))},[A,q]),u.useEffect(()=>()=>q(),[q]);const R=u.useCallback(j=>{if(J.current)return;f(!0),p(0);const L=async()=>{try{const AA=await T.getPolarTopupStatus(j);if(console.log("[SetuTopupModal] Poll status:",AA),p(EA=>EA+1),AA?.confirmed){q(),w(AA.amountUsd),localStorage.removeItem("pendingPolarCheckout");const EA=await T.getSetuBalance();EA?.balance!==void 0&&B(EA.balance),E("confirmed")}}catch{p(AA=>AA+1)}};L(),J.current=setInterval(L,pI)},[q,B]),O=j=>{C(j),r(!1),I("")},K=j=>{I(j),r(!0)},v=u.useCallback(j=>{window.self!==window.top?window.parent.postMessage({type:"otto-open-url",url:j},"*"):window.open(j,"_blank")},[]),V=async()=>{if(S<be||S>Pe){tA.error(`Amount must be between $${be} and $${Pe}`);return}h(!0);try{const j=await T.createPolarCheckout(S,mI);if(j.checkoutUrl&&j.checkoutId){const L={url:j.checkoutUrl,checkoutId:j.checkoutId,creditAmount:j.creditAmount,chargeAmount:j.chargeAmount};y(L),localStorage.setItem("pendingPolarCheckout",j.checkoutId),E("checkout"),v(j.checkoutUrl),R(j.checkoutId)}}catch(j){tA.error(j instanceof Error?j.message:"Failed to create checkout")}finally{h(!1)}},_=async()=>{if(m){k(!0);try{const j=await T.getPolarTopupStatus(m.checkoutId);if(console.log("[SetuTopupModal] Manual check status:",j),j?.confirmed){q(),w(j.amountUsd),localStorage.removeItem("pendingPolarCheckout");const L=await T.getSetuBalance();L?.balance!==void 0&&B(L.balance),E("confirmed")}else tA.error("Payment not confirmed yet. Keep waiting or try again.")}catch(j){console.error("[SetuTopupModal] Check failed:",j),tA.error("Failed to check payment status")}finally{k(!1)}}},X=()=>{g()},iA=S>=be&&S<=Pe,mA=s==="confirmed"?"Payment Confirmed":s==="checkout"?"Waiting for Payment":"Add Credits";return t.jsx(qe,{isOpen:A,onClose:g,title:mA,maxWidth:"md",children:t.jsxs("div",{className:"space-y-6",children:[s==="confirmed"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"py-4",children:t.jsx(OQ,{status:"success",label:`+$${M?.toFixed(2)??m?.creditAmount.toFixed(2)}`,sublabel:"Credits added to your balance"})}),t.jsx("button",{type:"button",onClick:X,className:"w-full h-12 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors flex items-center justify-center gap-2",children:"Done"})]}),s==="checkout"&&m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"py-4",children:[t.jsx(OQ,{status:"loading",label:"Complete your payment",sublabel:"A checkout window has been opened"}),t.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4 px-3 py-1.5 bg-muted/40 rounded-full w-fit mx-auto",children:[t.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-blue-500 animate-pulse"}),t.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:x?`Checking... (${G})`:"Paused"})]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("button",{type:"button",onClick:_,disabled:U,className:"w-full h-12 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2",children:[U?t.jsx(uA,{className:"w-4 h-4 animate-spin"}):t.jsx(TA,{className:"w-4 h-4"}),U?"Checking...":"Check Now"]}),t.jsxs("button",{type:"button",onClick:()=>v(m.url),className:"w-full h-11 bg-transparent border border-border text-foreground rounded-lg font-medium hover:bg-muted/50 transition-colors flex items-center justify-center gap-2",children:[t.jsx(SA,{className:"w-4 h-4"}),"Open Checkout Again"]})]}),t.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Status checks automatically every 5 seconds. You can close this and it will keep checking."})]}),s==="amount"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between py-3 px-4 bg-muted/40 rounded-lg",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Current Balance"}),t.jsxs("span",{className:"text-lg font-mono font-semibold",children:["$",Q?.toFixed(2)??"0.00"]})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"grid grid-cols-4 gap-2",children:wI.map(j=>t.jsxs("button",{type:"button",onClick:()=>O(j),className:`h-12 text-base font-mono rounded-lg border-2 transition-all ${!l&&i===j?"bg-foreground text-background border-foreground":"bg-transparent border-border text-foreground hover:border-foreground/40"}`,children:["$",j]},j))}),t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground text-lg",children:"$"}),t.jsx("input",{type:"number",placeholder:"Custom",value:a,onChange:j=>K(j.target.value),onFocus:()=>r(!0),min:be,max:Pe,step:"1",className:`w-full h-12 pl-8 pr-4 text-base font-mono bg-transparent border-2 rounded-lg outline-none transition-all ${l?"border-foreground":"border-border focus:border-foreground/40"}`})]})]}),t.jsx("div",{className:`grid transition-all duration-200 ease-out ${iA?"grid-rows-[1fr] opacity-100":"grid-rows-[0fr] opacity-0"}`,children:t.jsx("div",{className:"overflow-hidden",children:t.jsx("div",{className:"space-y-3 py-4 border-t border-border",children:c?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Credits"}),t.jsx("div",{className:"h-6 w-16 bg-muted/60 rounded animate-pulse"})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Fee"}),t.jsx("div",{className:"h-4 w-12 bg-muted/60 rounded animate-pulse"})]}),t.jsxs("div",{className:"flex justify-between items-center pt-3 border-t border-border",children:[t.jsx("span",{className:"font-medium",children:"Total"}),t.jsx("div",{className:"h-7 w-20 bg-muted/60 rounded animate-pulse"})]})]}):n?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Credits"}),t.jsxs("span",{className:"font-mono text-lg",children:["$",n.creditAmount.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Fee"}),t.jsxs("span",{className:"font-mono text-sm text-muted-foreground",children:["+$",n.feeAmount.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between items-center pt-3 border-t border-border",children:[t.jsx("span",{className:"font-medium",children:"Total"}),t.jsxs("span",{className:"font-mono text-xl font-semibold",children:["$",n.chargeAmount.toFixed(2)]})]})]}):null})})}),t.jsxs("button",{type:"button",onClick:V,disabled:!iA||N,className:"w-full h-12 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:[N?t.jsx(uA,{className:"w-4 h-4 animate-spin"}):t.jsx(_e,{className:"w-4 h-4"}),"Pay with Card"]}),t.jsxs("div",{className:"relative pt-6",children:[t.jsxs("div",{className:"absolute inset-x-0 top-0 flex items-center",children:[t.jsx("div",{className:"flex-1 h-px bg-border"}),t.jsx("span",{className:"px-3 text-xs text-muted-foreground",children:"OR"}),t.jsx("div",{className:"flex-1 h-px bg-border"})]}),t.jsxs("div",{className:"flex items-start gap-3 p-4 bg-muted/30 rounded-lg",children:[t.jsx(yg,{className:"w-5 h-5 text-muted-foreground mt-0.5"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"font-medium text-sm",children:"Pay with USDC"}),o!==null&&t.jsxs("span",{className:"text-xs font-mono text-muted-foreground",children:[o.toFixed(2)," USDC"]})]}),t.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send USDC to your Setu wallet. Auto top-up when balance is low."})]})]})]})]})]})})}),xI=u.memo(function({sessionId:A,onSelectSession:g}){const{data:Q=[],isLoading:B}=Mt(A),{data:o=[]}=Yt();co(A),uI(A);const s=u.useMemo(()=>o.find(i=>i.id===A),[o,A]),E=u.useMemo(()=>Q.some(i=>i.role==="assistant"&&i.status==="pending"),[Q]);return B?t.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:"Loading messages..."}):t.jsxs(t.Fragment,{children:[t.jsx(dI,{messages:Q,sessionId:A,session:s,isGenerating:E,onSelectSession:g}),t.jsx(Hg,{})]})}),fI=u.memo(function({session:A,isActive:g,onClick:Q}){const B=C=>{const a=new Date(C),l=new Date().getTime()-a.getTime(),r=Math.floor(l/6e4),n=Math.floor(r/60),d=Math.floor(n/24);return r<1?"just now":r<60?`${r}m ago`:n<24?`${n}h ago`:d<7?`${d}d ago`:a.toLocaleDateString()},o=A.sessionType==="branch";return t.jsx("button",{type:"button",onClick:Q,className:`group w-full rounded-lg px-3 py-3 text-left transition-colors duration-150 ${g?"bg-primary/10":"hover:bg-muted/20"}`,children:t.jsxs("div",{className:"flex items-start gap-3",children:[o?t.jsx(HA,{className:`h-4 w-4 shrink-0 mt-1 text-muted-foreground ${g?"text-primary":""}`}):t.jsx(QB,{className:`h-4 w-4 shrink-0 mt-1 text-muted-foreground ${g?"text-primary":""}`}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"truncate text-sm font-semibold text-foreground",children:A.title||`Session ${A.id.slice(0,8)}`}),o&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-violet-500/10 text-violet-600 dark:text-violet-400 rounded-full shrink-0",children:"branch"})]}),t.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs text-muted-foreground/80",children:[A.agent&&t.jsx("span",{className:"uppercase",children:A.agent}),A.agent&&t.jsx("span",{children:"•"}),t.jsx("span",{children:B(A.lastActiveAt||A.createdAt)})]})]})]})})}),Pg=UA(e=>({currentFocus:null,sessionIndex:0,gitFileIndex:0,setFocus:A=>e({currentFocus:A}),setSessionIndex:A=>e({sessionIndex:A}),setGitFileIndex:A=>e({gitFileIndex:A}),resetGitFileIndex:()=>e({gitFileIndex:0}),resetSessionIndex:()=>e({sessionIndex:0})})),NI=u.memo(function({activeSessionId:A,onSelectSession:g}){const{data:Q=[],isLoading:B}=Yt(),{currentFocus:o,sessionIndex:s}=Pg(),E=u.useRef(new Map),i=u.useCallback(a=>{g(a)},[g]),C=u.useMemo(()=>Q.map(a=>({id:a.id,title:a.title,agent:a.agent,createdAt:a.createdAt})),[Q]);return u.useEffect(()=>{o==="sessions"&&E.current.get(s)?.scrollIntoView({block:"nearest",behavior:"smooth"})},[o,s]),B?t.jsxs("div",{className:"flex flex-col gap-2 px-2 py-2",children:[t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"})]}):C.length===0?t.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground/80",children:"No sessions yet. Create one to get started."}):t.jsx("div",{className:"flex flex-col gap-1 px-2 py-2 overflow-y-auto scrollbar-hide",children:C.map((a,I)=>{const l=Q.find(n=>n.id===a.id);if(!l)return null;const r=o==="sessions"&&s===I;return t.jsx("div",{ref:n=>{n?E.current.set(I,n):E.current.delete(I)},className:r?"ring-1 ring-primary/40 rounded-md":"",children:t.jsx(fI,{session:l,isActive:a.id===A,onClick:()=>i(a.id)})},a.id)})})}),kI={js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"plaintext",svelte:"svelte"};function MI(e){const A=e.split(".").pop()?.toLowerCase()??"";return A?kI[A]??"plaintext":"plaintext"}function yI(e){const A=e.split("/");return A[A.length-1]}function GI({diff:e}){const A=document?.documentElement.classList.contains("dark")?ae:re,g=e.language&&e.language.trim().length>0?e.language:MI(e.file),Q=yI(e.file);if(e.isNewFile&&e.content)return t.jsxs("div",{className:"flex flex-col h-full bg-background",children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between min-h-10",children:[t.jsx("span",{className:"font-mono text-sm text-foreground truncate",title:e.file,children:Q}),t.jsxs("div",{className:"flex items-center gap-3 text-xs flex-shrink-0",children:[t.jsxs("span",{className:"text-green-600 dark:text-green-500",children:["+",e.insertions]}),t.jsx("span",{className:"text-muted-foreground",children:g})]})]}),t.jsx("div",{className:"px-4 py-3 bg-green-500/10 border-b border-green-500/20",children:t.jsxs("p",{className:"text-sm text-green-600 dark:text-green-400 font-medium",children:["New file: ",e.insertions," lines"]})}),t.jsx("div",{className:"flex-1 overflow-auto",children:t.jsx(jA,{language:g,style:A,showLineNumbers:!0,customStyle:{margin:0,padding:"1rem",background:"transparent"},lineNumberStyle:{minWidth:"3em",paddingRight:"1em",color:"var(--color-muted-foreground)",userSelect:"none"},children:e.content})})]});if(e.isBinary)return t.jsxs("div",{className:"flex flex-col h-full bg-background",children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between min-h-10",children:[t.jsx("span",{className:"font-mono text-sm text-foreground truncate",title:e.file,children:Q}),t.jsx("div",{className:"flex items-center gap-3 text-xs flex-shrink-0",children:t.jsx("span",{className:"text-muted-foreground",children:"Binary file"})})]}),t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx("div",{className:"p-4 text-center",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"Binary file - cannot display diff"})})})]});const B=e.diff.split(`
102
+ `)}}}catch(g){g instanceof Error&&g.name==="AbortError"||console.error("[SSE] Connection error:",g)}}disconnect(){this.running=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}on(A,g){return this.handlers.has(A)||this.handlers.set(A,new Set),this.handlers.get(A)?.add(g),()=>{this.off(A,g)}}off(A,g){const Q=this.handlers.get(A);Q&&(Q.delete(g),Q.size===0&&this.handlers.delete(A))}emit(A){const g=this.handlers.get(A.type);if(g)for(const B of g)B(A);const Q=this.handlers.get("*");if(Q)for(const B of Q)B(A)}}function co(e){const A=nA(),g=u.useRef(null),Q=u.useRef(null),B=u.useRef(0),{addPendingApproval:o,removePendingApproval:s,updatePendingApproval:E,setPendingApprovals:i}=Lg();u.useEffect(()=>{if(!e){console.log("[useSessionStream] No sessionId, skipping");return}Q.current=null,T.getPendingApprovals(e).then(x=>{x.ok&&x.pending.length>0?i(x.pending):i([])}).catch(()=>{i([])});const C=new lo;g.current=C;const a=T.getStreamUrl(e);console.log("[useSessionStream] Connecting to stream:",a),C.connect(a);const I=x=>{if(Q.current){const f=x.findIndex(M=>M.id===Q.current);if(f!==-1)return f}for(let f=x.length-1;f>=0;f-=1){const M=x[f];if(M.role==="assistant"&&M.status!=="complete")return f}return-1},l=x=>{if(x.contentJson&&typeof x.contentJson=="object"&&!Array.isArray(x.contentJson)&&"text"in x.contentJson)return String(x.contentJson.text??"");if(typeof x.content=="string"){try{const f=JSON.parse(x.content);if(f&&typeof f.text=="string")return f.text}catch{}return x.content}return""},r=x=>{const f=typeof x?.messageId=="string"?x.messageId:null,M=typeof x?.partId=="string"?x.partId:null,w=typeof x?.delta=="string"?x.delta:null;!f||!M||w===null||A.setQueryData(["messages",e],G=>{if(!G)return G;const p=[...G],U=p.findIndex(q=>q.id===f);if(U===-1)return G;const k=p[U],J=k.parts?[...k.parts]:[];let S=J.findIndex(q=>q.id===M);const Y=typeof x?.stepIndex=="number"?x.stepIndex:null;if(S===-1){const q={id:M,messageId:f,index:J.length,stepIndex:Y,type:"reasoning",content:JSON.stringify({text:w}),contentJson:{text:w},agent:k.agent,provider:k.provider,model:k.model,startedAt:Date.now(),completedAt:null,toolName:null,toolCallId:null,toolDurationMs:null};J.push(q),S=J.length-1}else{const q=J[S],O=`${l(q)}${w}`;J[S]={...q,content:JSON.stringify({text:O}),contentJson:{text:O},stepIndex:Y??q.stepIndex??null,completedAt:null}}return p[U]={...k,parts:J},p})},n=x=>{const f=typeof x?.messageId=="string"?x.messageId:null,M=typeof x?.partId=="string"?x.partId:null,w=typeof x?.delta=="string"?x.delta:null;!f||!M||w===null||A.setQueryData(["messages",e],G=>{if(!G)return G;const p=[...G],U=p.findIndex(q=>q.id===f);if(U===-1)return G;const k=p[U],J=k.parts?[...k.parts]:[];let S=J.findIndex(q=>q.id===M);const Y=typeof x?.stepIndex=="number"?x.stepIndex:null;if(S===-1){const q={id:M,messageId:f,index:J.length,stepIndex:Y,type:"text",content:JSON.stringify({text:w}),contentJson:{text:w},agent:k.agent,provider:k.provider,model:k.model,startedAt:Date.now(),completedAt:null,toolName:null,toolCallId:null,toolDurationMs:null};J.push(q),S=J.length-1}else{const q=J[S],O=`${l(q)}${w}`;J[S]={...q,content:JSON.stringify({text:O}),contentJson:{text:O},stepIndex:Y??q.stepIndex??null,completedAt:null}}return p[U]={...k,parts:J},p})},d=x=>{if(!x)return;const f=typeof x.callId=="string"?x.callId:null,M=typeof x.name=="string"?x.name:null;M&&A.setQueryData(["messages",e],w=>{if(!w)return w;const G=[...w];let p=I(G);if(typeof x.messageId=="string"){const R=G.findIndex(O=>O.id===x.messageId);R!==-1&&(p=R)}if(p===-1)return w;const U=G[p],k=U.parts?[...U.parts]:[];let J=-1;f&&(J=k.findIndex(R=>R.toolCallId===f&&R.ephemeral)),J===-1&&!f&&(J=k.findIndex(R=>R.ephemeral&&R.toolName===M));const S=x.args,Y=typeof x.stepIndex=="number"?x.stepIndex:null,q={name:M};if(f&&(q.callId=f),S!==void 0&&(q.args=S),J===-1){const R={id:f?`ephemeral-tool-call-${f}`:`ephemeral-tool-call-${M}-${Date.now()}`,messageId:U.id,index:k.length,stepIndex:Y,type:"tool_call",content:JSON.stringify(q),contentJson:q,agent:U.agent,provider:U.provider,model:U.model,startedAt:Date.now(),completedAt:null,toolName:M,toolCallId:f,toolDurationMs:null,ephemeral:!0};k.push(R)}else{const R=k[J],O={...typeof R.contentJson=="object"&&!Array.isArray(R.contentJson)?R.contentJson:{},name:M};f&&(O.callId=f),S!==void 0&&(O.args=S),k[J]={...R,content:JSON.stringify(O),contentJson:O,stepIndex:Y??R.stepIndex??null,toolCallId:f??R.toolCallId,toolName:M}}return G[p]={...U,parts:k},G})},c=x=>{const f=typeof x?.callId=="string"?x.callId:null;f&&A.setQueryData(["messages",e],M=>{if(!M)return M;let w=!1;const G=M.map(p=>{if(!p.parts?.length)return p;const U=p.parts.filter(k=>!(k.ephemeral&&k.toolCallId===f));return U.length===p.parts.length?p:(w=!0,{...p,parts:U})});return w?G:M})},D=x=>{x&&A.setQueryData(["messages",e],f=>{if(!f)return f;const M=f.findIndex(p=>p.id===x);if(M===-1)return f;const w=f[M];if(!w.parts?.some(p=>p.ephemeral))return f;const G=[...f];return G[M]={...w,parts:w.parts?.filter(p=>!p.ephemeral)??[]},G})},N=x=>{const f=typeof x?.id=="string"?x.id:null;f&&A.setQueryData(["messages",e],M=>{if(!M)return M;const w=[...M],G=w.findIndex(U=>U.id===f);if(G===-1)return M;const p=w[G];return w[G]={...p,status:"complete",completedAt:Date.now()},w})},h=()=>{const x=Date.now();x-B.current<500||(B.current=x,A.invalidateQueries({queryKey:["messages",e]}))},m=new Set(["message.completed","tool.result","finish-step","error"]),y=C.on("*",x=>{const f=x.payload;switch(x.type){case"message.created":{const M=typeof f?.role=="string"?f.role:null,w=typeof f?.id=="string"?f.id:null;M==="assistant"&&w&&(Q.current=w);break}case"message.part.delta":{n(f);break}case"reasoning.delta":{r(f);break}case"message.completed":{const M=typeof f?.id=="string"?f.id:null;M&&Q.current===M&&(Q.current=null),N(f),D(M),A.invalidateQueries({queryKey:["sessions"]});break}case"tool.delta":{(typeof f?.channel=="string"?f.channel:null)==="input"&&d(f);break}case"tool.call":{d(f);break}case"tool.result":{c(f);break}case"tool.approval.required":{const M=typeof f?.callId=="string"?f.callId:null,w=typeof f?.toolName=="string"?f.toolName:null,G=typeof f?.messageId=="string"?f.messageId:null,p=f?.args;M&&w&&G&&o({callId:M,toolName:w,args:p,messageId:G,createdAt:Date.now()});break}case"tool.approval.resolved":{const M=typeof f?.callId=="string"?f.callId:null;M&&s(M);break}case"tool.approval.updated":{const M=typeof f?.callId=="string"?f.callId:null,w=f?.args;M&&E(M,w);break}case"error":{c(f);const M=typeof f?.messageId=="string"?f.messageId:null;M&&D(M);break}case"queue.updated":{const M={currentMessageId:f?.currentMessageId,queuedMessages:f?.queuedMessages??[],queueLength:f?.queueLength??0};A.setQueryData(["queueState",e],M);break}}m.has(x.type)&&h()});return()=>{y(),C.disconnect()}},[e,A,o,s,i,E])}function uI(e){const{pendingApprovals:A,removePendingApproval:g}=Lg(),Q=A,B=u.useCallback(async E=>{if(e)try{await T.approveToolCall(e,E,!0),g(E)}catch(i){console.error("Failed to approve tool call:",i)}},[e,g]),o=u.useCallback(async E=>{if(e)try{await T.approveToolCall(e,E,!1),g(E)}catch(i){console.error("Failed to reject tool call:",i)}},[e,g]),s=u.useCallback(async()=>{if(e)try{await Promise.all(Q.map(E=>T.approveToolCall(e,E.callId,!0)));for(const E of Q)g(E.callId)}catch(E){console.error("Failed to approve all tool calls:",E)}},[e,Q,g]);u.useEffect(()=>{if(!e||Q.length===0)return;const E=i=>{if(i.target instanceof HTMLInputElement||i.target instanceof HTMLTextAreaElement||i.target?.isContentEditable)return;const C=Q[0];i.key==="y"||i.key==="Y"?(i.preventDefault(),B(C.callId)):i.key==="n"||i.key==="N"||i.key==="Escape"?(i.preventDefault(),o(C.callId)):(i.key==="a"||i.key==="A")&&(i.preventDefault(),s())};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e,Q,B,o,s])}const hI=({height:e=22})=>{const A=Math.round(e*2.4686468646864688);return t.jsx("svg",{width:A,height:e,viewBox:"0 0 748 303",fill:"currentColor",className:"text-foreground","aria-label":"otto",role:"img",children:t.jsx("path",{d:"M192.877 257.682C192.877 263.287 191.783 268.551 189.596 273.473C187.545 278.395 184.674 282.701 180.982 286.393C177.428 289.947 173.189 292.818 168.268 295.006C163.482 297.057 158.287 298.082 152.682 298.082H44.1953C38.7266 298.082 33.5312 297.057 28.6094 295.006C23.6875 292.818 19.3809 289.947 15.6895 286.393C12.1348 282.701 9.26367 278.395 7.07617 273.473C5.02539 268.551 4 263.287 4 257.682V120.074C4 114.469 5.02539 109.205 7.07617 104.283C9.26367 99.3613 12.1348 95.123 15.6895 91.5684C19.3809 87.877 23.6875 85.0059 28.6094 82.9551C33.5312 80.7676 38.7266 79.6738 44.1953 79.6738H152.682C158.287 79.6738 163.482 80.7676 168.268 82.9551C173.189 85.0059 177.428 87.877 180.982 91.5684C184.674 95.123 187.545 99.3613 189.596 104.283C191.783 109.205 192.877 114.469 192.877 120.074V257.682ZM44.1953 120.074V257.682H152.682V120.074H44.1953ZM331.715 4V298.082H289.674V46.041H239.225V4H331.715ZM478.961 4V298.082H436.92V46.041H386.471V4H478.961ZM743.717 257.682C743.717 263.287 742.623 268.551 740.436 273.473C738.385 278.395 735.514 282.701 731.822 286.393C728.268 289.947 724.029 292.818 719.107 295.006C714.322 297.057 709.127 298.082 703.521 298.082H595.035C589.566 298.082 584.371 297.057 579.449 295.006C574.527 292.818 570.221 289.947 566.529 286.393C562.975 282.701 560.104 278.395 557.916 273.473C555.865 268.551 554.84 263.287 554.84 257.682V120.074C554.84 114.469 555.865 109.205 557.916 104.283C560.104 99.3613 562.975 95.123 566.529 91.5684C570.221 87.877 574.527 85.0059 579.449 82.9551C584.371 80.7676 589.566 79.6738 595.035 79.6738H703.521C709.127 79.6738 714.322 80.7676 719.107 82.9551C724.029 85.0059 728.268 87.877 731.822 91.5684C735.514 95.123 738.385 99.3613 740.436 104.283C742.623 109.205 743.717 114.469 743.717 120.074V257.682ZM595.035 120.074V257.682H703.521V120.074H595.035Z"})})},DI={sm:{ring:48,icon:20,iconSize:16},md:{ring:72,icon:32,iconSize:24},lg:{ring:96,icon:40,iconSize:32}},OQ=u.memo(function({status:A,label:g,sublabel:Q,size:B="md"}){const{ring:o,icon:s,iconSize:E}=DI[B],i={position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:o,height:o},C={content:'""',position:"absolute",inset:0,borderRadius:"50%"},a=()=>A==="success"?"rgb(34, 197, 94)":A==="error"?"rgb(239, 68, 68)":"currentColor";return t.jsxs("div",{className:"flex flex-col items-center justify-center gap-5",children:[t.jsxs("div",{style:i,children:[t.jsx("div",{style:{...C,border:"2px solid hsl(var(--muted))"}}),A==="loading"&&t.jsx("div",{className:"animate-spin",style:{...C,border:"2px solid transparent",borderTopColor:"hsl(var(--foreground))",animation:"spin 1s cubic-bezier(0.4, 0, 0.2, 1) infinite"}}),A==="success"&&t.jsx("div",{style:{...C,border:`2px solid ${a()}`,opacity:.3}}),A==="error"&&t.jsx("div",{style:{...C,border:`2px solid ${a()}`,opacity:.3}}),t.jsxs("div",{style:{position:"relative",zIndex:1},children:[A==="loading"&&t.jsx(hI,{height:Math.round(s*.65)}),A==="success"&&t.jsx(HQ,{className:"text-green-500",style:{width:E,height:E}}),A==="error"&&t.jsx(fg,{className:"text-red-500",style:{width:E,height:E}})]})]}),g&&t.jsxs("div",{className:"flex flex-col items-center gap-1",children:[t.jsx("span",{className:"text-sm font-medium text-foreground",children:g}),Q&&t.jsx("span",{className:"text-xs text-muted-foreground",children:Q})]})]})}),wI=[10,25,50,100],be=5,Pe=500,pI=5e3,mI="https://share.ottocode.io/checkout/success",Hg=u.memo(function(){const A=sA(j=>j.isTopupModalOpen),g=sA(j=>j.closeTopupModal),Q=sA(j=>j.balance),B=sA(j=>j.setBalance),o=sA(j=>j.usdcBalance),[s,E]=u.useState("amount"),[i,C]=u.useState(25),[a,I]=u.useState(""),[l,r]=u.useState(!1),[n,d]=u.useState(null),[c,D]=u.useState(!1),[N,h]=u.useState(!1),[m,y]=u.useState(null),[x,f]=u.useState(!1),[M,w]=u.useState(null),[G,p]=u.useState(0),[U,k]=u.useState(!1),J=u.useRef(null),S=l?parseFloat(a)||0:i,Y=u.useCallback(async j=>{if(j<be||j>Pe){d(null);return}D(!0);try{const L=await T.getPolarTopupEstimate(j);d(L)}catch{d(null)}finally{D(!1)}},[]);u.useEffect(()=>{if(A&&S>=be&&s==="amount"){const j=setTimeout(()=>Y(S),300);return()=>clearTimeout(j)}},[A,S,Y,s]);const q=u.useCallback(()=>{J.current&&(clearInterval(J.current),J.current=null),f(!1)},[]);u.useEffect(()=>{A||(q(),E("amount"),y(null),w(null),p(0))},[A,q]),u.useEffect(()=>()=>q(),[q]);const R=u.useCallback(j=>{if(J.current)return;f(!0),p(0);const L=async()=>{try{const AA=await T.getPolarTopupStatus(j);if(console.log("[SetuTopupModal] Poll status:",AA),p(EA=>EA+1),AA?.confirmed){q(),w(AA.amountUsd),localStorage.removeItem("pendingPolarCheckout");const EA=await T.getSetuBalance();EA?.balance!==void 0&&B(EA.balance),E("confirmed")}}catch{p(AA=>AA+1)}};L(),J.current=setInterval(L,pI)},[q,B]),O=j=>{C(j),r(!1),I("")},K=j=>{I(j),r(!0)},v=u.useCallback(j=>{window.self!==window.top?window.parent.postMessage({type:"otto-open-url",url:j},"*"):window.open(j,"_blank")},[]),V=async()=>{if(S<be||S>Pe){tA.error(`Amount must be between $${be} and $${Pe}`);return}h(!0);try{const j=await T.createPolarCheckout(S,mI);if(j.checkoutUrl&&j.checkoutId){const L={url:j.checkoutUrl,checkoutId:j.checkoutId,creditAmount:j.creditAmount,chargeAmount:j.chargeAmount};y(L),localStorage.setItem("pendingPolarCheckout",j.checkoutId),E("checkout"),v(j.checkoutUrl),R(j.checkoutId)}}catch(j){tA.error(j instanceof Error?j.message:"Failed to create checkout")}finally{h(!1)}},_=async()=>{if(m){k(!0);try{const j=await T.getPolarTopupStatus(m.checkoutId);if(console.log("[SetuTopupModal] Manual check status:",j),j?.confirmed){q(),w(j.amountUsd),localStorage.removeItem("pendingPolarCheckout");const L=await T.getSetuBalance();L?.balance!==void 0&&B(L.balance),E("confirmed")}else tA.error("Payment not confirmed yet. Keep waiting or try again.")}catch(j){console.error("[SetuTopupModal] Check failed:",j),tA.error("Failed to check payment status")}finally{k(!1)}}},X=()=>{g()},iA=S>=be&&S<=Pe,mA=s==="confirmed"?"Payment Confirmed":s==="checkout"?"Waiting for Payment":"Add Credits";return t.jsx(qe,{isOpen:A,onClose:g,title:mA,maxWidth:"md",children:t.jsxs("div",{className:"space-y-6",children:[s==="confirmed"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"py-4",children:t.jsx(OQ,{status:"success",label:`+$${M?.toFixed(2)??m?.creditAmount.toFixed(2)}`,sublabel:"Credits added to your balance"})}),t.jsx("button",{type:"button",onClick:X,className:"w-full h-12 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors flex items-center justify-center gap-2",children:"Done"})]}),s==="checkout"&&m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"py-4",children:[t.jsx(OQ,{status:"loading",label:"Complete your payment",sublabel:"A checkout window has been opened"}),t.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4 px-3 py-1.5 bg-muted/40 rounded-full w-fit mx-auto",children:[t.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-blue-500 animate-pulse"}),t.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:x?`Checking... (${G})`:"Paused"})]})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("button",{type:"button",onClick:_,disabled:U,className:"w-full h-12 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2",children:[U?t.jsx(uA,{className:"w-4 h-4 animate-spin"}):t.jsx(TA,{className:"w-4 h-4"}),U?"Checking...":"Check Now"]}),t.jsxs("button",{type:"button",onClick:()=>v(m.url),className:"w-full h-11 bg-transparent border border-border text-foreground rounded-lg font-medium hover:bg-muted/50 transition-colors flex items-center justify-center gap-2",children:[t.jsx(SA,{className:"w-4 h-4"}),"Open Checkout Again"]})]}),t.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Status checks automatically every 5 seconds. You can close this and it will keep checking."})]}),s==="amount"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between py-3 px-4 bg-muted/40 rounded-lg",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Current Balance"}),t.jsxs("span",{className:"text-lg font-mono font-semibold",children:["$",Q?.toFixed(2)??"0.00"]})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"grid grid-cols-4 gap-2",children:wI.map(j=>t.jsxs("button",{type:"button",onClick:()=>O(j),className:`h-12 text-base font-mono rounded-lg border-2 transition-all ${!l&&i===j?"bg-foreground text-background border-foreground":"bg-transparent border-border text-foreground hover:border-foreground/40"}`,children:["$",j]},j))}),t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground text-lg",children:"$"}),t.jsx("input",{type:"number",placeholder:"Custom",value:a,onChange:j=>K(j.target.value),onFocus:()=>r(!0),min:be,max:Pe,step:"1",className:`w-full h-12 pl-8 pr-4 text-base font-mono bg-transparent border-2 rounded-lg outline-none transition-all ${l?"border-foreground":"border-border focus:border-foreground/40"}`})]})]}),t.jsx("div",{className:`grid transition-all duration-200 ease-out ${iA?"grid-rows-[1fr] opacity-100":"grid-rows-[0fr] opacity-0"}`,children:t.jsx("div",{className:"overflow-hidden",children:t.jsx("div",{className:"space-y-3 py-4 border-t border-border",children:c?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Credits"}),t.jsx("div",{className:"h-6 w-16 bg-muted/60 rounded animate-pulse"})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Fee"}),t.jsx("div",{className:"h-4 w-12 bg-muted/60 rounded animate-pulse"})]}),t.jsxs("div",{className:"flex justify-between items-center pt-3 border-t border-border",children:[t.jsx("span",{className:"font-medium",children:"Total"}),t.jsx("div",{className:"h-7 w-20 bg-muted/60 rounded animate-pulse"})]})]}):n?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Credits"}),t.jsxs("span",{className:"font-mono text-lg",children:["$",n.creditAmount.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Fee"}),t.jsxs("span",{className:"font-mono text-sm text-muted-foreground",children:["+$",n.feeAmount.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between items-center pt-3 border-t border-border",children:[t.jsx("span",{className:"font-medium",children:"Total"}),t.jsxs("span",{className:"font-mono text-xl font-semibold",children:["$",n.chargeAmount.toFixed(2)]})]})]}):null})})}),t.jsxs("button",{type:"button",onClick:V,disabled:!iA||N,className:"w-full h-12 bg-foreground text-background rounded-lg font-medium hover:bg-foreground/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:[N?t.jsx(uA,{className:"w-4 h-4 animate-spin"}):t.jsx(_e,{className:"w-4 h-4"}),"Pay with Card"]}),t.jsxs("div",{className:"relative pt-6",children:[t.jsxs("div",{className:"absolute inset-x-0 top-0 flex items-center",children:[t.jsx("div",{className:"flex-1 h-px bg-border"}),t.jsx("span",{className:"px-3 text-xs text-muted-foreground",children:"OR"}),t.jsx("div",{className:"flex-1 h-px bg-border"})]}),t.jsxs("div",{className:"flex items-start gap-3 p-4 bg-muted/30 rounded-lg",children:[t.jsx(yg,{className:"w-5 h-5 text-muted-foreground mt-0.5"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"font-medium text-sm",children:"Pay with USDC"}),o!==null&&t.jsxs("span",{className:"text-xs font-mono text-muted-foreground",children:[o.toFixed(2)," USDC"]})]}),t.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send USDC to your Setu wallet. Auto top-up when balance is low."})]})]})]})]})]})})}),xI=u.memo(function({sessionId:A,onSelectSession:g}){const{data:Q=[],isLoading:B}=Mt(A),{data:o=[]}=Yt();co(A),uI(A);const s=u.useMemo(()=>o.find(i=>i.id===A),[o,A]),E=u.useMemo(()=>Q.some(i=>i.role==="assistant"&&i.status==="pending"),[Q]);return B?t.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:"Loading messages..."}):t.jsxs(t.Fragment,{children:[t.jsx(dI,{messages:Q,sessionId:A,session:s,isGenerating:E,onSelectSession:g}),t.jsx(Hg,{})]})}),fI=u.memo(function({session:A,isActive:g,onClick:Q}){const B=C=>{const a=new Date(C),l=new Date().getTime()-a.getTime(),r=Math.floor(l/6e4),n=Math.floor(r/60),d=Math.floor(n/24);return r<1?"just now":r<60?`${r}m ago`:n<24?`${n}h ago`:d<7?`${d}d ago`:a.toLocaleDateString()},o=A.sessionType==="branch";return t.jsx("button",{type:"button",onClick:Q,className:`group w-full rounded-lg px-3 py-3 text-left transition-colors duration-150 ${g?"bg-primary/10":"hover:bg-muted/20"}`,children:t.jsxs("div",{className:"flex items-start gap-3",children:[o?t.jsx(HA,{className:`h-4 w-4 shrink-0 mt-1 text-muted-foreground ${g?"text-primary":""}`}):t.jsx(QB,{className:`h-4 w-4 shrink-0 mt-1 text-muted-foreground ${g?"text-primary":""}`}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"truncate text-sm font-semibold text-foreground",children:A.title||`Session ${A.id.slice(0,8)}`}),o&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-violet-500/10 text-violet-600 dark:text-violet-400 rounded-full shrink-0",children:"branch"})]}),t.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs text-muted-foreground/80",children:[A.agent&&t.jsx("span",{className:"uppercase",children:A.agent}),A.agent&&t.jsx("span",{children:"•"}),t.jsx("span",{children:B(A.lastActiveAt||A.createdAt)})]})]})]})})}),Pg=UA(e=>({currentFocus:null,sessionIndex:0,gitFileIndex:0,setFocus:A=>e({currentFocus:A}),setSessionIndex:A=>e({sessionIndex:A}),setGitFileIndex:A=>e({gitFileIndex:A}),resetGitFileIndex:()=>e({gitFileIndex:0}),resetSessionIndex:()=>e({sessionIndex:0})})),NI=u.memo(function({activeSessionId:A,onSelectSession:g}){const{data:Q=[],isLoading:B}=Yt(),{currentFocus:o,sessionIndex:s}=Pg(),E=u.useRef(new Map),i=u.useCallback(a=>{g(a)},[g]),C=u.useMemo(()=>Q.map(a=>({id:a.id,title:a.title,agent:a.agent,createdAt:a.createdAt})),[Q]);return u.useEffect(()=>{o==="sessions"&&E.current.get(s)?.scrollIntoView({block:"nearest",behavior:"smooth"})},[o,s]),B?t.jsxs("div",{className:"flex flex-col gap-2 px-2 py-2",children:[t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"}),t.jsx("div",{className:"h-12 rounded-md bg-muted/30 animate-pulse"})]}):C.length===0?t.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground/80",children:"No sessions yet. Create one to get started."}):t.jsx("div",{className:"flex flex-col gap-1 px-2 py-2 overflow-y-auto scrollbar-hide",children:C.map((a,I)=>{const l=Q.find(n=>n.id===a.id);if(!l)return null;const r=o==="sessions"&&s===I;return t.jsx("div",{ref:n=>{n?E.current.set(I,n):E.current.delete(I)},className:r?"ring-1 ring-primary/40 rounded-md":"",children:t.jsx(fI,{session:l,isActive:a.id===A,onClick:()=>i(a.id)})},a.id)})})}),kI={js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"plaintext",svelte:"svelte"};function MI(e){const A=e.split(".").pop()?.toLowerCase()??"";return A?kI[A]??"plaintext":"plaintext"}function yI(e){const A=e.split("/");return A[A.length-1]}function GI({diff:e}){const A=document?.documentElement.classList.contains("dark")?ae:re,g=e.language&&e.language.trim().length>0?e.language:MI(e.file),Q=yI(e.file);if(e.isNewFile&&e.content)return t.jsxs("div",{className:"flex flex-col h-full bg-background",children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between min-h-10",children:[t.jsx("span",{className:"font-mono text-sm text-foreground truncate",title:e.file,children:Q}),t.jsxs("div",{className:"flex items-center gap-3 text-xs flex-shrink-0",children:[t.jsxs("span",{className:"text-green-600 dark:text-green-500",children:["+",e.insertions]}),t.jsx("span",{className:"text-muted-foreground",children:g})]})]}),t.jsx("div",{className:"px-4 py-3 bg-green-500/10 border-b border-green-500/20",children:t.jsxs("p",{className:"text-sm text-green-600 dark:text-green-400 font-medium",children:["New file: ",e.insertions," lines"]})}),t.jsx("div",{className:"flex-1 overflow-auto",children:t.jsx(jA,{language:g,style:A,showLineNumbers:!0,customStyle:{margin:0,padding:"1rem",background:"transparent"},lineNumberStyle:{minWidth:"3em",paddingRight:"1em",color:"var(--color-muted-foreground)",userSelect:"none"},children:e.content})})]});if(e.isBinary)return t.jsxs("div",{className:"flex flex-col h-full bg-background",children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between min-h-10",children:[t.jsx("span",{className:"font-mono text-sm text-foreground truncate",title:e.file,children:Q}),t.jsx("div",{className:"flex items-center gap-3 text-xs flex-shrink-0",children:t.jsx("span",{className:"text-muted-foreground",children:"Binary file"})})]}),t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx("div",{className:"p-4 text-center",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"Binary file - cannot display diff"})})})]});const B=e.diff.split(`
105
103
  `),o=[];let s=0,E=0;for(const C of B)if(C.startsWith("@@")){const a=C.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);a&&(s=parseInt(a[1],10),E=parseInt(a[2],10)),o.push({oldLineNumber:null,newLineNumber:null,content:C,codeContent:C,type:"hunk"})}else C.startsWith("diff")||C.startsWith("index")||C.startsWith("---")||C.startsWith("+++")?o.push({oldLineNumber:null,newLineNumber:null,content:C,codeContent:C,type:"meta"}):C.startsWith("+")?(o.push({oldLineNumber:null,newLineNumber:E,content:C,codeContent:C.slice(1),type:"add"}),E++):C.startsWith("-")?(o.push({oldLineNumber:s,newLineNumber:null,content:C,codeContent:C.slice(1),type:"delete"}),s++):(o.push({oldLineNumber:s,newLineNumber:E,content:C,codeContent:C,type:"context"}),s++,E++);const i=(C,a)=>{let I="flex hover:bg-muted/20",l="flex-shrink-0 w-20 px-2 py-0.5 text-xs font-mono select-none border-r border-border",r="flex-1 px-4 py-0.5 font-mono text-xs overflow-x-auto";C.type==="hunk"?(I+=" bg-blue-500/10",l+=" text-blue-600 dark:text-blue-400",r+=" text-blue-600 dark:text-blue-400 font-semibold"):C.type==="add"?(I+=" bg-green-500/10",l+=" text-green-700 dark:text-green-400",r+=" text-green-700 dark:text-green-400"):C.type==="delete"?(I+=" bg-red-500/10",l+=" text-red-600 dark:text-red-400",r+=" text-red-600 dark:text-red-400"):C.type==="meta"?(r+=" text-muted-foreground",l+=" text-muted-foreground"):(r+=" text-foreground/80",l+=" text-muted-foreground");const n=C.oldLineNumber!==null?C.oldLineNumber.toString():"",d=C.newLineNumber!==null?C.newLineNumber.toString():"";let c=C.content||" ";return C.type!=="meta"&&C.type!=="hunk"&&g!=="plaintext"&&C.codeContent.trim()&&(c=t.jsx(jA,{language:g,style:A,customStyle:{margin:0,padding:0,background:"transparent",display:"inline",fontSize:"inherit",lineHeight:"inherit"},codeTagProps:{style:{fontFamily:"inherit",background:"transparent"}},PreTag:"span",children:C.codeContent}),C.type==="add"?c=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:"+"}),c]}):C.type==="delete"&&(c=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:"-"}),c]}))),t.jsxs("div",{className:I,children:[t.jsx("div",{className:l,children:t.jsxs("div",{className:"flex justify-between gap-2",children:[t.jsx("span",{className:"text-right w-8",children:n}),t.jsx("span",{className:"text-right w-8",children:d})]})}),t.jsx("div",{className:r,children:c})]},a)};return t.jsxs("div",{className:"flex flex-col h-full bg-background",children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between min-h-10",children:[t.jsx("span",{className:"font-mono text-sm text-foreground truncate",title:e.file,children:Q}),t.jsxs("div",{className:"flex items-center gap-3 text-xs flex-shrink-0",children:[e.insertions>0&&t.jsxs("span",{className:"text-green-600 dark:text-green-500",children:["+",e.insertions]}),e.deletions>0&&t.jsxs("span",{className:"text-red-600 dark:text-red-500",children:["-",e.deletions]}),t.jsx("span",{className:"text-muted-foreground",children:g})]})]}),t.jsx("div",{className:"flex-1 overflow-auto",children:e.diff.trim()===""?t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"No changes to display"}):t.jsx("div",{className:"min-w-max",children:o.map(i)})})]})}function FI(e,A=2){const g=e.split("/");return g.length<=A+1?e:`../${g.slice(-A).join("/")}`}function at({file:e,staged:A,showModifiedIndicator:g=!1}){const{openDiff:Q}=CA(),B=jt(),o=Tg(),s=$B(),E=Ao(),i=Rg(h=>h.openConfirmation),[C,a]=u.useState(A),I=async h=>{h.stopPropagation();const m=h.target.checked;a(m);try{m?await B.mutateAsync([e.path]):await o.mutateAsync([e.path])}catch(y){a(!m),console.error("Failed to stage/unstage file:",y)}},l=async h=>{h.stopPropagation(),i({title:"Restore File",message:`Restore ${e.path} to HEAD state? This will discard all changes.`,confirmLabel:"Restore",variant:"destructive",onConfirm:async()=>{try{await s.mutateAsync([e.path])}catch(m){throw console.error("Failed to restore file:",m),m}}})},r=async h=>{h.stopPropagation(),i({title:"Delete File",message:`Delete ${e.path}? This will permanently remove the untracked file.`,confirmLabel:"Delete",variant:"destructive",onConfirm:async()=>{try{await E.mutateAsync([e.path])}catch(m){throw console.error("Failed to delete file:",m),m}}})},n=()=>{Q(e.path,A)},c=(()=>{switch(e.status){case"added":case"untracked":return{icon:oB,color:"text-green-500",label:"A",labelColor:"text-green-500"};case"deleted":return{icon:rs,color:"text-red-500",label:"D",labelColor:"text-red-500"};case"modified":return{icon:le,color:"text-blue-500",label:"M",labelColor:"text-blue-500"};case"renamed":return{icon:le,color:"text-purple-500",label:"R",labelColor:"text-purple-500"};case"conflicted":return{icon:BB,color:"text-red-500",label:"C",labelColor:"text-red-500"};default:return{icon:le,color:"text-muted-foreground",label:"?",labelColor:"text-muted-foreground"}}})(),D=c.icon,N=FI(e.path,2);return t.jsxs("button",{type:"button",className:"flex items-center gap-2 px-3 py-2 hover:bg-muted/50 cursor-pointer group transition-colors w-full text-left",onClick:n,children:[t.jsx("input",{type:"checkbox",checked:C,onChange:I,onClick:h=>h.stopPropagation(),className:"w-4 h-4 rounded border-border","aria-label":`${C?"Unstage":"Stage"} ${e.path}`}),t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx(D,{className:`w-4 h-4 flex-shrink-0 ${c.color}`}),t.jsx("div",{className:"flex-1 min-w-0",children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm text-foreground font-mono truncate",title:`${e.path}
106
104
  ${e.absPath}`,children:N}),t.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[t.jsx("span",{className:`text-xs font-semibold ${c.labelColor}`,children:c.label}),g&&t.jsx("div",{title:"Also modified in working directory",children:t.jsx(Be,{className:"w-3.5 h-3.5 text-orange-500"})})]})]})})]}),e.insertions!==void 0||e.deletions!==void 0?t.jsxs("div",{className:"flex items-center gap-2 text-xs flex-shrink-0",children:[e.insertions!==void 0&&e.insertions>0&&t.jsxs("span",{className:"text-green-500",children:["+",e.insertions]}),e.deletions!==void 0&&e.deletions>0&&t.jsxs("span",{className:"text-red-500",children:["-",e.deletions]})]}):null,!A&&e.status==="untracked"&&t.jsx("button",{type:"button",onClick:r,className:"p-1.5 hover:bg-destructive/10 rounded opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0",title:"Delete untracked file","aria-label":`Delete ${e.path}`,children:t.jsx(kg,{className:"w-3.5 h-3.5 text-destructive"})}),!A&&e.status!=="untracked"&&e.status!=="added"&&t.jsx("button",{type:"button",onClick:l,className:"p-1.5 hover:bg-destructive/10 rounded opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0",title:"Restore file to HEAD (Shift+R)","aria-label":`Restore ${e.path}`,children:t.jsx(eB,{className:"w-3.5 h-3.5 text-destructive"})}),A&&!g&&t.jsx(XA,{className:"w-4 h-4 text-green-500 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"})]})}function bI({status:e}){const{openCommitModal:A,openDiff:g}=CA(),Q=jt();Tg();const{currentFocus:B,gitFileIndex:o}=Pg(),s=u.useRef(new Map),E=(e.conflicted?.length??0)>0,i=e.staged.length>0,C=e.unstaged.length>0||e.untracked.length>0,a=[...e.unstaged,...e.untracked],I=a.length>0;u.useMemo(()=>[...e.conflicted??[],...e.staged,...e.unstaged,...e.untracked],[e]);const l=new Set(e.unstaged.map(d=>d.path)),r=()=>{const d=a.map(c=>c.path);d.length>0&&Q.mutate(d)},n=e.conflicted?.length??0;return u.useEffect(()=>{if(B==="git"&&o>=0){s.current.get(o)?.scrollIntoView({block:"nearest",behavior:"smooth"});const D=[...e.conflicted??[],...e.staged,...e.unstaged,...e.untracked][o];if(D){const N=e.staged.includes(D);g(D.path,N)}}},[B,o,e.conflicted,e.staged,e.unstaged,e.untracked,g]),t.jsxs("div",{className:"flex flex-col",children:[E&&t.jsxs("div",{className:"border-b border-border",children:[t.jsx("div",{className:"px-4 py-2 bg-red-500/10 flex items-center justify-between",children:t.jsxs("span",{className:"text-xs font-semibold text-red-500 uppercase flex items-center gap-1.5",children:[t.jsx(BB,{className:"w-3.5 h-3.5"}),"Conflicts (",n,")"]})}),t.jsx("div",{className:"divide-y divide-border",children:e.conflicted?.map((d,c)=>{const D=c,N=B==="git"&&o===D;return t.jsx("div",{ref:h=>{h?s.current.set(D,h):s.current.delete(D)},className:N?"ring-1 ring-inset ring-primary/40":"",children:t.jsx(at,{file:d,staged:!1})},d.path)})})]}),i&&t.jsxs("div",{className:"border-b border-border",children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between",children:[t.jsxs("span",{className:"text-xs font-semibold text-foreground uppercase",children:["Staged Changes (",e.staged.length,")"]}),t.jsxs("div",{className:"flex items-center gap-1",children:[e.staged.length>0&&!E&&t.jsxs(QA,{variant:"primary",size:"sm",onClick:A,className:"h-6 text-xs",children:[t.jsx(mt,{className:"w-3 h-3 mr-1"}),"Commit"]}),e.staged.length>0&&E&&t.jsx("span",{className:"text-xs text-muted-foreground",children:"Resolve conflicts first"})]})]}),t.jsx("div",{className:"divide-y divide-border",children:e.staged.map((d,c)=>{const D=n+c,N=B==="git"&&o===D;return t.jsx("div",{ref:h=>{h?s.current.set(D,h):s.current.delete(D)},className:N?"ring-1 ring-inset ring-primary/40":"",children:t.jsx(at,{file:d,staged:!0,showModifiedIndicator:l.has(d.path)})},d.path)})})]}),C&&t.jsxs("div",{children:[t.jsxs("div",{className:"px-4 py-2 bg-muted/50 flex items-center justify-between",children:[t.jsxs("span",{className:"text-xs font-semibold text-foreground uppercase",children:["Changes (",e.unstaged.length+e.untracked.length,")"]}),I&&t.jsxs(QA,{variant:"ghost",size:"sm",onClick:r,title:"Stage all changes",className:"h-6 text-xs",children:[t.jsx(Is,{className:"w-3 h-3 mr-1"}),"Stage All"]})]}),t.jsxs("div",{className:"divide-y divide-border",children:[e.unstaged.map((d,c)=>{const D=n+e.staged.length+c,N=B==="git"&&o===D;return t.jsx("div",{ref:h=>{h?s.current.set(D,h):s.current.delete(D)},className:N?"ring-1 ring-inset ring-primary/40":"",children:t.jsx(at,{file:d,staged:!1})},d.path)}),e.untracked.map((d,c)=>{const D=n+e.staged.length+e.unstaged.length+c,N=B==="git"&&o===D;return t.jsx("div",{ref:h=>{h?s.current.set(D,h):s.current.delete(D)},className:N?"ring-1 ring-inset ring-primary/40":"",children:t.jsx(at,{file:d,staged:!1})},d.path)})]})]}),!E&&!i&&!C&&t.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No changes"})]})}const UI=u.memo(function(){const A=CA(c=>c.isExpanded),g=CA(c=>c.collapseSidebar),{data:Q,isLoading:B,error:o,refetch:s}=vt(),E=nA(),i=Ar(),[C,a]=u.useState(null);u.useEffect(()=>{A&&E.invalidateQueries({queryKey:["git","status"]})},[A,E]);const I=()=>{s()},l=async()=>{a(null);try{await i.mutateAsync()}catch(c){a(c instanceof Error?c.message:"Failed to push")}};if(!A)return null;const n=[...Q?.conflicted||[],...Q?.staged||[],...Q?.unstaged||[],...Q?.untracked||[]].length,d=Q&&Q.ahead>0;return t.jsxs("div",{className:"w-80 border-l border-border bg-background flex flex-col h-full",children:[t.jsxs("div",{className:"h-14 border-b border-border px-4 flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx(HA,{className:"w-4 h-4 text-muted-foreground"}),t.jsxs("span",{className:"font-medium text-foreground",children:["Git Changes",n>0&&t.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",n,")"]})]})]}),t.jsx(QA,{variant:"ghost",size:"icon",onClick:g,title:"Close sidebar",children:t.jsx(fA,{className:"w-4 h-4"})})]}),t.jsx("div",{className:"flex-1 overflow-y-auto",children:B?t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading git status..."}):o?t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("span",{className:"text-orange-500",children:o instanceof Error?o.message:"Failed to load git status"}),t.jsx(QA,{variant:"secondary",size:"sm",onClick:I,children:"Retry"})]})}):!Q||n===0?t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"No changes detected"}):t.jsx(bI,{status:Q})}),C&&t.jsx("div",{className:"px-4 py-2 text-xs text-orange-500 border-t border-border bg-orange-50 dark:bg-orange-950/20",children:C}),t.jsxs("div",{className:"h-12 px-4 border-t border-border text-xs text-muted-foreground flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[t.jsx(HA,{className:"w-3 h-3 flex-shrink-0"}),Q?.branch&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"truncate",children:Q.branch}),Q.ahead>0&&t.jsxs("span",{className:"text-green-500 flex-shrink-0",children:["↑",Q.ahead]}),Q.behind>0&&t.jsxs("span",{className:"text-orange-500 flex-shrink-0",children:["↓",Q.behind]})]})]}),t.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[d&&t.jsx(QA,{variant:"ghost",size:"icon",onClick:l,title:"Push commits to remote",className:"h-6 w-6 transition-transform duration-200 hover:scale-110",disabled:i.isPending,children:t.jsx(ns,{className:`w-3 h-3 ${i.isPending?"animate-pulse":""}`})}),t.jsx(QA,{variant:"ghost",size:"icon",onClick:I,title:"Refresh git status",className:"h-6 w-6 transition-transform duration-200 hover:scale-110",disabled:B,children:t.jsx(TA,{className:`w-3 h-3 ${B?"animate-spin":""}`})})]})]})]})}),JI=u.memo(function(){const A=CA(o=>o.isExpanded),g=CA(o=>o.toggleSidebar),{data:Q}=vt(),B=(Q?.staged?.length??0)+(Q?.unstaged?.length??0)+(Q?.untracked?.length??0);return t.jsxs("button",{type:"button",onClick:g,className:`relative h-14 w-full transition-colors touch-manipulation flex items-center justify-center ${A?"bg-muted border-r-2 border-primary":"hover:bg-muted/50"}`,title:"Git",children:[t.jsx(HA,{className:"w-5 h-5 text-muted-foreground mx-auto"}),B>0&&t.jsx("span",{className:"absolute top-1 right-1 w-5 h-5 bg-primary text-primary-foreground text-xs rounded-full flex items-center justify-center font-semibold",children:B>9?"9+":B})]})});function KI(e,A){let g;try{g=e()}catch{return}return{getItem:B=>{var o;const s=i=>i===null?null:JSON.parse(i,void 0),E=(o=g.getItem(B))!=null?o:null;return E instanceof Promise?E.then(s):s(E)},setItem:(B,o)=>g.setItem(B,JSON.stringify(o,void 0)),removeItem:B=>g.removeItem(B)}}const Dg=e=>A=>{try{const g=e(A);return g instanceof Promise?g:{then(Q){return Dg(Q)(g)},catch(Q){return this}}}catch(g){return{then(Q){return this},catch(Q){return Dg(Q)(g)}}}},SI=(e,A)=>(g,Q,B)=>{let o={storage:KI(()=>window.localStorage),partialize:c=>c,version:0,merge:(c,D)=>({...D,...c}),...A},s=!1,E=0;const i=new Set,C=new Set;let a=o.storage;if(!a)return e((...c)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),g(...c)},Q,B);const I=()=>{const c=o.partialize({...Q()});return a.setItem(o.name,{state:c,version:o.version})},l=B.setState;B.setState=(c,D)=>(l(c,D),I());const r=e((...c)=>(g(...c),I()),Q,B);B.getInitialState=()=>r;let n;const d=()=>{var c,D;if(!a)return;const N=++E;s=!1,i.forEach(m=>{var y;return m((y=Q())!=null?y:r)});const h=((D=o.onRehydrateStorage)==null?void 0:D.call(o,(c=Q())!=null?c:r))||void 0;return Dg(a.getItem.bind(a))(o.name).then(m=>{if(m)if(typeof m.version=="number"&&m.version!==o.version){if(o.migrate){const y=o.migrate(m.state,m.version);return y instanceof Promise?y.then(x=>[!0,x]):[!0,y]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,m.state];return[!1,void 0]}).then(m=>{var y;if(N!==E)return;const[x,f]=m;if(n=o.merge(f,(y=Q())!=null?y:r),g(n,!0),x)return I()}).then(()=>{N===E&&(h?.(n,void 0),n=Q(),s=!0,C.forEach(m=>m(n)))}).catch(m=>{N===E&&h?.(void 0,m)})};return B.persist={setOptions:c=>{o={...o,...c},c.storage&&(a=c.storage)},clearStorage:()=>{a?.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>d(),hasHydrated:()=>s,onHydrate:c=>(i.add(c),()=>{i.delete(c)}),onFinishHydration:c=>(C.add(c),()=>{C.delete(c)})},o.skipHydration||d(),n||r},RI=SI,Me=UA()(RI(e=>({isCollapsed:!1,toggleCollapse:()=>e(A=>({isCollapsed:!A.isCollapsed})),setCollapsed:A=>e({isCollapsed:A})}),{name:"sidebar-storage"})),LI=u.memo(function(){const A=CA(a=>a.isDiffOpen),g=CA(a=>a.selectedFile),Q=CA(a=>a.selectedFileStaged),B=CA(a=>a.closeDiff),o=Me(a=>a.setCollapsed),s=u.useRef(null),E=u.useRef(!1),{data:i,isLoading:C}=Xa(g,Q);return u.useEffect(()=>{if(A&&!E.current){const{isCollapsed:a}=Me.getState();s.current=a,o(!0)}else!A&&E.current&&s.current!==null&&(o(s.current),s.current=null);E.current=A},[A,o]),u.useEffect(()=>{const a=I=>{const l=I.target,r=l.tagName==="INPUT"||l.tagName==="TEXTAREA"||l.isContentEditable;(I.key==="Escape"||I.key==="q"&&!r)&&A&&B()};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[A,B]),!A||!g?null:t.jsxs("div",{className:"absolute inset-0 bg-background z-50 flex flex-col animate-in slide-in-from-left duration-300",children:[t.jsxs("div",{className:"h-14 border-b border-border px-4 flex items-center gap-3",children:[t.jsx(QA,{variant:"ghost",size:"icon",onClick:B,title:"Close diff viewer (ESC)",children:t.jsx(MA,{className:"w-4 h-4"})}),t.jsxs("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[t.jsx("span",{className:"text-sm font-medium text-foreground font-mono truncate",title:`${g}
107
105
  ${i?.absPath||""}`,children:g}),Q&&t.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-primary/10 text-primary flex-shrink-0",children:"Staged"})]})]}),t.jsx("div",{className:"flex-1 overflow-auto",children:C?t.jsx("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:"Loading diff..."}):i?t.jsx(GI,{diff:i}):t.jsx("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:"No diff available"})})]})});function qI(){const{isCommitModalOpen:e,closeCommitModal:A}=CA(),g=CA(I=>I.commitSessionId),Q=$a(),B=_a(g),[o,s]=u.useState(""),E=u.useId(),i=u.useCallback(async()=>{if(o.trim())try{await Q.mutateAsync(o),s(""),A()}catch(I){console.error("Failed to commit:",I)}},[o,Q,A]),C=()=>{s(""),A()},a=u.useCallback(async()=>{try{const I=await B.mutateAsync();s(I.message)}catch(I){console.error("Failed to generate commit message:",I)}},[B]);return u.useEffect(()=>{if(!e)return;const I=l=>{(l.metaKey||l.ctrlKey)&&l.key==="Enter"&&(l.preventDefault(),l.stopPropagation(),o.trim()&&!Q.isPending&&i()),(l.metaKey||l.ctrlKey)&&l.key==="g"&&(l.preventDefault(),l.stopPropagation(),a())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,o,Q.isPending,i,a]),t.jsx(qe,{isOpen:e,onClose:C,title:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(mt,{className:"w-5 h-5"}),t.jsx("span",{children:"Commit Changes"})]}),maxWidth:"2xl",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{htmlFor:E,className:"text-sm font-medium text-foreground",children:"Commit Message"}),t.jsx(Ot,{id:E,value:o,onChange:I=>s(I.target.value),placeholder:"Enter commit message...",rows:6,className:"w-full resize-none",autoFocus:!0,disabled:B.isPending})]}),t.jsx(QA,{variant:"secondary",onClick:a,className:"w-full",disabled:B.isPending,children:B.isPending?t.jsxs(t.Fragment,{children:[t.jsx(uA,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Ke,{className:"w-4 h-4 mr-2"}),"Generate commit message"," ",t.jsx("span",{className:"text-muted-foreground ml-1",children:"(⌘G)"})]})}),B.isError&&t.jsx("div",{className:"text-sm text-red-600 dark:text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:B.error?.message||"Failed to generate commit message"}),t.jsxs("div",{className:"flex items-center justify-end gap-2 pt-4 border-t border-border",children:[t.jsxs(QA,{variant:"ghost",onClick:C,children:["Cancel ",t.jsx("span",{className:"text-muted-foreground ml-1",children:"(Esc)"})]}),t.jsx(QA,{variant:"primary",onClick:i,disabled:!o.trim()||Q.isPending,children:Q.isPending?t.jsx("span",{children:"Committing..."}):t.jsxs(t.Fragment,{children:[t.jsx(mt,{className:"w-4 h-4 mr-2"}),"Commit ",t.jsx("span",{className:"text-muted-foreground ml-1",children:"(⌘↵)"})]})})]}),Q.isError&&t.jsx("div",{className:"text-sm text-red-600 dark:text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:Q.error?.message||"Failed to commit changes"})]})})}function uo(e){const A=wA(g=>g.isExpanded);return PA({queryKey:["session",e,"files"],queryFn:()=>e?T.getSessionFiles(e):null,enabled:!!e,refetchInterval:A?5e3:!1,retry:1,staleTime:3e3})}function OI(e){switch(e){case"write":return t.jsx(oB,{className:"w-3 h-3 text-green-500"});case"patch":return t.jsx(Ne,{className:"w-3 h-3 text-blue-500"});case"edit":return t.jsx(WQ,{className:"w-3 h-3 text-yellow-500"});default:return t.jsx(Ne,{className:"w-3 h-3 text-muted-foreground"})}}function YI(e){return e.split("/").pop()||e}function TI(e){if(e.artifact?.summary)return{additions:e.artifact.summary.additions,deletions:e.artifact.summary.deletions};const A=e.artifact?.patch||e.patch;if(A){let g=0,Q=0;const B=A.split(`