@ottocode/web-ui 0.1.174 → 0.1.176

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(`
@@ -77,7 +77,7 @@ ${d.slice(c)}`;return Q(D),setTimeout(()=>{r.setSelectionRange(c,c)},0),!0}if(s=
77
77
  `,c);if(h!==-1){const m=h+1;let y=d.indexOf(`
78
78
  `,m);y===-1&&(y=d.length);const x=y-m,f=m+Math.min(N,x);r.setSelectionRange(f,f)}return!0}if(n==="k"){l.preventDefault();const d=r.value,c=r.selectionStart,D=d.lastIndexOf(`
79
79
  `,c-1)+1;if(D>0){const N=c-D,h=D-1,m=d.lastIndexOf(`
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-3 items-center mt-1 px-3",children:[t.jsx("div",{className:"justify-self-start",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"}),"Extended 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!=="api"&&t.jsxs("span",{className:"opacity-50",children:["(",D==="oauth"?"pro":"wallet",")"]})]}),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",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"}),"Supports 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(`
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
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}
83
83
 
@@ -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(`