@ottocode/web-ui 0.1.176 → 0.1.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,7 +27,7 @@ For tests, pass a Ghostty instance directly:
27
27
  transition-all duration-150 ease-out cursor-pointer
28
28
  hover:bg-accent/50
29
29
  ${A?"opacity-100 translate-y-0":"opacity-0 translate-y-2"}
30
- `,onClick:B,role:"alert",children:[pi[e.type],t.jsx("span",{className:"text-sm text-foreground",children:e.message}),e.action&&t.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Bt(e.action.href)},className:"ml-auto flex items-center gap-1 text-xs text-primary hover:underline",children:[e.action.label,t.jsx(SA,{className:"h-3 w-3"})]})]})}function xi(){const e=_A(A=>A.toasts);return e.length===0?null:t.jsx("div",{className:"fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 max-w-sm",children:e.map(A=>t.jsx(mi,{toast:A},A.id))})}const Lg=UA(e=>({pendingApprovals:[],addPendingApproval:A=>e(g=>({pendingApprovals:[...g.pendingApprovals,A]})),removePendingApproval:A=>e(g=>({pendingApprovals:g.pendingApprovals.filter(Q=>Q.callId!==A)})),updatePendingApproval:(A,g)=>e(Q=>({pendingApprovals:Q.pendingApprovals.map(B=>B.callId===A?{...B,args:g}:B)})),clearPendingApprovals:()=>e({pendingApprovals:[]}),setPendingApprovals:A=>e({pendingApprovals:A})}));function Ce(e){return Array.isArray?Array.isArray(e):YB(e)==="[object Array]"}function fi(e){if(typeof e=="string")return e;let A=e+"";return A=="0"&&1/e==-1/0?"-0":A}function Ni(e){return e==null?"":fi(e)}function ge(e){return typeof e=="string"}function qB(e){return typeof e=="number"}function ki(e){return e===!0||e===!1||Mi(e)&&YB(e)=="[object Boolean]"}function OB(e){return typeof e=="object"}function Mi(e){return OB(e)&&e!==null}function YA(e){return e!=null}function $t(e){return!e.trim().length}function YB(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const yi="Incorrect 'index' type",Gi=e=>`Invalid value for key ${e}`,Fi=e=>`Pattern length exceeds max of ${e}.`,bi=e=>`Missing ${e} property in key`,Ui=e=>`Property 'weight' in key '${e}' must be a positive integer`,NQ=Object.prototype.hasOwnProperty;class Ji{constructor(A){this._keys=[],this._keyMap={};let g=0;A.forEach(Q=>{let B=TB(Q);this._keys.push(B),this._keyMap[B.id]=B,g+=B.weight}),this._keys.forEach(Q=>{Q.weight/=g})}get(A){return this._keyMap[A]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function TB(e){let A=null,g=null,Q=null,B=1,o=null;if(ge(e)||Ce(e))Q=e,A=kQ(e),g=ag(e);else{if(!NQ.call(e,"name"))throw new Error(bi("name"));const s=e.name;if(Q=s,NQ.call(e,"weight")&&(B=e.weight,B<=0))throw new Error(Ui(s));A=kQ(s),g=ag(s),o=e.getFn}return{path:A,id:g,weight:B,src:Q,getFn:o}}function kQ(e){return Ce(e)?e:e.split(".")}function ag(e){return Ce(e)?e.join("."):e}function Ki(e,A){let g=[],Q=!1;const B=(o,s,E)=>{if(YA(o))if(!s[E])g.push(o);else{let i=s[E];const C=o[i];if(!YA(C))return;if(E===s.length-1&&(ge(C)||qB(C)||ki(C)))g.push(Ni(C));else if(Ce(C)){Q=!0;for(let a=0,I=C.length;a<I;a+=1)B(C[a],s,E+1)}else s.length&&B(C,s,E+1)}};return B(e,ge(A)?A.split("."):A,0),Q?g:g[0]}const Si={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Ri={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,A)=>e.score===A.score?e.idx<A.idx?-1:1:e.score<A.score?-1:1},Li={location:0,threshold:.6,distance:100},qi={useExtendedSearch:!1,getFn:Ki,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var z={...Ri,...Si,...Li,...qi};const Oi=/[^ ]+/g;function Yi(e=1,A=3){const g=new Map,Q=Math.pow(10,A);return{get(B){const o=B.match(Oi).length;if(g.has(o))return g.get(o);const s=1/Math.pow(o,.5*e),E=parseFloat(Math.round(s*Q)/Q);return g.set(o,E),E},clear(){g.clear()}}}class qg{constructor({getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){this.norm=Yi(g,3),this.getFn=A,this.isCreated=!1,this.setIndexRecords()}setSources(A=[]){this.docs=A}setIndexRecords(A=[]){this.records=A}setKeys(A=[]){this.keys=A,this._keysMap={},A.forEach((g,Q)=>{this._keysMap[g.id]=Q})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,ge(this.docs[0])?this.docs.forEach((A,g)=>{this._addString(A,g)}):this.docs.forEach((A,g)=>{this._addObject(A,g)}),this.norm.clear())}add(A){const g=this.size();ge(A)?this._addString(A,g):this._addObject(A,g)}removeAt(A){this.records.splice(A,1);for(let g=A,Q=this.size();g<Q;g+=1)this.records[g].i-=1}getValueForItemAtKeyId(A,g){return A[this._keysMap[g]]}size(){return this.records.length}_addString(A,g){if(!YA(A)||$t(A))return;let Q={v:A,i:g,n:this.norm.get(A)};this.records.push(Q)}_addObject(A,g){let Q={i:g,$:{}};this.keys.forEach((B,o)=>{let s=B.getFn?B.getFn(A):this.getFn(A,B.path);if(YA(s)){if(Ce(s)){let E=[];const i=[{nestedArrIndex:-1,value:s}];for(;i.length;){const{nestedArrIndex:C,value:a}=i.pop();if(YA(a))if(ge(a)&&!$t(a)){let I={v:a,i:C,n:this.norm.get(a)};E.push(I)}else Ce(a)&&a.forEach((I,l)=>{i.push({nestedArrIndex:l,value:I})})}Q.$[o]=E}else if(ge(s)&&!$t(s)){let E={v:s,n:this.norm.get(s)};Q.$[o]=E}}}),this.records.push(Q)}toJSON(){return{keys:this.keys,records:this.records}}}function vB(e,A,{getFn:g=z.getFn,fieldNormWeight:Q=z.fieldNormWeight}={}){const B=new qg({getFn:g,fieldNormWeight:Q});return B.setKeys(e.map(TB)),B.setSources(A),B.create(),B}function Ti(e,{getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){const{keys:Q,records:B}=e,o=new qg({getFn:A,fieldNormWeight:g});return o.setKeys(Q),o.setIndexRecords(B),o}function Ct(e,{errors:A=0,currentLocation:g=0,expectedLocation:Q=0,distance:B=z.distance,ignoreLocation:o=z.ignoreLocation}={}){const s=A/e.length;if(o)return s;const E=Math.abs(Q-g);return B?s+E/B:E?1:s}function vi(e=[],A=z.minMatchCharLength){let g=[],Q=-1,B=-1,o=0;for(let s=e.length;o<s;o+=1){let E=e[o];E&&Q===-1?Q=o:!E&&Q!==-1&&(B=o-1,B-Q+1>=A&&g.push([Q,B]),Q=-1)}return e[o-1]&&o-Q>=A&&g.push([Q,o-1]),g}const pe=32;function ji(e,A,g,{location:Q=z.location,distance:B=z.distance,threshold:o=z.threshold,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,includeMatches:i=z.includeMatches,ignoreLocation:C=z.ignoreLocation}={}){if(A.length>pe)throw new Error(Fi(pe));const a=A.length,I=e.length,l=Math.max(0,Math.min(Q,I));let r=o,n=l;const d=E>1||i,c=d?Array(I):[];let D;for(;(D=e.indexOf(A,n))>-1;){let f=Ct(A,{currentLocation:D,expectedLocation:l,distance:B,ignoreLocation:C});if(r=Math.min(f,r),n=D+a,d){let M=0;for(;M<a;)c[D+M]=1,M+=1}}n=-1;let N=[],h=1,m=a+I;const y=1<<a-1;for(let f=0;f<a;f+=1){let M=0,w=m;for(;M<w;)Ct(A,{errors:f,currentLocation:l+w,expectedLocation:l,distance:B,ignoreLocation:C})<=r?M=w:m=w,w=Math.floor((m-M)/2+M);m=w;let G=Math.max(1,l-w+1),p=s?I:Math.min(l+w,I)+a,U=Array(p+2);U[p+1]=(1<<f)-1;for(let J=p;J>=G;J-=1){let S=J-1,Y=g[e.charAt(S)];if(d&&(c[S]=+!!Y),U[J]=(U[J+1]<<1|1)&Y,f&&(U[J]|=(N[J+1]|N[J])<<1|1|N[J+1]),U[J]&y&&(h=Ct(A,{errors:f,currentLocation:S,expectedLocation:l,distance:B,ignoreLocation:C}),h<=r)){if(r=h,n=S,n<=l)break;G=Math.max(1,2*l-n)}}if(Ct(A,{errors:f+1,currentLocation:l,expectedLocation:l,distance:B,ignoreLocation:C})>r)break;N=U}const x={isMatch:n>=0,score:Math.max(.001,h)};if(d){const f=vi(c,E);f.length?i&&(x.indices=f):x.isMatch=!1}return x}function Hi(e){let A={};for(let g=0,Q=e.length;g<Q;g+=1){const B=e.charAt(g);A[B]=(A[B]||0)|1<<Q-g-1}return A}const Nt=String.prototype.normalize?(e=>e.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"")):(e=>e);class jB{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){if(this.options={location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a},A=i?A:A.toLowerCase(),A=C?Nt(A):A,this.pattern=A,this.chunks=[],!this.pattern.length)return;const I=(r,n)=>{this.chunks.push({pattern:r,alphabet:Hi(r),startIndex:n})},l=this.pattern.length;if(l>pe){let r=0;const n=l%pe,d=l-n;for(;r<d;)I(this.pattern.substr(r,pe),r),r+=pe;if(n){const c=l-pe;I(this.pattern.substr(c),c)}}else I(this.pattern,0)}searchIn(A){const{isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B}=this.options;if(A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern===A){let d={isMatch:!0,score:0};return B&&(d.indices=[[0,A.length-1]]),d}const{location:o,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,ignoreLocation:a}=this.options;let I=[],l=0,r=!1;this.chunks.forEach(({pattern:d,alphabet:c,startIndex:D})=>{const{isMatch:N,score:h,indices:m}=ji(A,d,c,{location:o+D,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,includeMatches:B,ignoreLocation:a});N&&(r=!0),l+=h,N&&m&&(I=[...I,...m])});let n={isMatch:r,score:r?l/this.chunks.length:1};return r&&B&&(n.indices=I),n}}class ce{constructor(A){this.pattern=A}static isMultiMatch(A){return MQ(A,this.multiRegex)}static isSingleMatch(A){return MQ(A,this.singleRegex)}search(){}}function MQ(e,A){const g=e.match(A);return g?g[1]:null}class Pi extends ce{constructor(A){super(A)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(A){const g=A===this.pattern;return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Wi extends ce{constructor(A){super(A)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(A){const Q=A.indexOf(this.pattern)===-1;return{isMatch:Q,score:Q?0:1,indices:[0,A.length-1]}}}class zi extends ce{constructor(A){super(A)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(A){const g=A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Vi extends ce{constructor(A){super(A)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(A){const g=!A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class Zi extends ce{constructor(A){super(A)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(A){const g=A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[A.length-this.pattern.length,A.length-1]}}}class Xi extends ce{constructor(A){super(A)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(A){const g=!A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class HB extends ce{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){super(A),this._bitapSearch=new jB(A,{location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(A){return this._bitapSearch.searchIn(A)}}class PB extends ce{constructor(A){super(A)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(A){let g=0,Q;const B=[],o=this.pattern.length;for(;(Q=A.indexOf(this.pattern,g))>-1;)g=Q+o,B.push([Q,g-1]);const s=!!B.length;return{isMatch:s,score:s?0:1,indices:B}}}const rg=[Pi,PB,zi,Vi,Xi,Zi,Wi,HB],yQ=rg.length,_i=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,$i="|";function Aa(e,A={}){return e.split($i).map(g=>{let Q=g.trim().split(_i).filter(o=>o&&!!o.trim()),B=[];for(let o=0,s=Q.length;o<s;o+=1){const E=Q[o];let i=!1,C=-1;for(;!i&&++C<yQ;){const a=rg[C];let I=a.isMultiMatch(E);I&&(B.push(new a(I,A)),i=!0)}if(!i)for(C=-1;++C<yQ;){const a=rg[C];let I=a.isSingleMatch(E);if(I){B.push(new a(I,A));break}}}return B})}const ea=new Set([HB.type,PB.type]);class ta{constructor(A,{isCaseSensitive:g=z.isCaseSensitive,ignoreDiacritics:Q=z.ignoreDiacritics,includeMatches:B=z.includeMatches,minMatchCharLength:o=z.minMatchCharLength,ignoreLocation:s=z.ignoreLocation,findAllMatches:E=z.findAllMatches,location:i=z.location,threshold:C=z.threshold,distance:a=z.distance}={}){this.query=null,this.options={isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B,minMatchCharLength:o,findAllMatches:E,ignoreLocation:s,location:i,threshold:C,distance:a},A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern=A,this.query=Aa(this.pattern,this.options)}static condition(A,g){return g.useExtendedSearch}searchIn(A){const g=this.query;if(!g)return{isMatch:!1,score:1};const{includeMatches:Q,isCaseSensitive:B,ignoreDiacritics:o}=this.options;A=B?A:A.toLowerCase(),A=o?Nt(A):A;let s=0,E=[],i=0;for(let C=0,a=g.length;C<a;C+=1){const I=g[C];E.length=0,s=0;for(let l=0,r=I.length;l<r;l+=1){const n=I[l],{isMatch:d,indices:c,score:D}=n.search(A);if(d){if(s+=1,i+=D,Q){const N=n.constructor.type;ea.has(N)?E=[...E,...c]:E.push(c)}}else{i=0,s=0,E.length=0;break}}if(s){let l={isMatch:!0,score:i/s};return Q&&(l.indices=E),l}}return{isMatch:!1,score:1}}}const Ig=[];function ga(...e){Ig.push(...e)}function ng(e,A){for(let g=0,Q=Ig.length;g<Q;g+=1){let B=Ig[g];if(B.condition(e,A))return new B(e,A)}return new jB(e,A)}const kt={AND:"$and",OR:"$or"},lg={PATH:"$path",PATTERN:"$val"},cg=e=>!!(e[kt.AND]||e[kt.OR]),Qa=e=>!!e[lg.PATH],Ba=e=>!Ce(e)&&OB(e)&&!cg(e),GQ=e=>({[kt.AND]:Object.keys(e).map(A=>({[A]:e[A]}))});function WB(e,A,{auto:g=!0}={}){const Q=B=>{let o=Object.keys(B);const s=Qa(B);if(!s&&o.length>1&&!cg(B))return Q(GQ(B));if(Ba(B)){const i=s?B[lg.PATH]:o[0],C=s?B[lg.PATTERN]:B[i];if(!ge(C))throw new Error(Gi(i));const a={keyId:ag(i),pattern:C};return g&&(a.searcher=ng(C,A)),a}let E={children:[],operator:o[0]};return o.forEach(i=>{const C=B[i];Ce(C)&&C.forEach(a=>{E.children.push(Q(a))})}),E};return cg(e)||(e=GQ(e)),Q(e)}function oa(e,{ignoreFieldNorm:A=z.ignoreFieldNorm}){e.forEach(g=>{let Q=1;g.matches.forEach(({key:B,norm:o,score:s})=>{const E=B?B.weight:null;Q*=Math.pow(s===0&&E?Number.EPSILON:s,(E||1)*(A?1:o))}),g.score=Q})}function sa(e,A){const g=e.matches;A.matches=[],YA(g)&&g.forEach(Q=>{if(!YA(Q.indices)||!Q.indices.length)return;const{indices:B,value:o}=Q;let s={indices:B,value:o};Q.key&&(s.key=Q.key.src),Q.idx>-1&&(s.refIndex=Q.idx),A.matches.push(s)})}function Ea(e,A){A.score=e.score}function Ca(e,A,{includeMatches:g=z.includeMatches,includeScore:Q=z.includeScore}={}){const B=[];return g&&B.push(sa),Q&&B.push(Ea),e.map(o=>{const{idx:s}=o,E={item:A[s],refIndex:s};return B.length&&B.forEach(i=>{i(o,E)}),E})}class de{constructor(A,g={},Q){this.options={...z,...g},this.options.useExtendedSearch,this._keyStore=new Ji(this.options.keys),this.setCollection(A,Q)}setCollection(A,g){if(this._docs=A,g&&!(g instanceof qg))throw new Error(yi);this._myIndex=g||vB(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(A){YA(A)&&(this._docs.push(A),this._myIndex.add(A))}remove(A=()=>!1){const g=[];for(let Q=0,B=this._docs.length;Q<B;Q+=1){const o=this._docs[Q];A(o,Q)&&(this.removeAt(Q),Q-=1,B-=1,g.push(o))}return g}removeAt(A){this._docs.splice(A,1),this._myIndex.removeAt(A)}getIndex(){return this._myIndex}search(A,{limit:g=-1}={}){const{includeMatches:Q,includeScore:B,shouldSort:o,sortFn:s,ignoreFieldNorm:E}=this.options;let i=ge(A)?ge(this._docs[0])?this._searchStringList(A):this._searchObjectList(A):this._searchLogical(A);return oa(i,{ignoreFieldNorm:E}),o&&i.sort(s),qB(g)&&g>-1&&(i=i.slice(0,g)),Ca(i,this._docs,{includeMatches:Q,includeScore:B})}_searchStringList(A){const g=ng(A,this.options),{records:Q}=this._myIndex,B=[];return Q.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=g.searchIn(o);i&&B.push({item:o,idx:s,matches:[{score:C,value:o,norm:E,indices:a}]})}),B}_searchLogical(A){const g=WB(A,this.options),Q=(E,i,C)=>{if(!E.children){const{keyId:I,searcher:l}=E,r=this._findMatches({key:this._keyStore.get(I),value:this._myIndex.getValueForItemAtKeyId(i,I),searcher:l});return r&&r.length?[{idx:C,item:i,matches:r}]:[]}const a=[];for(let I=0,l=E.children.length;I<l;I+=1){const r=E.children[I],n=Q(r,i,C);if(n.length)a.push(...n);else if(E.operator===kt.AND)return[]}return a},B=this._myIndex.records,o={},s=[];return B.forEach(({$:E,i})=>{if(YA(E)){let C=Q(g,E,i);C.length&&(o[i]||(o[i]={idx:i,item:E,matches:[]},s.push(o[i])),C.forEach(({matches:a})=>{o[i].matches.push(...a)}))}}),s}_searchObjectList(A){const g=ng(A,this.options),{keys:Q,records:B}=this._myIndex,o=[];return B.forEach(({$:s,i:E})=>{if(!YA(s))return;let i=[];Q.forEach((C,a)=>{i.push(...this._findMatches({key:C,value:s[a],searcher:g}))}),i.length&&o.push({idx:E,item:s,matches:i})}),o}_findMatches({key:A,value:g,searcher:Q}){if(!YA(g))return[];let B=[];if(Ce(g))g.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=Q.searchIn(o);i&&B.push({score:C,key:A,value:o,idx:s,norm:E,indices:a})});else{const{v:o,n:s}=g,{isMatch:E,score:i,indices:C}=Q.searchIn(o);E&&B.push({score:i,key:A,value:o,norm:s,indices:C})}return B}}de.version="7.1.0";de.createIndex=vB;de.parseIndex=Ti;de.config=z;de.parseQuery=WB;ga(ta);function ia(e){switch(e.split(".").pop()?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"go":case"rs":case"java":case"c":case"cpp":case"h":case"hpp":return WQ;case"json":case"yaml":case"yml":case"toml":return zo;case"md":case"txt":case"log":return Ft;case"png":case"jpg":case"jpeg":case"gif":case"svg":case"webp":return PQ;case"css":case"scss":case"sass":case"less":return Wo;case"html":case"xml":return Po;default:return le}}function aa(e,A){const g=A.get(e);return g?{added:{icon:Je,label:"Added",className:"text-green-500"},modified:{icon:gg,label:"Modified",className:"text-yellow-500"},untracked:{icon:Je,label:"Untracked",className:"text-blue-500"}}[g]||{icon:gg,label:"Modified",className:"text-yellow-500"}:null}function ra({files:e,changedFiles:A=[],query:g,selectedIndex:Q,onSelect:B,onEnterSelect:o,onClose:s}){const E=u.useMemo(()=>new Map(A?.map(a=>[a.path,a.status])||[]),[A]),i=u.useMemo(()=>new de(e,{threshold:.4,distance:100,ignoreLocation:!0,includeMatches:!0}),[e]),C=u.useMemo(()=>{if(!g)return e.slice(0,20);const a=i.search(g).map(I=>I.item);return a.sort((I,l)=>{const r=E.has(I),n=E.has(l);return r&&!n?-1:!r&&n?1:0}),a.slice(0,20)},[i,g,e,E]);return u.useEffect(()=>{document.getElementById(`file-item-${Q}`)?.scrollIntoView({block:"nearest"})},[Q]),u.useEffect(()=>{o(C[Q])},[C,Q,o]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-file-mention-popup]")||s()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[s]),C.length===0?t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No files found"})}):t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>t.jsx("button",{type:"button",id:`file-item-${I}`,onMouseDown:l=>{l.preventDefault(),B(a)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===Q?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-2 w-full",children:[(()=>{const l=ia(a);return t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-muted-foreground"})})(),t.jsx("span",{className:"font-mono text-sm flex-1 truncate",children:a}),(()=>{const l=aa(a,E);return l&&t.jsx(l.icon,{className:`w-3.5 h-3.5 flex-shrink-0 ${l.className}`,title:l.label})})()]})},a))})}const zB="otto-preferences",ut={vimMode:!1,reasoningEnabled:!0};function Ia(){if(typeof window>"u")return ut;try{const e=window.localStorage.getItem(zB);if(e){const A=JSON.parse(e);return{...ut,...A}}}catch(e){console.warn("Failed to load preferences",e)}return ut}let ht=Ia();const dg=new Set;function na(){return ht}function la(){return ut}function ca(e){return dg.add(e),()=>dg.delete(e)}function da(){for(const e of dg)e()}function ua(e){if(ht={...ht,...e},typeof window<"u")try{window.localStorage.setItem(zB,JSON.stringify(ht))}catch(A){console.warn("Failed to persist preferences",A)}da()}function ot(){const e=u.useSyncExternalStore(ca,na,la),A=u.useCallback(g=>{ua(g)},[]);return u.useMemo(()=>({preferences:e,updatePreferences:A}),[e,A])}function Z(e){if(!e)return"Unknown error";if(typeof e=="string")return e;if(e&&typeof e=="object"){const A=e;if(A.error&&typeof A.error=="object"){const g=A.error;if(typeof g.message=="string")return g.message}if(typeof A.error=="string")return A.error;if(typeof A.message=="string")return A.message;try{return JSON.stringify(e)}catch{return"Error occurred (unable to parse)"}}return"Unknown error"}function ha(){const A=window.OTTO_SERVER_URL||qt;lA.setConfig({baseURL:A})}ha();function Ag(e){return{...e,title:e.title??null,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,lastActiveAt:typeof e.lastActiveAt=="string"?new Date(e.lastActiveAt).getTime():e.lastActiveAt}}function Da(e){return{...e,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,completedAt:e.completedAt?typeof e.completedAt=="string"?new Date(e.completedAt).getTime():e.completedAt:null}}class wa{get baseUrl(){const A=window;return A.OTTO_SERVER_URL?A.OTTO_SERVER_URL:qt}async getSessions(){const A=await uC();if(A.error)throw new Error(Z(A.error));return(A.data||[]).map(Ag)}async createSession(A){const g=await hC({body:A});if(g.error)throw new Error(Z(g.error));if(!g.data)throw new Error("No data returned from create session");return Ag(g.data)}async updateSession(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const o=await Q.json().catch(()=>({error:"Failed to update session"}));throw new Error(Z(o))}const B=await Q.json();return Ag(B)}async deleteSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to delete session"}));throw new Error(Z(Q))}return await g.json()}async abortSession(A){const g=await DC({path:{sessionId:A}});if(g.error)throw new Error(Z(g.error));return g.data}async abortMessage(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/abort`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:g})});if(!B.ok)throw new Error("Failed to abort message");return B.json()}async getQueueState(A){const g=this.baseUrl,Q=await fetch(`${g}/v1/sessions/${A}/queue`);if(!Q.ok)throw new Error("Failed to get queue state");return Q.json()}async removeFromQueue(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/queue/${g}`,{method:"DELETE"});if(!B.ok)throw new Error("Failed to remove from queue");return B.json()}async getMessages(A){const g=await wC({path:{id:A}});if(g.error)throw new Error(Z(g.error));return(g.data||[]).map(Da)}async sendMessage(A,g){const Q=await pC({path:{id:A},body:g});if(Q.error)throw new Error(Z(Q.error));return Q.data}getStreamUrl(A){return`${this.baseUrl}/v1/sessions/${A}/stream`}async getConfig(){const A=await mC();if(A.error)throw new Error(Z(A.error));return A.data}async getModels(A){const g=await xC({path:{provider:A}});if(g.error)throw new Error(Z(g.error));return g.data}async getAllModels(){const A=await fetch(`${this.baseUrl}/v1/config/models`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to fetch models"}));throw new Error(Z(g))}return await A.json()}async updateDefaults(A){const g=await fetch(`${this.baseUrl}/v1/config/defaults`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to update defaults"}));throw new Error(Z(Q))}return await g.json()}async getGitStatus(){const A=await NC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async getGitDiff(A,g=!1){const Q=await kC({query:{file:A,staged:g?"true":"false"}});if(Q.error)throw new Error(Z(Q.error));return Q.data?.data}async generateCommitMessage(A){const g=await bC({body:A?{sessionId:A}:{}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async stageFiles(A){const g=await yC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async unstageFiles(A){const g=await GC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async restoreFiles(A){const g=await JC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async deleteFiles(A){const g=await KC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async commitChanges(A){const g=await FC({body:{message:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async getGitBranch(){const A=await MC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async pushCommits(){const A=await UC({body:{}});if(A.error)throw new Error(Z(A.error));return A.data?.data}async listFiles(){const A=await fC();if(A.error)throw new Error(Z(A.error));return A.data}async getSessionFiles(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/files`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to fetch session files"}));throw new Error(Z(Q))}return await g.json()}async createBranch(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/branch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create branch"}));throw new Error(Z(B))}return await Q.json()}async listBranches(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/branches`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to list branches"}));throw new Error(Z(Q))}return await g.json()}async getParentSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/parent`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to get parent session"}));throw new Error(Z(Q))}return await g.json()}async getSetuBalance(){try{const A=await fetch(`${this.baseUrl}/v1/setu/balance`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():null}catch{return null}}async getSetuWallet(){try{const A=await fetch(`${this.baseUrl}/v1/setu/wallet`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():{configured:!1}}catch{return{configured:!1}}}async getSetuUsdcBalance(A="mainnet"){try{const g=await fetch(`${this.baseUrl}/v1/setu/usdc-balance?network=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async getShareStatus(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{shared:!1}}async shareSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to share session"}));throw new Error(Z(Q))}return await g.json()}async syncSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"PUT",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to sync session"}));throw new Error(Z(Q))}return await g.json()}async approveToolCall(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:g,approved:Q})});if(!B.ok)throw new Error("Failed to send tool approval");return await B.json()}async getPendingApprovals(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval/pending`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{ok:!1,pending:[]}}async getPolarTopupEstimate(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/estimate?amount=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async createPolarCheckout(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/polar`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:A,successUrl:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create checkout"}));throw new Error(Z(B))}return await Q.json()}async selectTopupMethod(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/select`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,method:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to select topup method"}));throw new Error(Z(B))}return await Q.json()}async cancelTopup(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,reason:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to cancel topup"}));throw new Error(Z(B))}return await Q.json()}async getPendingTopup(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/pending?sessionId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{hasPending:!1}}catch{return{hasPending:!1}}}async getPolarTopupStatus(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/status?checkoutId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async retryMessage(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/messages/${g}/retry`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to retry message"}));throw new Error(Z(B))}return await Q.json()}async getAuthStatus(){const A=await fetch(`${this.baseUrl}/v1/auth/status`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to get auth status"}));throw new Error(Z(g))}return await A.json()}async setupSetuWallet(){const A=await fetch(`${this.baseUrl}/v1/auth/setu/setup`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to setup wallet"}));throw new Error(Z(g))}return await A.json()}async importSetuWallet(A){const g=await fetch(`${this.baseUrl}/v1/auth/setu/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({privateKey:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to import wallet"}));throw new Error(Z(Q))}return await g.json()}async addProvider(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to add provider"}));throw new Error(Z(B))}return await Q.json()}async removeProvider(A){const g=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to remove provider"}));throw new Error(Z(Q))}return await g.json()}async completeOnboarding(){const A=await fetch(`${this.baseUrl}/v1/auth/onboarding/complete`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to complete onboarding"}));throw new Error(Z(g))}return await A.json()}getOAuthStartUrl(A,g){const Q=`${this.baseUrl}/v1/auth/${A}/oauth/start`;return g?`${Q}?mode=${g}`:Q}async getOAuthUrl(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to get OAuth URL"}));throw new Error(Z(B))}return await Q.json()}async exchangeOAuthCode(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g,sessionId:Q})});if(!B.ok){const o=await B.json().catch(()=>({error:"Failed to exchange OAuth code"}));throw new Error(Z(o))}return await B.json()}async startCopilotDeviceFlow(){const A=await fetch(`${this.baseUrl}/v1/auth/copilot/device/start`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to start Copilot device flow"}));throw new Error(Z(g))}return await A.json()}async pollCopilotDeviceFlow(A){const g=await fetch(`${this.baseUrl}/v1/auth/copilot/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Poll failed"}));throw new Error(Z(Q))}return await g.json()}}const T=new wa;function Og(e){const{data:A,isLoading:g,error:Q}=PA({queryKey:["share-status",e],queryFn:()=>T.getShareStatus(e),enabled:!!e,staleTime:3e4});return{data:A,isLoading:g,error:Q}}const VB=[{id:"models",label:"/models",description:"Open model selector",icon:Ke},{id:"agents",label:"/agents",description:"Open agent selector",icon:fe},{id:"new",label:"/new",description:"Create new session",icon:Je},{id:"stop",label:"/stop",description:"Stop current generation",icon:zQ},{id:"help",label:"/help",description:"Show keyboard shortcuts and help",icon:VQ},{id:"vim",label:"/vim",description:e=>e.vimModeEnabled?"Disable Vim mode":"Enable Vim mode",icon:Vo},{id:"reasoning",label:"/reasoning",description:e=>e.reasoningEnabled?"Disable extended thinking":"Enable extended thinking",icon:Ng},{id:"stage",label:"/stage",description:"Stage all changes (git add -A)",icon:HA},{id:"commit",label:"/commit",description:"Commit staged changes",icon:XA},{id:"compact",label:"/compact",description:"Compact conversation to reduce context size",icon:Zo},{id:"branch",label:"/branch",description:"Branch session from last message",icon:Xo},{id:"delete",label:"/delete",description:"Delete current session",icon:kg},{id:"share",label:"/share",description:"Share session publicly",icon:Mg},{id:"sync",label:"/sync",description:"Sync new messages to shared session",icon:TA}];function ZB(e,A){return typeof e.description=="function"?e.description(A):e.description}function pa(e,A){const g=VB.filter(o=>!(o.id==="share"&&A.isShared||o.id==="sync"&&!A.isShared));if(!e)return g;const Q=e.toLowerCase(),B=[];for(const o of g){const s=ZB(o,A),E=o.label.toLowerCase().includes(Q),i=s.toLowerCase().includes(Q);if(E||i){const C=E?10:5;B.push({...o,matchScore:C})}}return B.sort((o,s)=>{const E=s.matchScore-o.matchScore;return E!==0?E:o.label.localeCompare(s.label)})}function ma({query:e,selectedIndex:A,onSelect:g,onEnterSelect:Q,onClose:B,sessionId:o}){const{preferences:s}=ot(),{data:E}=Og(o),i=u.useMemo(()=>({vimModeEnabled:s.vimMode,reasoningEnabled:s.reasoningEnabled,isShared:E?.shared}),[s.vimMode,s.reasoningEnabled,E?.shared]),C=u.useMemo(()=>pa(e,i),[e,i]);return u.useEffect(()=>{document.getElementById(`command-item-${A}`)?.scrollIntoView({block:"nearest"})},[A]),u.useEffect(()=>{Q(C[A]?.id)},[C,A,Q]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-command-popup]")||B()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[B]),C.length===0?t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No commands found"})}):t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>{const l=a.icon;return t.jsx("button",{type:"button",id:`command-item-${I}`,onMouseDown:r=>{r.preventDefault(),g(a.id)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===A?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-3 w-full",children:[t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-primary"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-mono text-sm font-medium text-foreground",children:a.label}),t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ZB(a,i)})]})]})},a.id)})})}const xa={sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-xl","2xl":"max-w-2xl"};function qe({isOpen:e,onClose:A,title:g,children:Q,showCloseButton:B=!0,closeOnBackdropClick:o=!0,closeOnEscape:s=!0,maxWidth:E="md"}){if(u.useEffect(()=>{if(!e||!s)return;const C=a=>{const I=a.target,l=I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable;(a.key==="Escape"||a.key==="q"&&!l)&&(a.preventDefault(),a.stopPropagation(),A())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,s,A]),u.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),!e)return null;const i=C=>{o&&C.target===C.currentTarget&&A()};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] cursor-default",onClick:i,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&i(C)},"aria-label":"Close modal"}),t.jsx("div",{className:`fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[9999] w-full ${xa[E]} px-4`,children:t.jsxs("div",{className:"bg-background border border-border rounded-lg shadow-lg",children:[(g||B)&&t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[g&&t.jsx("div",{className:"text-lg font-semibold text-foreground",children:g}),B&&t.jsx("button",{type:"button",onClick:A,className:"text-muted-foreground hover:text-foreground transition-colors ml-auto","aria-label":"Close",children:t.jsx(MA,{className:"h-5 w-5"})})]}),t.jsx("div",{className:"p-6",children:Q})]})})]})}const fa=[{keys:["Ctrl","H"],description:"Navigate to left sidebar (sessions)",category:"Navigation"},{keys:["Ctrl","L"],description:"Navigate to right sidebar (git)",category:"Navigation"},{keys:["Ctrl","/"],description:"Toggle left sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","\\"],description:"Toggle right sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","N"],description:"Create new session",category:"Navigation"},{keys:["ESC"],description:"Close sidebar and return to center",category:"Navigation"},{keys:["J"],description:"Navigate to next item (in focused list)",category:"List Navigation"},{keys:["K"],description:"Navigate to previous item (in focused list)",category:"List Navigation"},{keys:["Enter"],description:"Select focused item and return to input",category:"List Navigation"},{keys:["Space"],description:"Toggle stage/unstage for focused file (git panel)",category:"Git Operations"},{keys:["A"],description:"Stage all unstaged files",category:"Git Operations"},{keys:["U"],description:"Unstage all staged files",category:"Git Operations"},{keys:["C"],description:"Open commit modal (if files are staged)",category:"Git Operations"},{keys:["Tab"],description:"Toggle plan mode",category:"Chat"},{keys:["Enter"],description:"Send message",category:"Chat"},{keys:["Shift","Enter"],description:"New line in message",category:"Chat"},{keys:["@"],description:"Mention file (opens file picker)",category:"Chat"},{keys:["/"],description:"Slash command (opens command menu)",category:"Chat"}],Na=[{keys:["i"],description:"Enter insert mode at cursor (vim mode)",category:"Vim Mode"},{keys:["a"],description:"Enter insert mode after cursor (vim mode)",category:"Vim Mode"},{keys:["I"],description:"Enter insert mode at line start (vim mode)",category:"Vim Mode"},{keys:["A"],description:"Enter insert mode at line end (vim mode)",category:"Vim Mode"},{keys:["o"],description:"New line below and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["O"],description:"New line above and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["ESC"],description:"Return to normal mode (vim mode)",category:"Vim Mode"},{keys:["Enter"],description:"Send message in normal mode (vim mode)",category:"Vim Mode"},{keys:["w"],description:"Jump to next word start (vim mode)",category:"Vim Mode"},{keys:["e"],description:"Jump to next word end (vim mode)",category:"Vim Mode"},{keys:["b"],description:"Jump to previous word start (vim mode)",category:"Vim Mode"},{keys:["x"],description:"Delete character under cursor (vim mode)",category:"Vim Mode"},{keys:["s"],description:"Delete character and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["S"],description:"Delete line and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["f","{char}"],description:"Find and jump to next character on line (vim mode)",category:"Vim Mode"},{keys:["d","d"],description:"Delete current line (vim mode)",category:"Vim Mode"},{keys:["0"],description:"Jump to line start (vim mode)",category:"Vim Mode"},{keys:["$"],description:"Jump to line end (vim mode)",category:"Vim Mode"}],ka=[{command:"/models",description:"Open model selector"},{command:"/agents",description:"Open agent selector"},{command:"/new",description:"Create new session"},{command:"/help",description:"Show keyboard shortcuts and help (this modal)"},{command:"/compact",description:"Compact conversation to reduce context size"}];function Ma(e){const A={};for(const g of e)A[g.category]||(A[g.category]=[]),A[g.category].push(g);return A}function ya({isOpen:e,onClose:A}){const g=[...fa,...Na],Q=Ma(g),B=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{e?(o.current=document.activeElement,o.current&&o.current.blur()):o.current&&(o.current.focus(),o.current=null)},[e]),u.useEffect(()=>{if(!e)return;const s=E=>{const i=E.target;if(!(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable))if(E.key==="j"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:100,behavior:"smooth"})}else if(E.key==="k"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:-100,behavior:"smooth"})}else E.key==="Enter"&&(E.preventDefault(),A())};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,A]),t.jsx(qe,{isOpen:e,onClose:A,title:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(VQ,{className:"w-5 h-5"}),t.jsx("span",{children:"Keyboard Shortcuts & Help"})]}),maxWidth:"2xl",closeOnEscape:!0,closeOnBackdropClick:!0,children:t.jsxs("div",{ref:B,className:"space-y-6 max-h-[70vh] overflow-y-auto",children:[Object.entries(Q).map(([s,E])=>t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),s]}),t.jsx("div",{className:"space-y-2",children:E.map((i,C)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:i.description}),t.jsx("div",{className:"flex items-center gap-1",children:i.keys.map(a=>t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:a}),i.keys.indexOf(a)<i.keys.length-1&&t.jsx("span",{className:"text-muted-foreground",children:"+"})]},a))})]},`${s}-${i.description}`))})]},s)),t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),"Slash Commands"]}),t.jsx("div",{className:"space-y-2",children:ka.map((s,E)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:s.description}),t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:s.command})]},s.command))})]}),t.jsx("div",{className:"pt-4 border-t border-border",children:t.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.jsx("strong",{children:"Tip:"})," Shortcuts are disabled when typing in input fields. Press ",t.jsx("kbd",{className:"text-xs",children:"ESC"})," to close popups and return focus to chat input."]})})]})})}const Ga=`<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
30
+ `,onClick:B,role:"alert",children:[pi[e.type],t.jsx("span",{className:"text-sm text-foreground",children:e.message}),e.action&&t.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Bt(e.action.href)},className:"ml-auto flex items-center gap-1 text-xs text-primary hover:underline",children:[e.action.label,t.jsx(SA,{className:"h-3 w-3"})]})]})}function xi(){const e=_A(A=>A.toasts);return e.length===0?null:t.jsx("div",{className:"fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 max-w-sm",children:e.map(A=>t.jsx(mi,{toast:A},A.id))})}const Lg=UA(e=>({pendingApprovals:[],addPendingApproval:A=>e(g=>({pendingApprovals:[...g.pendingApprovals,A]})),removePendingApproval:A=>e(g=>({pendingApprovals:g.pendingApprovals.filter(Q=>Q.callId!==A)})),updatePendingApproval:(A,g)=>e(Q=>({pendingApprovals:Q.pendingApprovals.map(B=>B.callId===A?{...B,args:g}:B)})),clearPendingApprovals:()=>e({pendingApprovals:[]}),setPendingApprovals:A=>e({pendingApprovals:A})}));function Ce(e){return Array.isArray?Array.isArray(e):YB(e)==="[object Array]"}function fi(e){if(typeof e=="string")return e;let A=e+"";return A=="0"&&1/e==-1/0?"-0":A}function Ni(e){return e==null?"":fi(e)}function ge(e){return typeof e=="string"}function qB(e){return typeof e=="number"}function ki(e){return e===!0||e===!1||Mi(e)&&YB(e)=="[object Boolean]"}function OB(e){return typeof e=="object"}function Mi(e){return OB(e)&&e!==null}function YA(e){return e!=null}function $t(e){return!e.trim().length}function YB(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const yi="Incorrect 'index' type",Gi=e=>`Invalid value for key ${e}`,Fi=e=>`Pattern length exceeds max of ${e}.`,bi=e=>`Missing ${e} property in key`,Ui=e=>`Property 'weight' in key '${e}' must be a positive integer`,NQ=Object.prototype.hasOwnProperty;class Ji{constructor(A){this._keys=[],this._keyMap={};let g=0;A.forEach(Q=>{let B=TB(Q);this._keys.push(B),this._keyMap[B.id]=B,g+=B.weight}),this._keys.forEach(Q=>{Q.weight/=g})}get(A){return this._keyMap[A]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function TB(e){let A=null,g=null,Q=null,B=1,o=null;if(ge(e)||Ce(e))Q=e,A=kQ(e),g=ag(e);else{if(!NQ.call(e,"name"))throw new Error(bi("name"));const s=e.name;if(Q=s,NQ.call(e,"weight")&&(B=e.weight,B<=0))throw new Error(Ui(s));A=kQ(s),g=ag(s),o=e.getFn}return{path:A,id:g,weight:B,src:Q,getFn:o}}function kQ(e){return Ce(e)?e:e.split(".")}function ag(e){return Ce(e)?e.join("."):e}function Ki(e,A){let g=[],Q=!1;const B=(o,s,E)=>{if(YA(o))if(!s[E])g.push(o);else{let i=s[E];const C=o[i];if(!YA(C))return;if(E===s.length-1&&(ge(C)||qB(C)||ki(C)))g.push(Ni(C));else if(Ce(C)){Q=!0;for(let a=0,I=C.length;a<I;a+=1)B(C[a],s,E+1)}else s.length&&B(C,s,E+1)}};return B(e,ge(A)?A.split("."):A,0),Q?g:g[0]}const Si={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Ri={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,A)=>e.score===A.score?e.idx<A.idx?-1:1:e.score<A.score?-1:1},Li={location:0,threshold:.6,distance:100},qi={useExtendedSearch:!1,getFn:Ki,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var z={...Ri,...Si,...Li,...qi};const Oi=/[^ ]+/g;function Yi(e=1,A=3){const g=new Map,Q=Math.pow(10,A);return{get(B){const o=B.match(Oi).length;if(g.has(o))return g.get(o);const s=1/Math.pow(o,.5*e),E=parseFloat(Math.round(s*Q)/Q);return g.set(o,E),E},clear(){g.clear()}}}class qg{constructor({getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){this.norm=Yi(g,3),this.getFn=A,this.isCreated=!1,this.setIndexRecords()}setSources(A=[]){this.docs=A}setIndexRecords(A=[]){this.records=A}setKeys(A=[]){this.keys=A,this._keysMap={},A.forEach((g,Q)=>{this._keysMap[g.id]=Q})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,ge(this.docs[0])?this.docs.forEach((A,g)=>{this._addString(A,g)}):this.docs.forEach((A,g)=>{this._addObject(A,g)}),this.norm.clear())}add(A){const g=this.size();ge(A)?this._addString(A,g):this._addObject(A,g)}removeAt(A){this.records.splice(A,1);for(let g=A,Q=this.size();g<Q;g+=1)this.records[g].i-=1}getValueForItemAtKeyId(A,g){return A[this._keysMap[g]]}size(){return this.records.length}_addString(A,g){if(!YA(A)||$t(A))return;let Q={v:A,i:g,n:this.norm.get(A)};this.records.push(Q)}_addObject(A,g){let Q={i:g,$:{}};this.keys.forEach((B,o)=>{let s=B.getFn?B.getFn(A):this.getFn(A,B.path);if(YA(s)){if(Ce(s)){let E=[];const i=[{nestedArrIndex:-1,value:s}];for(;i.length;){const{nestedArrIndex:C,value:a}=i.pop();if(YA(a))if(ge(a)&&!$t(a)){let I={v:a,i:C,n:this.norm.get(a)};E.push(I)}else Ce(a)&&a.forEach((I,l)=>{i.push({nestedArrIndex:l,value:I})})}Q.$[o]=E}else if(ge(s)&&!$t(s)){let E={v:s,n:this.norm.get(s)};Q.$[o]=E}}}),this.records.push(Q)}toJSON(){return{keys:this.keys,records:this.records}}}function vB(e,A,{getFn:g=z.getFn,fieldNormWeight:Q=z.fieldNormWeight}={}){const B=new qg({getFn:g,fieldNormWeight:Q});return B.setKeys(e.map(TB)),B.setSources(A),B.create(),B}function Ti(e,{getFn:A=z.getFn,fieldNormWeight:g=z.fieldNormWeight}={}){const{keys:Q,records:B}=e,o=new qg({getFn:A,fieldNormWeight:g});return o.setKeys(Q),o.setIndexRecords(B),o}function Ct(e,{errors:A=0,currentLocation:g=0,expectedLocation:Q=0,distance:B=z.distance,ignoreLocation:o=z.ignoreLocation}={}){const s=A/e.length;if(o)return s;const E=Math.abs(Q-g);return B?s+E/B:E?1:s}function vi(e=[],A=z.minMatchCharLength){let g=[],Q=-1,B=-1,o=0;for(let s=e.length;o<s;o+=1){let E=e[o];E&&Q===-1?Q=o:!E&&Q!==-1&&(B=o-1,B-Q+1>=A&&g.push([Q,B]),Q=-1)}return e[o-1]&&o-Q>=A&&g.push([Q,o-1]),g}const pe=32;function ji(e,A,g,{location:Q=z.location,distance:B=z.distance,threshold:o=z.threshold,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,includeMatches:i=z.includeMatches,ignoreLocation:C=z.ignoreLocation}={}){if(A.length>pe)throw new Error(Fi(pe));const a=A.length,I=e.length,l=Math.max(0,Math.min(Q,I));let r=o,n=l;const d=E>1||i,c=d?Array(I):[];let D;for(;(D=e.indexOf(A,n))>-1;){let f=Ct(A,{currentLocation:D,expectedLocation:l,distance:B,ignoreLocation:C});if(r=Math.min(f,r),n=D+a,d){let M=0;for(;M<a;)c[D+M]=1,M+=1}}n=-1;let N=[],h=1,m=a+I;const y=1<<a-1;for(let f=0;f<a;f+=1){let M=0,w=m;for(;M<w;)Ct(A,{errors:f,currentLocation:l+w,expectedLocation:l,distance:B,ignoreLocation:C})<=r?M=w:m=w,w=Math.floor((m-M)/2+M);m=w;let G=Math.max(1,l-w+1),p=s?I:Math.min(l+w,I)+a,U=Array(p+2);U[p+1]=(1<<f)-1;for(let J=p;J>=G;J-=1){let S=J-1,Y=g[e.charAt(S)];if(d&&(c[S]=+!!Y),U[J]=(U[J+1]<<1|1)&Y,f&&(U[J]|=(N[J+1]|N[J])<<1|1|N[J+1]),U[J]&y&&(h=Ct(A,{errors:f,currentLocation:S,expectedLocation:l,distance:B,ignoreLocation:C}),h<=r)){if(r=h,n=S,n<=l)break;G=Math.max(1,2*l-n)}}if(Ct(A,{errors:f+1,currentLocation:l,expectedLocation:l,distance:B,ignoreLocation:C})>r)break;N=U}const x={isMatch:n>=0,score:Math.max(.001,h)};if(d){const f=vi(c,E);f.length?i&&(x.indices=f):x.isMatch=!1}return x}function Hi(e){let A={};for(let g=0,Q=e.length;g<Q;g+=1){const B=e.charAt(g);A[B]=(A[B]||0)|1<<Q-g-1}return A}const Nt=String.prototype.normalize?(e=>e.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"")):(e=>e);class jB{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){if(this.options={location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a},A=i?A:A.toLowerCase(),A=C?Nt(A):A,this.pattern=A,this.chunks=[],!this.pattern.length)return;const I=(r,n)=>{this.chunks.push({pattern:r,alphabet:Hi(r),startIndex:n})},l=this.pattern.length;if(l>pe){let r=0;const n=l%pe,d=l-n;for(;r<d;)I(this.pattern.substr(r,pe),r),r+=pe;if(n){const c=l-pe;I(this.pattern.substr(c),c)}}else I(this.pattern,0)}searchIn(A){const{isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B}=this.options;if(A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern===A){let d={isMatch:!0,score:0};return B&&(d.indices=[[0,A.length-1]]),d}const{location:o,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,ignoreLocation:a}=this.options;let I=[],l=0,r=!1;this.chunks.forEach(({pattern:d,alphabet:c,startIndex:D})=>{const{isMatch:N,score:h,indices:m}=ji(A,d,c,{location:o+D,distance:s,threshold:E,findAllMatches:i,minMatchCharLength:C,includeMatches:B,ignoreLocation:a});N&&(r=!0),l+=h,N&&m&&(I=[...I,...m])});let n={isMatch:r,score:r?l/this.chunks.length:1};return r&&B&&(n.indices=I),n}}class ce{constructor(A){this.pattern=A}static isMultiMatch(A){return MQ(A,this.multiRegex)}static isSingleMatch(A){return MQ(A,this.singleRegex)}search(){}}function MQ(e,A){const g=e.match(A);return g?g[1]:null}class Pi extends ce{constructor(A){super(A)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(A){const g=A===this.pattern;return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Wi extends ce{constructor(A){super(A)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(A){const Q=A.indexOf(this.pattern)===-1;return{isMatch:Q,score:Q?0:1,indices:[0,A.length-1]}}}class zi extends ce{constructor(A){super(A)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(A){const g=A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,this.pattern.length-1]}}}class Vi extends ce{constructor(A){super(A)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(A){const g=!A.startsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class Zi extends ce{constructor(A){super(A)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(A){const g=A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[A.length-this.pattern.length,A.length-1]}}}class Xi extends ce{constructor(A){super(A)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(A){const g=!A.endsWith(this.pattern);return{isMatch:g,score:g?0:1,indices:[0,A.length-1]}}}class HB extends ce{constructor(A,{location:g=z.location,threshold:Q=z.threshold,distance:B=z.distance,includeMatches:o=z.includeMatches,findAllMatches:s=z.findAllMatches,minMatchCharLength:E=z.minMatchCharLength,isCaseSensitive:i=z.isCaseSensitive,ignoreDiacritics:C=z.ignoreDiacritics,ignoreLocation:a=z.ignoreLocation}={}){super(A),this._bitapSearch=new jB(A,{location:g,threshold:Q,distance:B,includeMatches:o,findAllMatches:s,minMatchCharLength:E,isCaseSensitive:i,ignoreDiacritics:C,ignoreLocation:a})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(A){return this._bitapSearch.searchIn(A)}}class PB extends ce{constructor(A){super(A)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(A){let g=0,Q;const B=[],o=this.pattern.length;for(;(Q=A.indexOf(this.pattern,g))>-1;)g=Q+o,B.push([Q,g-1]);const s=!!B.length;return{isMatch:s,score:s?0:1,indices:B}}}const rg=[Pi,PB,zi,Vi,Xi,Zi,Wi,HB],yQ=rg.length,_i=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,$i="|";function Aa(e,A={}){return e.split($i).map(g=>{let Q=g.trim().split(_i).filter(o=>o&&!!o.trim()),B=[];for(let o=0,s=Q.length;o<s;o+=1){const E=Q[o];let i=!1,C=-1;for(;!i&&++C<yQ;){const a=rg[C];let I=a.isMultiMatch(E);I&&(B.push(new a(I,A)),i=!0)}if(!i)for(C=-1;++C<yQ;){const a=rg[C];let I=a.isSingleMatch(E);if(I){B.push(new a(I,A));break}}}return B})}const ea=new Set([HB.type,PB.type]);class ta{constructor(A,{isCaseSensitive:g=z.isCaseSensitive,ignoreDiacritics:Q=z.ignoreDiacritics,includeMatches:B=z.includeMatches,minMatchCharLength:o=z.minMatchCharLength,ignoreLocation:s=z.ignoreLocation,findAllMatches:E=z.findAllMatches,location:i=z.location,threshold:C=z.threshold,distance:a=z.distance}={}){this.query=null,this.options={isCaseSensitive:g,ignoreDiacritics:Q,includeMatches:B,minMatchCharLength:o,findAllMatches:E,ignoreLocation:s,location:i,threshold:C,distance:a},A=g?A:A.toLowerCase(),A=Q?Nt(A):A,this.pattern=A,this.query=Aa(this.pattern,this.options)}static condition(A,g){return g.useExtendedSearch}searchIn(A){const g=this.query;if(!g)return{isMatch:!1,score:1};const{includeMatches:Q,isCaseSensitive:B,ignoreDiacritics:o}=this.options;A=B?A:A.toLowerCase(),A=o?Nt(A):A;let s=0,E=[],i=0;for(let C=0,a=g.length;C<a;C+=1){const I=g[C];E.length=0,s=0;for(let l=0,r=I.length;l<r;l+=1){const n=I[l],{isMatch:d,indices:c,score:D}=n.search(A);if(d){if(s+=1,i+=D,Q){const N=n.constructor.type;ea.has(N)?E=[...E,...c]:E.push(c)}}else{i=0,s=0,E.length=0;break}}if(s){let l={isMatch:!0,score:i/s};return Q&&(l.indices=E),l}}return{isMatch:!1,score:1}}}const Ig=[];function ga(...e){Ig.push(...e)}function ng(e,A){for(let g=0,Q=Ig.length;g<Q;g+=1){let B=Ig[g];if(B.condition(e,A))return new B(e,A)}return new jB(e,A)}const kt={AND:"$and",OR:"$or"},lg={PATH:"$path",PATTERN:"$val"},cg=e=>!!(e[kt.AND]||e[kt.OR]),Qa=e=>!!e[lg.PATH],Ba=e=>!Ce(e)&&OB(e)&&!cg(e),GQ=e=>({[kt.AND]:Object.keys(e).map(A=>({[A]:e[A]}))});function WB(e,A,{auto:g=!0}={}){const Q=B=>{let o=Object.keys(B);const s=Qa(B);if(!s&&o.length>1&&!cg(B))return Q(GQ(B));if(Ba(B)){const i=s?B[lg.PATH]:o[0],C=s?B[lg.PATTERN]:B[i];if(!ge(C))throw new Error(Gi(i));const a={keyId:ag(i),pattern:C};return g&&(a.searcher=ng(C,A)),a}let E={children:[],operator:o[0]};return o.forEach(i=>{const C=B[i];Ce(C)&&C.forEach(a=>{E.children.push(Q(a))})}),E};return cg(e)||(e=GQ(e)),Q(e)}function oa(e,{ignoreFieldNorm:A=z.ignoreFieldNorm}){e.forEach(g=>{let Q=1;g.matches.forEach(({key:B,norm:o,score:s})=>{const E=B?B.weight:null;Q*=Math.pow(s===0&&E?Number.EPSILON:s,(E||1)*(A?1:o))}),g.score=Q})}function sa(e,A){const g=e.matches;A.matches=[],YA(g)&&g.forEach(Q=>{if(!YA(Q.indices)||!Q.indices.length)return;const{indices:B,value:o}=Q;let s={indices:B,value:o};Q.key&&(s.key=Q.key.src),Q.idx>-1&&(s.refIndex=Q.idx),A.matches.push(s)})}function Ea(e,A){A.score=e.score}function Ca(e,A,{includeMatches:g=z.includeMatches,includeScore:Q=z.includeScore}={}){const B=[];return g&&B.push(sa),Q&&B.push(Ea),e.map(o=>{const{idx:s}=o,E={item:A[s],refIndex:s};return B.length&&B.forEach(i=>{i(o,E)}),E})}class de{constructor(A,g={},Q){this.options={...z,...g},this.options.useExtendedSearch,this._keyStore=new Ji(this.options.keys),this.setCollection(A,Q)}setCollection(A,g){if(this._docs=A,g&&!(g instanceof qg))throw new Error(yi);this._myIndex=g||vB(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(A){YA(A)&&(this._docs.push(A),this._myIndex.add(A))}remove(A=()=>!1){const g=[];for(let Q=0,B=this._docs.length;Q<B;Q+=1){const o=this._docs[Q];A(o,Q)&&(this.removeAt(Q),Q-=1,B-=1,g.push(o))}return g}removeAt(A){this._docs.splice(A,1),this._myIndex.removeAt(A)}getIndex(){return this._myIndex}search(A,{limit:g=-1}={}){const{includeMatches:Q,includeScore:B,shouldSort:o,sortFn:s,ignoreFieldNorm:E}=this.options;let i=ge(A)?ge(this._docs[0])?this._searchStringList(A):this._searchObjectList(A):this._searchLogical(A);return oa(i,{ignoreFieldNorm:E}),o&&i.sort(s),qB(g)&&g>-1&&(i=i.slice(0,g)),Ca(i,this._docs,{includeMatches:Q,includeScore:B})}_searchStringList(A){const g=ng(A,this.options),{records:Q}=this._myIndex,B=[];return Q.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=g.searchIn(o);i&&B.push({item:o,idx:s,matches:[{score:C,value:o,norm:E,indices:a}]})}),B}_searchLogical(A){const g=WB(A,this.options),Q=(E,i,C)=>{if(!E.children){const{keyId:I,searcher:l}=E,r=this._findMatches({key:this._keyStore.get(I),value:this._myIndex.getValueForItemAtKeyId(i,I),searcher:l});return r&&r.length?[{idx:C,item:i,matches:r}]:[]}const a=[];for(let I=0,l=E.children.length;I<l;I+=1){const r=E.children[I],n=Q(r,i,C);if(n.length)a.push(...n);else if(E.operator===kt.AND)return[]}return a},B=this._myIndex.records,o={},s=[];return B.forEach(({$:E,i})=>{if(YA(E)){let C=Q(g,E,i);C.length&&(o[i]||(o[i]={idx:i,item:E,matches:[]},s.push(o[i])),C.forEach(({matches:a})=>{o[i].matches.push(...a)}))}}),s}_searchObjectList(A){const g=ng(A,this.options),{keys:Q,records:B}=this._myIndex,o=[];return B.forEach(({$:s,i:E})=>{if(!YA(s))return;let i=[];Q.forEach((C,a)=>{i.push(...this._findMatches({key:C,value:s[a],searcher:g}))}),i.length&&o.push({idx:E,item:s,matches:i})}),o}_findMatches({key:A,value:g,searcher:Q}){if(!YA(g))return[];let B=[];if(Ce(g))g.forEach(({v:o,i:s,n:E})=>{if(!YA(o))return;const{isMatch:i,score:C,indices:a}=Q.searchIn(o);i&&B.push({score:C,key:A,value:o,idx:s,norm:E,indices:a})});else{const{v:o,n:s}=g,{isMatch:E,score:i,indices:C}=Q.searchIn(o);E&&B.push({score:i,key:A,value:o,norm:s,indices:C})}return B}}de.version="7.1.0";de.createIndex=vB;de.parseIndex=Ti;de.config=z;de.parseQuery=WB;ga(ta);function ia(e){switch(e.split(".").pop()?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"go":case"rs":case"java":case"c":case"cpp":case"h":case"hpp":return WQ;case"json":case"yaml":case"yml":case"toml":return zo;case"md":case"txt":case"log":return Ft;case"png":case"jpg":case"jpeg":case"gif":case"svg":case"webp":return PQ;case"css":case"scss":case"sass":case"less":return Wo;case"html":case"xml":return Po;default:return le}}function aa(e,A){const g=A.get(e);return g?{added:{icon:Je,label:"Added",className:"text-green-500"},modified:{icon:gg,label:"Modified",className:"text-yellow-500"},untracked:{icon:Je,label:"Untracked",className:"text-blue-500"}}[g]||{icon:gg,label:"Modified",className:"text-yellow-500"}:null}function ra({files:e,changedFiles:A=[],query:g,selectedIndex:Q,onSelect:B,onEnterSelect:o,onClose:s}){const E=u.useMemo(()=>new Map(A?.map(a=>[a.path,a.status])||[]),[A]),i=u.useMemo(()=>new de(e.map(a=>({path:a,filename:a.split("/").pop()||a,normalized:a.replace(/[.\-_/]/g,"")})),{keys:[{name:"filename",weight:2},{name:"normalized",weight:1.5},{name:"path",weight:1}],threshold:.3,distance:200,ignoreLocation:!0,includeScore:!0}),[e]),C=u.useMemo(()=>{if(!g)return e.slice(0,20);const a=g.replace(/[.\-_/]/g,""),I=i.search(a);return I.sort((l,r)=>{const n=l.score??1,d=r.score??1;if(Math.abs(n-d)<.05){const D=E.has(l.item.path),N=E.has(r.item.path);if(D&&!N)return-1;if(!D&&N)return 1}return n-d}),I.slice(0,20).map(l=>l.item.path)},[i,g,e,E]);return u.useEffect(()=>{document.getElementById(`file-item-${Q}`)?.scrollIntoView({block:"nearest"})},[Q]),u.useEffect(()=>{o(C[Q])},[C,Q,o]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-file-mention-popup]")||s()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[s]),C.length===0?t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No files found"})}):t.jsx("div",{"data-file-mention-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>t.jsx("button",{type:"button",id:`file-item-${I}`,onMouseDown:l=>{l.preventDefault(),B(a)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===Q?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-2 w-full",children:[(()=>{const l=ia(a);return t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-muted-foreground"})})(),t.jsx("span",{className:"font-mono text-sm flex-1 truncate",children:a}),(()=>{const l=aa(a,E);return l&&t.jsx(l.icon,{className:`w-3.5 h-3.5 flex-shrink-0 ${l.className}`,title:l.label})})()]})},a))})}const zB="otto-preferences",ut={vimMode:!1,reasoningEnabled:!0};function Ia(){if(typeof window>"u")return ut;try{const e=window.localStorage.getItem(zB);if(e){const A=JSON.parse(e);return{...ut,...A}}}catch(e){console.warn("Failed to load preferences",e)}return ut}let ht=Ia();const dg=new Set;function na(){return ht}function la(){return ut}function ca(e){return dg.add(e),()=>dg.delete(e)}function da(){for(const e of dg)e()}function ua(e){if(ht={...ht,...e},typeof window<"u")try{window.localStorage.setItem(zB,JSON.stringify(ht))}catch(A){console.warn("Failed to persist preferences",A)}da()}function ot(){const e=u.useSyncExternalStore(ca,na,la),A=u.useCallback(g=>{ua(g)},[]);return u.useMemo(()=>({preferences:e,updatePreferences:A}),[e,A])}function Z(e){if(!e)return"Unknown error";if(typeof e=="string")return e;if(e&&typeof e=="object"){const A=e;if(A.error&&typeof A.error=="object"){const g=A.error;if(typeof g.message=="string")return g.message}if(typeof A.error=="string")return A.error;if(typeof A.message=="string")return A.message;try{return JSON.stringify(e)}catch{return"Error occurred (unable to parse)"}}return"Unknown error"}function ha(){const A=window.OTTO_SERVER_URL||qt;lA.setConfig({baseURL:A})}ha();function Ag(e){return{...e,title:e.title??null,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,lastActiveAt:typeof e.lastActiveAt=="string"?new Date(e.lastActiveAt).getTime():e.lastActiveAt}}function Da(e){return{...e,createdAt:typeof e.createdAt=="string"?new Date(e.createdAt).getTime():e.createdAt,completedAt:e.completedAt?typeof e.completedAt=="string"?new Date(e.completedAt).getTime():e.completedAt:null}}class wa{get baseUrl(){const A=window;return A.OTTO_SERVER_URL?A.OTTO_SERVER_URL:qt}async getSessions(){const A=await uC();if(A.error)throw new Error(Z(A.error));return(A.data||[]).map(Ag)}async createSession(A){const g=await hC({body:A});if(g.error)throw new Error(Z(g.error));if(!g.data)throw new Error("No data returned from create session");return Ag(g.data)}async updateSession(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const o=await Q.json().catch(()=>({error:"Failed to update session"}));throw new Error(Z(o))}const B=await Q.json();return Ag(B)}async deleteSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to delete session"}));throw new Error(Z(Q))}return await g.json()}async abortSession(A){const g=await DC({path:{sessionId:A}});if(g.error)throw new Error(Z(g.error));return g.data}async abortMessage(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/abort`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:g})});if(!B.ok)throw new Error("Failed to abort message");return B.json()}async getQueueState(A){const g=this.baseUrl,Q=await fetch(`${g}/v1/sessions/${A}/queue`);if(!Q.ok)throw new Error("Failed to get queue state");return Q.json()}async removeFromQueue(A,g){const Q=this.baseUrl,B=await fetch(`${Q}/v1/sessions/${A}/queue/${g}`,{method:"DELETE"});if(!B.ok)throw new Error("Failed to remove from queue");return B.json()}async getMessages(A){const g=await wC({path:{id:A}});if(g.error)throw new Error(Z(g.error));return(g.data||[]).map(Da)}async sendMessage(A,g){const Q=await pC({path:{id:A},body:g});if(Q.error)throw new Error(Z(Q.error));return Q.data}getStreamUrl(A){return`${this.baseUrl}/v1/sessions/${A}/stream`}async getConfig(){const A=await mC();if(A.error)throw new Error(Z(A.error));return A.data}async getModels(A){const g=await xC({path:{provider:A}});if(g.error)throw new Error(Z(g.error));return g.data}async getAllModels(){const A=await fetch(`${this.baseUrl}/v1/config/models`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to fetch models"}));throw new Error(Z(g))}return await A.json()}async updateDefaults(A){const g=await fetch(`${this.baseUrl}/v1/config/defaults`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to update defaults"}));throw new Error(Z(Q))}return await g.json()}async getGitStatus(){const A=await NC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async getGitDiff(A,g=!1){const Q=await kC({query:{file:A,staged:g?"true":"false"}});if(Q.error)throw new Error(Z(Q.error));return Q.data?.data}async generateCommitMessage(A){const g=await bC({body:A?{sessionId:A}:{}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async stageFiles(A){const g=await yC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async unstageFiles(A){const g=await GC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async restoreFiles(A){const g=await JC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async deleteFiles(A){const g=await KC({body:{files:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async commitChanges(A){const g=await FC({body:{message:A}});if(g.error)throw new Error(Z(g.error));return g.data?.data}async getGitBranch(){const A=await MC();if(A.error)throw new Error(Z(A.error));return A.data?.data}async pushCommits(){const A=await UC({body:{}});if(A.error)throw new Error(Z(A.error));return A.data?.data}async listFiles(){const A=await fC();if(A.error)throw new Error(Z(A.error));return A.data}async getSessionFiles(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/files`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to fetch session files"}));throw new Error(Z(Q))}return await g.json()}async createBranch(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/branch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create branch"}));throw new Error(Z(B))}return await Q.json()}async listBranches(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/branches`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to list branches"}));throw new Error(Z(Q))}return await g.json()}async getParentSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/parent`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to get parent session"}));throw new Error(Z(Q))}return await g.json()}async getSetuBalance(){try{const A=await fetch(`${this.baseUrl}/v1/setu/balance`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():null}catch{return null}}async getSetuWallet(){try{const A=await fetch(`${this.baseUrl}/v1/setu/wallet`,{method:"GET",headers:{"Content-Type":"application/json"}});return A.ok?await A.json():{configured:!1}}catch{return{configured:!1}}}async getSetuUsdcBalance(A="mainnet"){try{const g=await fetch(`${this.baseUrl}/v1/setu/usdc-balance?network=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async getShareStatus(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{shared:!1}}async shareSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to share session"}));throw new Error(Z(Q))}return await g.json()}async syncSession(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/share`,{method:"PUT",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to sync session"}));throw new Error(Z(Q))}return await g.json()}async approveToolCall(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:g,approved:Q})});if(!B.ok)throw new Error("Failed to send tool approval");return await B.json()}async getPendingApprovals(A){const g=await fetch(`${this.baseUrl}/v1/sessions/${A}/approval/pending`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{ok:!1,pending:[]}}async getPolarTopupEstimate(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/estimate?amount=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async createPolarCheckout(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/polar`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:A,successUrl:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to create checkout"}));throw new Error(Z(B))}return await Q.json()}async selectTopupMethod(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/select`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,method:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to select topup method"}));throw new Error(Z(B))}return await Q.json()}async cancelTopup(A,g){const Q=await fetch(`${this.baseUrl}/v1/setu/topup/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A,reason:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to cancel topup"}));throw new Error(Z(B))}return await Q.json()}async getPendingTopup(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/pending?sessionId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():{hasPending:!1}}catch{return{hasPending:!1}}}async getPolarTopupStatus(A){try{const g=await fetch(`${this.baseUrl}/v1/setu/topup/polar/status?checkoutId=${A}`,{method:"GET",headers:{"Content-Type":"application/json"}});return g.ok?await g.json():null}catch{return null}}async retryMessage(A,g){const Q=await fetch(`${this.baseUrl}/v1/sessions/${A}/messages/${g}/retry`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to retry message"}));throw new Error(Z(B))}return await Q.json()}async getAuthStatus(){const A=await fetch(`${this.baseUrl}/v1/auth/status`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to get auth status"}));throw new Error(Z(g))}return await A.json()}async setupSetuWallet(){const A=await fetch(`${this.baseUrl}/v1/auth/setu/setup`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to setup wallet"}));throw new Error(Z(g))}return await A.json()}async importSetuWallet(A){const g=await fetch(`${this.baseUrl}/v1/auth/setu/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({privateKey:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to import wallet"}));throw new Error(Z(Q))}return await g.json()}async addProvider(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to add provider"}));throw new Error(Z(B))}return await Q.json()}async removeProvider(A){const g=await fetch(`${this.baseUrl}/v1/auth/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json"}});if(!g.ok){const Q=await g.json().catch(()=>({error:"Failed to remove provider"}));throw new Error(Z(Q))}return await g.json()}async completeOnboarding(){const A=await fetch(`${this.baseUrl}/v1/auth/onboarding/complete`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to complete onboarding"}));throw new Error(Z(g))}return await A.json()}getOAuthStartUrl(A,g){const Q=`${this.baseUrl}/v1/auth/${A}/oauth/start`;return g?`${Q}?mode=${g}`:Q}async getOAuthUrl(A,g){const Q=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:g})});if(!Q.ok){const B=await Q.json().catch(()=>({error:"Failed to get OAuth URL"}));throw new Error(Z(B))}return await Q.json()}async exchangeOAuthCode(A,g,Q){const B=await fetch(`${this.baseUrl}/v1/auth/${A}/oauth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g,sessionId:Q})});if(!B.ok){const o=await B.json().catch(()=>({error:"Failed to exchange OAuth code"}));throw new Error(Z(o))}return await B.json()}async startCopilotDeviceFlow(){const A=await fetch(`${this.baseUrl}/v1/auth/copilot/device/start`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!A.ok){const g=await A.json().catch(()=>({error:"Failed to start Copilot device flow"}));throw new Error(Z(g))}return await A.json()}async pollCopilotDeviceFlow(A){const g=await fetch(`${this.baseUrl}/v1/auth/copilot/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:A})});if(!g.ok){const Q=await g.json().catch(()=>({error:"Poll failed"}));throw new Error(Z(Q))}return await g.json()}}const T=new wa;function Og(e){const{data:A,isLoading:g,error:Q}=PA({queryKey:["share-status",e],queryFn:()=>T.getShareStatus(e),enabled:!!e,staleTime:3e4});return{data:A,isLoading:g,error:Q}}const VB=[{id:"models",label:"/models",description:"Open model selector",icon:Ke},{id:"agents",label:"/agents",description:"Open agent selector",icon:fe},{id:"new",label:"/new",description:"Create new session",icon:Je},{id:"stop",label:"/stop",description:"Stop current generation",icon:zQ},{id:"help",label:"/help",description:"Show keyboard shortcuts and help",icon:VQ},{id:"vim",label:"/vim",description:e=>e.vimModeEnabled?"Disable Vim mode":"Enable Vim mode",icon:Vo},{id:"reasoning",label:"/reasoning",description:e=>e.reasoningEnabled?"Disable extended thinking":"Enable extended thinking",icon:Ng},{id:"stage",label:"/stage",description:"Stage all changes (git add -A)",icon:HA},{id:"commit",label:"/commit",description:"Commit staged changes",icon:XA},{id:"compact",label:"/compact",description:"Compact conversation to reduce context size",icon:Zo},{id:"branch",label:"/branch",description:"Branch session from last message",icon:Xo},{id:"delete",label:"/delete",description:"Delete current session",icon:kg},{id:"share",label:"/share",description:"Share session publicly",icon:Mg},{id:"sync",label:"/sync",description:"Sync new messages to shared session",icon:TA}];function ZB(e,A){return typeof e.description=="function"?e.description(A):e.description}function pa(e,A){const g=VB.filter(o=>!(o.id==="share"&&A.isShared||o.id==="sync"&&!A.isShared));if(!e)return g;const Q=e.toLowerCase(),B=[];for(const o of g){const s=ZB(o,A),E=o.label.toLowerCase().includes(Q),i=s.toLowerCase().includes(Q);if(E||i){const C=E?10:5;B.push({...o,matchScore:C})}}return B.sort((o,s)=>{const E=s.matchScore-o.matchScore;return E!==0?E:o.label.localeCompare(s.label)})}function ma({query:e,selectedIndex:A,onSelect:g,onEnterSelect:Q,onClose:B,sessionId:o}){const{preferences:s}=ot(),{data:E}=Og(o),i=u.useMemo(()=>({vimModeEnabled:s.vimMode,reasoningEnabled:s.reasoningEnabled,isShared:E?.shared}),[s.vimMode,s.reasoningEnabled,E?.shared]),C=u.useMemo(()=>pa(e,i),[e,i]);return u.useEffect(()=>{document.getElementById(`command-item-${A}`)?.scrollIntoView({block:"nearest"})},[A]),u.useEffect(()=>{Q(C[A]?.id)},[C,A,Q]),u.useEffect(()=>{const a=I=>{I.target.closest("[data-command-popup]")||B()};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[B]),C.length===0?t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg z-50 p-3",children:t.jsx("span",{className:"text-muted-foreground text-sm",children:"No commands found"})}):t.jsx("div",{"data-command-popup":!0,className:"absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-lg shadow-lg max-h-[300px] overflow-y-auto z-50",children:C.map((a,I)=>{const l=a.icon;return t.jsx("button",{type:"button",id:`command-item-${I}`,onMouseDown:r=>{r.preventDefault(),g(a.id)},className:`w-full text-left px-3 py-2 hover:bg-accent ${I===A?"bg-accent":""}`,children:t.jsxs("div",{className:"flex items-center gap-3 w-full",children:[t.jsx(l,{className:"w-4 h-4 flex-shrink-0 text-primary"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-mono text-sm font-medium text-foreground",children:a.label}),t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ZB(a,i)})]})]})},a.id)})})}const xa={sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-xl","2xl":"max-w-2xl"};function qe({isOpen:e,onClose:A,title:g,children:Q,showCloseButton:B=!0,closeOnBackdropClick:o=!0,closeOnEscape:s=!0,maxWidth:E="md"}){if(u.useEffect(()=>{if(!e||!s)return;const C=a=>{const I=a.target,l=I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable;(a.key==="Escape"||a.key==="q"&&!l)&&(a.preventDefault(),a.stopPropagation(),A())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,s,A]),u.useEffect(()=>{if(e)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[e]),!e)return null;const i=C=>{o&&C.target===C.currentTarget&&A()};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] cursor-default",onClick:i,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&i(C)},"aria-label":"Close modal"}),t.jsx("div",{className:`fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[9999] w-full ${xa[E]} px-4`,children:t.jsxs("div",{className:"bg-background border border-border rounded-lg shadow-lg",children:[(g||B)&&t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[g&&t.jsx("div",{className:"text-lg font-semibold text-foreground",children:g}),B&&t.jsx("button",{type:"button",onClick:A,className:"text-muted-foreground hover:text-foreground transition-colors ml-auto","aria-label":"Close",children:t.jsx(MA,{className:"h-5 w-5"})})]}),t.jsx("div",{className:"p-6",children:Q})]})})]})}const fa=[{keys:["Ctrl","H"],description:"Navigate to left sidebar (sessions)",category:"Navigation"},{keys:["Ctrl","L"],description:"Navigate to right sidebar (git)",category:"Navigation"},{keys:["Ctrl","/"],description:"Toggle left sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","\\"],description:"Toggle right sidebar collapse/expand",category:"Navigation"},{keys:["Ctrl","N"],description:"Create new session",category:"Navigation"},{keys:["ESC"],description:"Close sidebar and return to center",category:"Navigation"},{keys:["J"],description:"Navigate to next item (in focused list)",category:"List Navigation"},{keys:["K"],description:"Navigate to previous item (in focused list)",category:"List Navigation"},{keys:["Enter"],description:"Select focused item and return to input",category:"List Navigation"},{keys:["Space"],description:"Toggle stage/unstage for focused file (git panel)",category:"Git Operations"},{keys:["A"],description:"Stage all unstaged files",category:"Git Operations"},{keys:["U"],description:"Unstage all staged files",category:"Git Operations"},{keys:["C"],description:"Open commit modal (if files are staged)",category:"Git Operations"},{keys:["Tab"],description:"Toggle plan mode",category:"Chat"},{keys:["Enter"],description:"Send message",category:"Chat"},{keys:["Shift","Enter"],description:"New line in message",category:"Chat"},{keys:["@"],description:"Mention file (opens file picker)",category:"Chat"},{keys:["/"],description:"Slash command (opens command menu)",category:"Chat"}],Na=[{keys:["i"],description:"Enter insert mode at cursor (vim mode)",category:"Vim Mode"},{keys:["a"],description:"Enter insert mode after cursor (vim mode)",category:"Vim Mode"},{keys:["I"],description:"Enter insert mode at line start (vim mode)",category:"Vim Mode"},{keys:["A"],description:"Enter insert mode at line end (vim mode)",category:"Vim Mode"},{keys:["o"],description:"New line below and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["O"],description:"New line above and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["ESC"],description:"Return to normal mode (vim mode)",category:"Vim Mode"},{keys:["Enter"],description:"Send message in normal mode (vim mode)",category:"Vim Mode"},{keys:["w"],description:"Jump to next word start (vim mode)",category:"Vim Mode"},{keys:["e"],description:"Jump to next word end (vim mode)",category:"Vim Mode"},{keys:["b"],description:"Jump to previous word start (vim mode)",category:"Vim Mode"},{keys:["x"],description:"Delete character under cursor (vim mode)",category:"Vim Mode"},{keys:["s"],description:"Delete character and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["S"],description:"Delete line and enter insert mode (vim mode)",category:"Vim Mode"},{keys:["f","{char}"],description:"Find and jump to next character on line (vim mode)",category:"Vim Mode"},{keys:["d","d"],description:"Delete current line (vim mode)",category:"Vim Mode"},{keys:["0"],description:"Jump to line start (vim mode)",category:"Vim Mode"},{keys:["$"],description:"Jump to line end (vim mode)",category:"Vim Mode"}],ka=[{command:"/models",description:"Open model selector"},{command:"/agents",description:"Open agent selector"},{command:"/new",description:"Create new session"},{command:"/help",description:"Show keyboard shortcuts and help (this modal)"},{command:"/compact",description:"Compact conversation to reduce context size"}];function Ma(e){const A={};for(const g of e)A[g.category]||(A[g.category]=[]),A[g.category].push(g);return A}function ya({isOpen:e,onClose:A}){const g=[...fa,...Na],Q=Ma(g),B=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{e?(o.current=document.activeElement,o.current&&o.current.blur()):o.current&&(o.current.focus(),o.current=null)},[e]),u.useEffect(()=>{if(!e)return;const s=E=>{const i=E.target;if(!(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable))if(E.key==="j"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:100,behavior:"smooth"})}else if(E.key==="k"){E.preventDefault();const a=B.current;a&&a.scrollBy({top:-100,behavior:"smooth"})}else E.key==="Enter"&&(E.preventDefault(),A())};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,A]),t.jsx(qe,{isOpen:e,onClose:A,title:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(VQ,{className:"w-5 h-5"}),t.jsx("span",{children:"Keyboard Shortcuts & Help"})]}),maxWidth:"2xl",closeOnEscape:!0,closeOnBackdropClick:!0,children:t.jsxs("div",{ref:B,className:"space-y-6 max-h-[70vh] overflow-y-auto",children:[Object.entries(Q).map(([s,E])=>t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),s]}),t.jsx("div",{className:"space-y-2",children:E.map((i,C)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:i.description}),t.jsx("div",{className:"flex items-center gap-1",children:i.keys.map(a=>t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:a}),i.keys.indexOf(a)<i.keys.length-1&&t.jsx("span",{className:"text-muted-foreground",children:"+"})]},a))})]},`${s}-${i.description}`))})]},s)),t.jsxs("div",{children:[t.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[t.jsx(Zg,{className:"w-4 h-4"}),"Slash Commands"]}),t.jsx("div",{className:"space-y-2",children:ka.map((s,E)=>t.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-accent/50 hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm text-foreground",children:s.description}),t.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-background border border-border rounded shadow-sm",children:s.command})]},s.command))})]}),t.jsx("div",{className:"pt-4 border-t border-border",children:t.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.jsx("strong",{children:"Tip:"})," Shortcuts are disabled when typing in input fields. Press ",t.jsx("kbd",{className:"text-xs",children:"ESC"})," to close popups and return focus to chat input."]})})]})})}const Ga=`<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
31
31
  <path d="M26.9568 9.88184H22.1265L30.7753 31.7848H35.4917L26.9568 9.88184ZM13.028 9.88184L4.4917 31.7848H9.32203L11.2305 27.1793H20.2166L22.0126 31.6724H26.8444L18.0832 9.88184H13.028ZM12.5783 23.1361L15.4987 15.3853L18.5315 23.1361H12.5783Z" fill="currentColor"/>
32
32
  </svg>`,Fa=`<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
33
33
  <path d="M32.8377 17.282C33.2127 16.25 33.3072 15.218 33.2127 14.1875C33.1197 13.1571 32.7447 12.1251 32.2752 11.1876C31.4322 9.78209 30.2127 8.6571 28.8072 8.0001C27.3072 7.34461 25.7127 7.15711 24.1197 7.53211C23.3698 6.78212 22.5253 6.12512 21.5878 5.65713C20.6503 5.18913 19.5253 5.00013 18.4948 5.00013C16.8851 4.99074 15.3125 5.48246 13.9948 6.40712C12.6824 7.34311 11.7449 8.6571 11.2754 10.1571C10.1504 10.4376 9.21289 10.9071 8.27539 11.4696C7.4324 12.1251 6.77541 12.9696 6.21291 13.8126C5.36992 15.2195 5.08792 16.8125 5.27542 18.407C5.46399 19.9968 6.11605 21.496 7.1504 22.718C6.79608 23.7086 6.66795 24.7659 6.77541 25.8124C6.86991 26.8444 7.2449 27.8749 7.7129 28.8124C8.55739 30.2194 9.77538 31.3444 11.1824 31.9999C12.6824 32.6569 14.2753 32.8444 15.8698 32.4694C16.6198 33.2194 17.4628 33.8749 18.4003 34.3444C19.3378 34.8139 20.4628 34.9999 21.4948 34.9999C23.1043 35.0097 24.6769 34.5185 25.9947 33.5944C27.3072 32.6569 28.2447 31.3444 28.7127 29.8444C29.7719 29.6432 30.7682 29.1934 31.6197 28.5319C32.4627 27.8749 33.2127 27.1249 33.6822 26.1874C34.5251 24.7819 34.8071 23.1875 34.6196 21.5945C34.4322 20 33.8697 18.5015 32.8377 17.282ZM21.5878 33.0304C20.0878 33.0304 18.9628 32.5609 17.9323 31.7179C17.9323 31.7179 18.0253 31.6234 18.1198 31.6234L24.1197 28.1554C24.2862 28.0803 24.4196 27.9469 24.4947 27.7804C24.5698 27.636 24.6021 27.4731 24.5877 27.3109V18.875L27.1197 20.375V27.3124C27.1455 28.0547 27.0215 28.7945 26.755 29.4878C26.4885 30.181 26.085 30.8134 25.5687 31.3473C25.0523 31.8811 24.4337 32.3054 23.7497 32.5949C23.0658 32.8843 22.3305 33.0314 21.5878 33.0304ZM9.49488 27.8749C8.83789 26.7499 8.55739 25.4374 8.83789 24.125C8.83789 24.125 8.93239 24.2195 9.02539 24.2195L15.0253 27.6874C15.1693 27.7638 15.3325 27.7966 15.4948 27.7819C15.6823 27.7819 15.8698 27.7819 15.9628 27.6874L23.2753 23.4695V26.3749L17.1823 29.9374C16.5506 30.3042 15.8527 30.5427 15.1287 30.6393C14.4046 30.7358 13.6686 30.6884 12.9629 30.4999C11.4629 30.1249 10.2449 29.1874 9.49488 27.8749ZM7.9004 14.8445C8.56239 13.7234 9.58826 12.8627 10.8074 12.4056V19.532C10.8074 19.718 10.8074 19.907 10.9004 20C10.9755 20.1665 11.1089 20.2998 11.2754 20.375L18.5878 24.5944L16.0573 26.0944L10.0574 22.625C9.41842 22.2639 8.85742 21.7797 8.40684 21.2004C7.95627 20.6211 7.62506 19.9582 7.4324 19.25C7.05741 17.8445 7.1504 16.157 7.9004 14.8445ZM28.6197 19.625L21.3073 15.407L23.8377 13.9071L29.8377 17.375C30.7752 17.9375 31.5252 18.6875 31.9947 19.625C32.4642 20.5625 32.7447 21.5945 32.6502 22.7195C32.5603 23.7755 32.1699 24.7837 31.5252 25.6249C30.8697 26.4694 30.0252 27.1249 28.9947 27.4999V20.375C28.9947 20.1875 28.9947 20 28.9002 19.907C28.9002 19.907 28.8072 19.718 28.6197 19.625ZM31.1502 15.875C31.1502 15.875 31.0572 15.782 30.9627 15.782L24.9627 12.3126C24.7752 12.2196 24.6822 12.2196 24.4947 12.2196C24.3072 12.2196 24.1197 12.2196 24.0252 12.3126L16.7128 16.532V13.6251L22.8073 10.0626C23.7448 9.50009 24.7752 9.31259 25.9002 9.31259C26.9322 9.31259 27.9627 9.68759 28.9002 10.3446C29.7447 11.0001 30.4947 11.8446 30.8697 12.7821C31.2447 13.7196 31.3377 14.8445 31.1502 15.875ZM15.4003 21.125L12.8699 19.625V12.5946C12.8699 11.5626 13.1503 10.4376 13.7128 9.59459C14.2753 8.6571 15.1198 8.0001 16.0573 7.53211C17.0127 7.05249 18.0956 6.88812 19.1503 7.06261C20.1823 7.15711 21.2128 7.62511 22.0573 8.2821C22.0573 8.2821 21.9628 8.3751 21.8698 8.3751L15.8698 11.8446C15.7033 11.9197 15.57 12.0531 15.4948 12.2196C15.4003 12.4071 15.4003 12.5001 15.4003 12.6876V21.125ZM16.7128 18.125L19.9948 16.25L23.2753 18.125V21.875L19.9948 23.75L16.7128 21.875V18.125Z" fill="currentColor"/>
@@ -79,7 +79,7 @@ ${d.slice(c)}`;return Q(D),setTimeout(()=>{r.setSelectionRange(c,c)},0),!0}if(s=
79
79
  `,c-1)+1;if(D>0){const N=c-D,h=D-1,m=d.lastIndexOf(`
80
80
  `,h-1)+1,y=h-m,x=m+Math.min(N,y);r.setSelectionRange(x,x)}return!0}return!1},[s,A,g,Q,i,C,a]);return{vimMode:B,setVimMode:o,handleVimNormalMode:I}}function va(){const[e,A]=u.useState(!1),[g,Q]=u.useState(""),[B,o]=u.useState(0),[s,E]=u.useState(),i=u.useCallback((I,l,r)=>{const n=l.current;if(!n)return;const d=n.value,c=n.selectionStart,N=d.slice(0,c).match(/@(\S*)$/);if(!N)return;const h=c-N[0].length,m=`${d.slice(0,h)}@${I} ${d.slice(c)}`;r(m),A(!1),setTimeout(()=>{const y=h+I.length+2;n.setSelectionRange(y,y),n.focus()},0)},[]),C=u.useCallback(I=>{E(I)},[]),a=u.useCallback((I,l)=>{const n=I.slice(0,l).match(/@(\S*)$/);n?(A(!0),Q(n[1]),o(0)):A(!1)},[]);return{showFileMention:e,mentionQuery:g,mentionSelectedIndex:B,currentFileToSelect:s,setShowFileMention:A,setMentionQuery:Q,setMentionSelectedIndex:o,setCurrentFileToSelect:E,handleFileSelect:i,handleEnterSelect:C,checkForMention:a}}function ja({onCommand:e,updatePreferences:A,vimModeEnabled:g,reasoningEnabled:Q,textareaRef:B,setMessage:o,setShowShortcutsModal:s,sessionId:E}){const[i,C]=u.useState(!1),[a,I]=u.useState(""),[l,r]=u.useState(0),[n,d]=u.useState(),c=u.useCallback(async h=>{const m=()=>{o(""),C(!1),B.current&&(B.current.style.height="auto"),B.current?.focus()};if(h==="help"){s(!0),m();return}if(h==="vim"){A({vimMode:!g}),m();return}if(h==="reasoning"){A({reasoningEnabled:!Q}),m();return}if(h==="stop"){if(E)try{await T.abortSession(E)}catch(y){console.error("Failed to stop generation:",y)}m();return}e&&e(h),m()},[e,g,Q,A,B,o,s,E]),D=u.useCallback(h=>{d(h)},[]),N=u.useCallback(h=>{h.startsWith("/")&&!h.includes(" ")?(C(!0),I(h.slice(1)),r(0)):C(!1)},[]);return{showCommandSuggestions:i,commandQuery:a,commandSelectedIndex:l,currentCommandToSelect:n,setShowCommandSuggestions:C,setCommandQuery:I,setCommandSelectedIndex:r,setCurrentCommandToSelect:d,handleCommandSelect:c,handleCommandEnterSelect:D,checkForCommand:N}}function Ha(e){return A=>{const{showFileMention:g,showCommandSuggestions:Q,mentionSelectedIndex:B,commandSelectedIndex:o,currentFileToSelect:s,currentCommandToSelect:E,isPlanMode:i,vimModeEnabled:C,vimMode:a,setMentionSelectedIndex:I,setCommandSelectedIndex:l,setShowFileMention:r,setShowCommandSuggestions:n,setIsPlanMode:d,setVimMode:c,handleFileSelect:D,handleCommandSelect:N,handleSend:h,handleVimNormalMode:m,onPlanModeToggle:y}=e;if(Q){const x=VB.length;A.key==="ArrowDown"||A.ctrlKey&&A.key==="j"?(A.preventDefault(),l((o+1)%x)):A.key==="ArrowUp"||A.ctrlKey&&A.key==="k"?(A.preventDefault(),l((o-1+x)%x)):A.key==="Enter"?(A.preventDefault(),E&&N(E)):A.key==="Escape"&&(A.preventDefault(),n(!1));return}if(g){A.key==="ArrowDown"||A.ctrlKey&&A.key==="j"?(A.preventDefault(),I((B+1)%20)):A.key==="ArrowUp"||A.ctrlKey&&A.key==="k"?(A.preventDefault(),I((B-1+20)%20)):A.key==="Enter"?(A.preventDefault(),s&&D(s)):A.key==="Escape"&&(A.preventDefault(),r(!1),C&&c("normal"));return}if(!(C&&a==="normal"&&m(A))){if(C&&a==="insert"&&A.key==="Escape"){A.preventDefault(),c("normal");return}if(A.key==="Tab"){A.preventDefault();const x=!i;d(x),y?.(x)}else A.key==="Enter"&&!A.shiftKey&&(!C||a==="normal")&&(A.preventDefault(),h())}}}const sA=UA(e=>({balance:null,usdcBalance:null,network:"mainnet",isPaymentPending:!1,lastPaymentAmount:null,walletAddress:null,isLoading:!1,isTopupModalOpen:!1,setBalance:A=>e({balance:A}),setUsdcBalance:A=>e({usdcBalance:A}),setNetwork:A=>e({network:A}),setPaymentPending:A=>e({isPaymentPending:A}),setLastPaymentAmount:A=>e({lastPaymentAmount:A}),setWalletAddress:A=>e({walletAddress:A}),setLoading:A=>e({isLoading:A}),openTopupModal:()=>e({isTopupModalOpen:!0}),closeTopupModal:()=>e({isTopupModalOpen:!1})})),Pa=u.memo(u.forwardRef(function({onSend:A,onCommand:g,disabled:Q,onConfigClick:B,onPlanModeToggle:o,isPlanMode:s,reasoningEnabled:E,sessionId:i,images:C=[],documents:a=[],onFileRemove:I,isDragging:l=!1,onPaste:r,visionEnabled:n=!1,modelName:d,providerName:c,authType:D,researchContexts:N=[],onResearchContextRemove:h,onRefreshBalance:m,isBalanceLoading:y=!1,onModelInfoClick:x},f){const[M,w]=u.useState(""),[G,p]=u.useState(s||!1),[U,k]=u.useState(!1),J=u.useRef(null),{data:S,isLoading:Y}=Ya(),{preferences:q,updatePreferences:R}=ot(),O=S?.files||[],K=S?.changedFiles||[],v=sA(gA=>gA.balance),V=c==="setu",_=u.useRef(()=>{}),{showFileMention:X,mentionQuery:iA,mentionSelectedIndex:mA,currentFileToSelect:j,setShowFileMention:L,setMentionSelectedIndex:AA,setCurrentFileToSelect:EA,handleFileSelect:NA,handleEnterSelect:DA,checkForMention:yA}=va(),{showCommandSuggestions:ue,commandQuery:Te,commandSelectedIndex:oe,currentCommandToSelect:Ie,setShowCommandSuggestions:KA,setCommandSelectedIndex:he,setCurrentCommandToSelect:zA,handleCommandSelect:De,handleCommandEnterSelect:H,checkForCommand:oA}=ja({onCommand:g,updatePreferences:R,vimModeEnabled:q.vimMode,reasoningEnabled:q.reasoningEnabled,textareaRef:J,setMessage:w,setShowShortcutsModal:k,sessionId:i}),{vimMode:eA,setVimMode:GA,handleVimNormalMode:ee}=Ta({enabled:q.vimMode,onSend:()=>_.current(),textareaRef:J,setMessage:w});u.useEffect(()=>{J.current?.focus()},[]),u.useEffect(()=>{s!==void 0&&p(s)},[s]),u.useImperativeHandle(f,()=>({focus:()=>{J.current?.focus()},setValue:gA=>{w(gA),J.current?.focus()}}));const Ge=u.useCallback(()=>{const gA=J.current;gA&&(gA.style.height="auto",gA.style.height=`${gA.scrollHeight}px`)},[]);u.useEffect(()=>{Ge()},[Ge,M]);const OA=u.useCallback(()=>{L(!1),EA(void 0)},[L,EA]),ve=u.useCallback(()=>{KA(!1),zA(void 0)},[KA,zA]),je=u.useCallback(gA=>{NA(gA,J,w)},[NA]),we=u.useCallback(()=>{!M.trim()||Q||(A(M),w(""),L(!1),KA(!1),EA(void 0),zA(void 0),J.current&&(J.current.style.height="auto"),q.vimMode&&GA("normal"),J.current?.focus())},[M,Q,A,q.vimMode,L,KA,EA,zA,GA]);u.useEffect(()=>{_.current=we},[we]);const zt=u.useCallback(gA=>{if(q.vimMode&&eA==="normal")return;const se=gA.target.value;w(se),oA(se),se.startsWith("/")&&!se.includes(" ")?(L(!1),EA(void 0)):(KA(!1),zA(void 0),yA(se,gA.target.selectionStart))},[q.vimMode,eA,oA,L,EA,KA,zA,yA]),Fe=u.useMemo(()=>Ha({showFileMention:X,showCommandSuggestions:ue,mentionSelectedIndex:mA,commandSelectedIndex:oe,currentFileToSelect:j,currentCommandToSelect:Ie,isPlanMode:G,vimModeEnabled:q.vimMode,vimMode:eA,setMentionSelectedIndex:AA,setCommandSelectedIndex:he,setShowFileMention:L,setShowCommandSuggestions:KA,setIsPlanMode:p,setVimMode:GA,handleFileSelect:je,handleCommandSelect:De,handleSend:we,handleVimNormalMode:ee,onPlanModeToggle:o}),[X,ue,mA,oe,j,Ie,G,q.vimMode,eA,AA,he,L,KA,GA,je,De,we,ee,o]);u.useEffect(()=>{q.vimMode||GA("insert")},[q.vimMode,GA]);const Vt=u.useCallback(gA=>{r?.(gA)},[r]),P=C.length>0,dA=a.length>0,FA=P||dA;return t.jsxs(t.Fragment,{children:[l&&t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm pointer-events-none",children:t.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 rounded-2xl bg-card border-2 border-dashed border-primary/50",children:[t.jsx("div",{className:"p-4 rounded-full bg-primary/10",children:t.jsx(le,{className:"w-12 h-12 text-primary"})}),t.jsxs("div",{className:"text-center",children:[t.jsx("p",{className:"text-lg font-medium text-foreground",children:"Drop files here"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"Images, PDF, Markdown, Text up to 10MB"})]})]})}),t.jsx("div",{className:"absolute bottom-0 left-0 right-0 pt-16 pb-6 md:pb-8 px-2 md:px-4 bg-gradient-to-t from-background via-background to-transparent pointer-events-none z-20 safe-area-inset-bottom",children:t.jsxs("div",{className:"max-w-3xl mx-auto pointer-events-auto mb-2 md:mb-0 relative",children:[q.vimMode&&eA==="normal"&&t.jsx("div",{className:"absolute -top-6 right-0 px-2 py-0.5 text-xs font-mono font-semibold bg-amber-500/90 text-white rounded shadow-sm",children:"NORMAL"}),q.vimMode&&eA==="insert"&&t.jsx("div",{className:"absolute -top-6 right-0 px-2 py-0.5 text-xs font-mono font-semibold bg-green-500/90 text-white rounded shadow-sm",children:"INSERT"}),t.jsxs("div",{className:`relative flex flex-col rounded-3xl p-1 transition-all touch-manipulation ${G?"bg-slate-100 dark:bg-slate-900/40 border border-slate-300 dark:border-slate-700 focus-within:border-slate-400 dark:focus-within:border-slate-600 focus-within:ring-1 focus-within:ring-slate-300 dark:focus-within:ring-slate-700":"bg-card border border-border focus-within:border-primary/60 focus-within:ring-1 focus-within:ring-primary/40"}`,children:[FA&&t.jsxs("div",{className:"flex flex-wrap gap-2 px-3 pt-2 pb-1",children:[C.map(gA=>t.jsxs("div",{className:"relative group w-12 h-12 rounded-lg overflow-hidden bg-muted",children:[t.jsx("img",{src:gA.preview,alt:"Attachment",className:"w-full h-full object-cover"}),t.jsx("button",{type:"button",onClick:()=>I?.(gA.id),className:"absolute top-0 right-0 p-0.5 bg-black/60 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity",children:t.jsx(MA,{className:"w-3 h-3 text-white"})})]},gA.id)),a.map(gA=>t.jsxs("div",{className:"relative group flex items-center gap-2 px-3 py-2 rounded-lg bg-muted max-w-[200px]",children:[gA.type==="pdf"?t.jsx(le,{className:"w-4 h-4 text-red-500 flex-shrink-0"}):t.jsx(Ft,{className:"w-4 h-4 text-blue-500 flex-shrink-0"}),t.jsx("span",{className:"text-xs truncate",children:gA.name}),t.jsx("button",{type:"button",onClick:()=>I?.(gA.id),className:"absolute top-0 right-0 p-0.5 bg-black/60 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity",children:t.jsx(MA,{className:"w-3 h-3 text-white"})})]},gA.id))]}),N.length>0&&t.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-2 pb-1",children:N.map(gA=>t.jsxs("div",{className:"relative group flex items-center gap-2 px-3 py-2 rounded-lg bg-teal-500/10 border border-teal-500/30 max-w-[200px]",children:[t.jsx(Ze,{className:"w-4 h-4 text-teal-500 flex-shrink-0"}),t.jsx("span",{className:"text-xs truncate text-teal-600 dark:text-teal-400",children:gA.label}),h&&t.jsx("button",{type:"button",onClick:()=>h(gA.id),className:"absolute top-0 right-0 p-0.5 bg-black/60 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity",children:t.jsx(MA,{className:"w-3 h-3 text-white"})})]},gA.id))}),t.jsxs("div",{className:"flex items-end gap-1",children:[B&&t.jsx("button",{type:"button",onClick:B,className:"flex items-center justify-center w-10 h-10 rounded-full hover:bg-background/50 active:bg-background/70 transition-colors text-muted-foreground hover:text-foreground flex-shrink-0 touch-manipulation",children:t.jsx(_o,{className:"w-4 h-4"})}),t.jsx(Ot,{ref:J,value:M,onChange:zt,onKeyDown:Fe,onPaste:Vt,placeholder:G?"Plan mode - Type a message...":"Type a message...",disabled:Q,rows:1,className:`border-0 bg-transparent pl-1 pr-2 py-2 max-h-[200px] overflow-y-auto leading-normal resize-none scrollbar-hide text-base ${q.vimMode&&eA==="normal"?"caret-[6px]":""}`,style:{height:"2.5rem"}}),t.jsx("button",{type:"button",onClick:we,disabled:Q||!M.trim()&&!FA,className:`flex items-center justify-center w-10 h-10 rounded-full transition-colors flex-shrink-0 touch-manipulation ${M.trim()||FA?"bg-primary hover:bg-primary/90 active:bg-primary/80 text-primary-foreground":"bg-transparent text-muted-foreground"}`,children:t.jsx(ZQ,{className:"w-4 h-4"})})]})]}),(E||n||d||c||D)&&t.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto] items-center mt-1 px-3",children:[t.jsx("div",{className:"justify-self-start flex-shrink-0",children:E&&t.jsxs("span",{className:"text-[10px] text-indigo-600 dark:text-indigo-300 flex items-center gap-1",children:[t.jsx(Ng,{className:"h-3 w-3"}),"thinking"]})}),t.jsx("div",{className:"justify-self-center",children:(c||d||D)&&t.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center gap-1 px-2 py-0.5",children:[t.jsxs("button",{type:"button",onClick:x,className:"flex items-center gap-1 transition-colors hover:text-foreground cursor-pointer",children:[c&&t.jsxs(t.Fragment,{children:[t.jsx(WA,{provider:c,size:12,className:"opacity-70"}),t.jsx("span",{className:"opacity-40",children:"/"})]}),d&&t.jsx("span",{children:d}),D&&D==="oauth"&&t.jsx("span",{className:"opacity-50",children:"(pro)"})]}),V&&v!==null&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400",children:["$",v.toFixed(2)]}),m&&t.jsx("button",{type:"button",onClick:gA=>{gA.stopPropagation(),m()},disabled:y,className:"p-0.5 hover:bg-background/50 rounded transition-colors disabled:opacity-50",children:t.jsx(TA,{className:`h-2.5 w-2.5 text-muted-foreground ${y?"animate-spin":""}`})})]})]})}),t.jsx("div",{className:"justify-self-end flex-shrink-0",children:n&&t.jsxs("span",{className:"text-[10px] text-emerald-600 dark:text-emerald-400 flex items-center gap-1",children:[t.jsx(PQ,{className:"h-3 w-3"}),"images"]})})]}),X&&!Y&&t.jsx(ra,{files:O,changedFiles:K,query:iA,selectedIndex:mA,onSelect:je,onEnterSelect:DA,onClose:OA}),ue&&t.jsx(ma,{query:Te,selectedIndex:oe,onSelect:De,onEnterSelect:H,onClose:ve,sessionId:i}),t.jsx(ya,{isOpen:U,onClose:()=>k(!1)})]})})]})}));function Mt(e){return PA({queryKey:["messages",e],queryFn:()=>{if(!e)throw new Error("Session ID is required");return T.getMessages(e)},enabled:!!e})}function Wa(e){const A=nA();return pA({mutationFn:g=>T.sendMessage(e,g),onSuccess:()=>{A.invalidateQueries({queryKey:["messages",e]}),A.invalidateQueries({queryKey:["sessions"]})}})}function Yt(){return PA({queryKey:["sessions"],queryFn:()=>T.getSessions(),refetchInterval:5e3,staleTime:5e3})}function XB(e){const{data:A}=Yt();return A?.find(g=>g.id===e)}function za(){const e=nA();return pA({mutationFn:A=>T.createSession(A),onSuccess:()=>{e.invalidateQueries({queryKey:["sessions"]})}})}function _B(e){const A=nA();return pA({mutationFn:g=>T.updateSession(e,g),onSuccess:async()=>{await A.invalidateQueries({queryKey:["sessions"]}),await A.invalidateQueries({queryKey:["session",e]})}})}function Va(){const e=nA();return pA({mutationFn:A=>T.deleteSession(A),onSuccess:()=>{e.invalidateQueries({queryKey:["sessions"]})}})}function Yg(){return PA({queryKey:["config"],queryFn:()=>T.getConfig(),staleTime:3e4})}function Tt(){return PA({queryKey:["models","all"],queryFn:()=>T.getAllModels()})}function Za(){const e=nA();return pA({mutationFn:A=>T.updateDefaults(A),onSuccess:()=>{e.invalidateQueries({queryKey:["config"]})}})}function vt(){const e=CA(A=>A.isExpanded);return PA({queryKey:["git","status"],queryFn:()=>T.getGitStatus(),refetchInterval:e?5e3:!1,retry:1,staleTime:3e3})}function Xa(e,A=!1){return PA({queryKey:["git","diff",e,A],queryFn:()=>e?T.getGitDiff(e,A):null,enabled:!!e,retry:1,refetchInterval:!1})}function _a(e){return pA({mutationFn:()=>T.generateCommitMessage(e??void 0)})}function jt(){const e=nA();return pA({mutationFn:A=>T.stageFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function Tg(){const e=nA();return pA({mutationFn:A=>T.unstageFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function $B(){const e=nA();return pA({mutationFn:A=>T.restoreFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function Ao(){const e=nA();return pA({mutationFn:A=>T.deleteFiles(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]})}})}function $a(){const e=nA();return pA({mutationFn:A=>T.commitChanges(A),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]}),e.invalidateQueries({queryKey:["git","branch"]})}})}function Ar(){const e=nA();return pA({mutationFn:()=>T.pushCommits(),onSuccess:()=>{e.invalidateQueries({queryKey:["git","status"]}),e.invalidateQueries({queryKey:["git","branch"]})}})}const eo=["image/png","image/jpeg","image/gif","image/webp"],to=["application/pdf"],go=["text/plain","text/markdown","text/x-markdown"],Qo=[".txt",".md",".markdown"],er=[...eo,...to,...go];function tr(){return`file-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function gr(e){if(eo.includes(e.type))return"image";if(to.includes(e.type))return"pdf";if(go.includes(e.type))return"text";const A=e.name.toLowerCase().slice(e.name.lastIndexOf("."));return Qo.includes(A)?"text":null}function it(e){if(er.includes(e.type))return!0;const A=e.name.toLowerCase().slice(e.name.lastIndexOf("."));return Qo.includes(A)}async function bQ(e){return new Promise((A,g)=>{const Q=new FileReader;Q.onload=()=>{const o=Q.result.split(",")[1];A(o)},Q.onerror=g,Q.readAsDataURL(e)})}async function Qr(e){return new Promise((A,g)=>{const Q=new FileReader;Q.onload=()=>A(Q.result),Q.onerror=g,Q.readAsText(e)})}async function Br(e){return new Promise((A,g)=>{const Q=new FileReader;Q.onload=()=>A(Q.result),Q.onerror=g,Q.readAsDataURL(e)})}function or(e={}){const{maxFiles:A=10,maxSizeMB:g=10,pageWide:Q=!0}=e,[B,o]=u.useState([]),[s,E]=u.useState(!1),[i,C]=u.useState(null),a=g*1024*1024,I=u.useCallback(x=>it(x)?x.size>a?`File too large: ${(x.size/1024/1024).toFixed(1)}MB. Max: ${g}MB`:null:`Unsupported file type: ${x.type||x.name}. Supported: images, PDF, markdown, text`,[a,g]),l=u.useCallback(async x=>{C(null);const f=Array.from(x),M=A-B.length;if(M<=0){C(`Maximum ${A} files allowed`);return}const w=f.slice(0,M),G=[];for(const p of w){const U=I(p);if(U){C(U);continue}const k=gr(p);if(k)try{let J,S,Y,q=p.type;if(k==="image")[J,S]=await Promise.all([Br(p),bQ(p)]);else if(k==="pdf")S=await bQ(p),q="application/pdf";else if(Y=await Qr(p),S=Y,!q){const R=p.name.toLowerCase();q=R.endsWith(".md")||R.endsWith(".markdown")?"text/markdown":"text/plain"}G.push({id:tr(),file:p,type:k,name:p.name,preview:J,data:S,mediaType:q,textContent:Y})}catch{C(`Failed to process file: ${p.name}`)}}G.length>0&&o(p=>[...p,...G])},[B.length,A,I]),r=u.useCallback(x=>{o(f=>f.filter(M=>M.id!==x)),C(null)},[]),n=u.useCallback(()=>{o([]),C(null)},[]),d=u.useCallback(x=>{x.preventDefault(),x.stopPropagation(),x.dataTransfer.types.includes("Files")&&E(!0)},[]),c=u.useCallback(x=>{x.preventDefault(),x.stopPropagation();const f=x.currentTarget.getBoundingClientRect(),M=x.clientX,w=x.clientY;(M<f.left||M>f.right||w<f.top||w>f.bottom)&&E(!1)},[]),D=u.useCallback(x=>{x.preventDefault(),x.stopPropagation()},[]),N=u.useCallback(x=>{x.preventDefault(),x.stopPropagation(),E(!1);const f=x.dataTransfer.files;if(f.length>0){const M=Array.from(f).filter(it);M.length>0&&l(M)}},[l]),h=u.useCallback(x=>{const f=x.clipboardData?.items;if(!f)return;const M=[];for(const w of Array.from(f))if(w.kind==="file"){const G=w.getAsFile();G&&it(G)&&M.push(G)}M.length>0&&(x.preventDefault(),l(M))},[l]);u.useEffect(()=>{if(!Q)return;let x=0;const f=p=>{p.preventDefault(),p.dataTransfer?.types.includes("Files")&&(x++,x===1&&E(!0))},M=p=>{p.preventDefault(),x--,x===0&&E(!1)},w=p=>{p.preventDefault()},G=p=>{p.preventDefault(),x=0,E(!1);const U=p.dataTransfer?.files;if(U&&U.length>0){const k=Array.from(U).filter(it);k.length>0&&l(k)}};return document.addEventListener("dragenter",f),document.addEventListener("dragleave",M),document.addEventListener("dragover",w),document.addEventListener("drop",G),()=>{document.removeEventListener("dragenter",f),document.removeEventListener("dragleave",M),document.removeEventListener("dragover",w),document.removeEventListener("drop",G)}},[Q,l]);const m=B.filter(x=>x.type==="image"),y=B.filter(x=>x.type==="pdf"||x.type==="text");return{files:B,images:m,documents:y,isDragging:s,error:i,addFiles:l,removeFile:r,clearFiles:n,handleDragEnter:d,handleDragLeave:c,handleDragOver:D,handleDrop:N,handlePaste:h}}const ug=UA((e,A)=>({pendingRestoreText:null,setPendingRestoreText:g=>e({pendingRestoreText:g}),consumeRestoreText:()=>{const g=A().pendingRestoreText;return e({pendingRestoreText:null}),g}})),Dt=UA((e,A)=>({pendingContexts:new Map,addContext:(g,Q)=>{e(B=>{const o=new Map(B.pendingContexts),s=o.get(g)||[];return s.some(E=>E.id===Q.id)||o.set(g,[...s,Q]),{pendingContexts:o}})},removeContext:(g,Q)=>{e(B=>{const o=new Map(B.pendingContexts),s=o.get(g)||[];return o.set(g,s.filter(E=>E.id!==Q)),{pendingContexts:o}})},getContexts:g=>A().pendingContexts.get(g)||[],clearContexts:g=>{e(Q=>{const B=new Map(Q.pendingContexts);return B.delete(g),{pendingContexts:B}})},consumeContexts:g=>{const Q=A().getContexts(g);return A().clearContexts(g),Q}})),sr=/<research-context\s+from="([^"]+)"\s+label="([^"]+)"[^>]*>([\s\S]*?)<\/research-context>/g;function Er(e){const A=[];let g=e;const Q=new RegExp(sr);let B=Q.exec(e);for(;B!==null;){const[o,s,E,i]=B;A.push({id:s,from:s,label:E,content:i.trim()}),g=g.replace(o,""),B=Q.exec(e)}return g=g.trim(),{researchContexts:A,cleanContent:g}}function Cr(e){return e.length===0?"":e.map(A=>A.content).join(`
81
81
 
82
- `)}function Ht(e){const A=sA(C=>C.setBalance),g=sA(C=>C.setUsdcBalance),Q=sA(C=>C.setWalletAddress),B=sA(C=>C.setLoading),o=sA(C=>C.balance),s=sA(C=>C.usdcBalance),E=sA(C=>C.network),i=u.useCallback(async()=>{if(e==="setu"){B(!0);try{const[C,a,I]=await Promise.all([T.getSetuBalance(),T.getSetuUsdcBalance(E),T.getSetuWallet()]);C?(A(C.balance),Q(C.walletAddress)):I?.configured&&I.publicKey&&Q(I.publicKey),a&&(g(a.usdcBalance),!C&&a.walletAddress&&Q(a.walletAddress))}catch{}finally{B(!1)}}},[e,E,A,g,Q,B]);return u.useEffect(()=>{e==="setu"&&(o===null||s===null)&&i()},[e,o,s,i]),{fetchBalance:i}}const Bo=u.forwardRef(function({provider:A,model:g,onChange:Q,disabled:B=!1},o){const{data:s,isLoading:E}=Tt(),[i,C]=u.useState(!1),[a,I]=u.useState(""),[l,r]=u.useState(0),n=u.useRef(null),d=u.useRef(null),c=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{C(!0)}}));const D=u.useMemo(()=>{if(!s)return[];const w=[];for(const[G,p]of Object.entries(s))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[s]),N=u.useMemo(()=>new de(D,{keys:[{name:"modelLabel",weight:1},{name:"modelId",weight:.5},{name:"providerLabel",weight:.3}],threshold:.5,ignoreLocation:!0,includeScore:!0,distance:100,minMatchCharLength:1,findAllMatches:!0}),[D]),h=u.useMemo(()=>{if(!s)return{};if(!a.trim())return s;const G=N.search(a).sort((U,k)=>{const J=U.score??1,S=k.score??1;if(Math.abs(J-S)<.001){const Y=U.item.modelLabel.toLowerCase(),q=k.item.modelLabel.toLowerCase(),R=a.toLowerCase(),O=Y.indexOf(R),K=q.indexOf(R);if(O>=0&&K<0)return-1;if(K>=0&&O<0)return 1;if(O>=0&&K>=0)return O-K}return J-S}),p={};for(const U of G){const k=U.item;p[k.providerKey]||(p[k.providerKey]={label:k.providerLabel,models:[]}),p[k.providerKey].models.find(S=>S.id===k.modelId)||p[k.providerKey].models.push({id:k.modelId,label:k.modelLabel,toolCall:k.toolCall,reasoningText:k.reasoningText})}return p},[s,a,N]),m=u.useMemo(()=>{const w=[];for(const[G,p]of Object.entries(h))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[h]);u.useEffect(()=>{i&&r(0)},[i]),u.useEffect(()=>{i&&l>=0&&l<c.current.length&&c.current[l]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[l,i]),u.useEffect(()=>{const w=p=>{n.current&&!n.current.contains(p.target)&&C(!1)},G=p=>{const U=p.target,k=U.tagName==="INPUT"||U.tagName==="TEXTAREA"||U.isContentEditable;(p.key==="Escape"||p.key==="q"&&!k)&&C(!1)};return i&&(document.addEventListener("mousedown",w),document.addEventListener("keydown",G),setTimeout(()=>d.current?.focus(),0)),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",G)}},[i]);const y=(w,G)=>{Q(w,G),C(!1),I("")},x=w=>{if(m.length!==0){if(w.key==="ArrowDown"||w.ctrlKey&&w.key==="j")w.preventDefault(),r(G=>G<m.length-1?G+1:0);else if(w.key==="ArrowUp"||w.ctrlKey&&w.key==="k")w.preventDefault(),r(G=>G>0?G-1:m.length-1);else if(w.key==="Enter"){w.preventDefault();const G=m[l];G&&y(G.providerKey,G.modelId)}}},f=s?.[A]?.label||A,M=s?.[A]?.models.find(w=>w.id===g)?.label||g;return t.jsxs("div",{ref:n,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&C(!i),disabled:B||E,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsxs("span",{className:"flex items-center gap-2 text-sm truncate",children:[t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]",children:f}),t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]/50",children:"/"}),t.jsx("span",{className:"text-[hsl(var(--foreground))]",children:M})]}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${i?"rotate-180":""}`})]}),i&&!E&&s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:d,type:"text",value:a,onChange:w=>I(w.target.value),onKeyDown:x,placeholder:"Search providers and models...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:Object.keys(h).length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No models found"}):Object.entries(h).map(([w,G])=>t.jsxs("div",{className:"border-b border-[hsl(var(--border))] last:border-0",children:[t.jsx("div",{className:"sticky top-0 px-3 py-2 text-xs font-semibold text-[hsl(var(--muted-foreground))] uppercase tracking-wider bg-[hsl(var(--muted))] z-10",children:G.label}),t.jsx("div",{children:G.models.map(p=>{const U=w===A&&p.id===g,k=m.findIndex(S=>S.providerKey===w&&S.modelId===p.id),J=k===l;return t.jsxs("button",{ref:S=>{k>=0&&(c.current[k]=S)},type:"button",onClick:()=>y(w,p.id),onMouseEnter:()=>r(k),className:`w-full text-left px-4 py-2 text-sm flex items-center justify-between transition-colors ${J?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${U?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:[t.jsx("span",{className:"truncate",children:p.label}),(p.toolCall||p.reasoningText)&&t.jsxs("div",{className:"flex gap-1 ml-2 flex-shrink-0",children:[p.toolCall&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-green-600/20 text-green-400 rounded",children:"Tools"}),p.reasoningText&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-purple-600/20 text-purple-400 rounded",children:"Reasoning"})]})]},p.id)})})]},w))})]})]})}),ir=u.forwardRef(function({agent:A,agents:g,onChange:Q,disabled:B=!1},o){const[s,E]=u.useState(!1),[i,C]=u.useState(""),[a,I]=u.useState(0),l=u.useRef(null),r=u.useRef(null),n=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{E(!0)}}));const d=u.useMemo(()=>new de(g,{threshold:.4,ignoreLocation:!0}),[g]),c=u.useMemo(()=>i.trim()?d.search(i).map(m=>m.item):g,[g,i,d]);u.useEffect(()=>{s&&I(0)},[s]),u.useEffect(()=>{s&&a>=0&&a<n.current.length&&n.current[a]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[a,s]),u.useEffect(()=>{const h=y=>{l.current&&!l.current.contains(y.target)&&E(!1)},m=y=>{const x=y.target,f=x.tagName==="INPUT"||x.tagName==="TEXTAREA"||x.isContentEditable;(y.key==="Escape"||y.key==="q"&&!f)&&E(!1)};return s&&(document.addEventListener("mousedown",h),document.addEventListener("keydown",m),setTimeout(()=>r.current?.focus(),0)),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",m)}},[s]);const D=h=>{Q(h),E(!1),C("")},N=h=>{if(c.length!==0){if(h.key==="ArrowDown"||h.ctrlKey&&h.key==="j")h.preventDefault(),I(m=>m<c.length-1?m+1:0);else if(h.key==="ArrowUp"||h.ctrlKey&&h.key==="k")h.preventDefault(),I(m=>m>0?m-1:c.length-1);else if(h.key==="Enter"){h.preventDefault();const m=c[a];m&&D(m)}}};return t.jsxs("div",{ref:l,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&E(!s),disabled:B,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsx("span",{className:"text-sm text-[hsl(var(--foreground))] truncate",children:A}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${s?"rotate-180":""}`})]}),s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:r,type:"text",value:i,onChange:h=>C(h.target.value),onKeyDown:N,placeholder:"Search agents...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:c.length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No agents found"}):c.map((h,m)=>{const y=h===A,x=m===a;return t.jsx("button",{ref:f=>{n.current[m]=f},type:"button",onClick:()=>D(h),onMouseEnter:()=>I(m),className:`w-full text-left px-4 py-2 text-sm transition-colors ${x?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${y?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:t.jsx("span",{className:"truncate",children:h})},h)})})]})]})});function ar({isOpen:e,onClose:A,initialFocus:g,chatInputRef:Q,agent:B,provider:o,model:s,modelSupportsReasoning:E,onAgentChange:i,onProviderChange:C,onModelChange:a,onModelSelectorChange:I}){const{data:l,isLoading:r}=Yg(),{preferences:n,updatePreferences:d}=ot(),c=u.useRef(null),D=u.useRef(null);u.useEffect(()=>{e&&g&&setTimeout(()=>{g==="agent"?c.current?.openAndFocus():g==="model"&&D.current?.openAndFocus()},100)},[e,g]);const N=()=>{A(),setTimeout(()=>{Q?.current?.focus()},100)},h=(m,y)=>{I?I(m,y):(C(m),a(y))};return t.jsx(qe,{isOpen:e,onClose:N,title:"Configuration",closeOnEscape:!0,closeOnBackdropClick:!0,children:r?t.jsx("div",{className:"text-center text-muted-foreground py-8",children:"Loading configuration..."}):l?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Agent"}),t.jsx(ir,{ref:c,agent:B,agents:l.agents,onChange:i})]}),t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Provider / Model"}),t.jsx(Bo,{ref:D,provider:o,model:s,onChange:h})]}),E&&t.jsxs("div",{className:"flex items-center justify-between py-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-foreground",children:"Extended Thinking"}),t.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable reasoning for deeper analysis"})]}),t.jsx("button",{type:"button",role:"switch","aria-checked":n.reasoningEnabled,onClick:()=>d({reasoningEnabled:!n.reasoningEnabled}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${n.reasoningEnabled?"bg-primary":"bg-muted"}`,children:t.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full transition-transform ${n.reasoningEnabled?"translate-x-6":"translate-x-1"} ${n.reasoningEnabled?"bg-primary-foreground":"bg-foreground"}`})})]})]}):null})}const rr=u.memo(u.forwardRef(function({sessionId:A,userContext:g,onNewSession:Q,onDeleteSession:B},o){const s=XB(A),[E,i]=u.useState(""),[C,a]=u.useState(""),[I,l]=u.useState(""),[r,n]=u.useState(!1),[d,c]=u.useState(null),[D,N]=u.useState(0),h=u.useRef(null),m=Wa(A);Mt(A);const y=_B(A),x=Va(),{data:f}=Tt(),{preferences:M}=ot(),{data:w}=vt(),G=jt(),p=CA(H=>H.openCommitModalForSession),U=CA(H=>H.setActiveSessionId),k=nA(),{images:J,documents:S,isDragging:Y,removeFile:q,clearFiles:R,handlePaste:O}=or(),K=f?.[C]?.models?.find(H=>H.id===I)?.reasoningText,v=f?.[C]?.models?.find(H=>H.id===I)?.vision,V=Dt(H=>H.pendingContexts),_=Dt(H=>H.removeContext),X=Dt(H=>H.consumeContexts),iA=V.get(A)||[],mA=u.useMemo(()=>iA.map(H=>({id:H.id,label:H.label})),[iA]),j=u.useCallback(H=>{_(A,H)},[A,_]),L=f?.[C]?.authType,{fetchBalance:AA}=Ht(C),EA=sA(H=>H.isLoading);u.useEffect(()=>{s&&(i(s.agent),a(s.provider),l(s.model))},[s]),u.useEffect(()=>(U(A),()=>U(null)),[A,U]),u.useEffect(()=>{N(H=>H+1)},[]);const NA=ug(H=>H.pendingRestoreText),DA=ug(H=>H.consumeRestoreText);u.useEffect(()=>{if(NA){const H=DA();H&&h.current?.setValue(H)}},[NA,DA]),u.useImperativeHandle(o,()=>({focus:()=>{h.current?.focus()}}));const yA=u.useCallback(async H=>{try{const oA=X(A),eA=Cr(oA),GA=eA?`${eA}
82
+ `)}function Ht(e){const A=sA(C=>C.setBalance),g=sA(C=>C.setUsdcBalance),Q=sA(C=>C.setWalletAddress),B=sA(C=>C.setLoading),o=sA(C=>C.balance),s=sA(C=>C.usdcBalance),E=sA(C=>C.network),i=u.useCallback(async()=>{if(e==="setu"){B(!0);try{const[C,a,I]=await Promise.all([T.getSetuBalance(),T.getSetuUsdcBalance(E),T.getSetuWallet()]);C?(A(C.balance),Q(C.walletAddress)):I?.configured&&I.publicKey&&Q(I.publicKey),a&&(g(a.usdcBalance),!C&&a.walletAddress&&Q(a.walletAddress))}catch{}finally{B(!1)}}},[e,E,A,g,Q,B]);return u.useEffect(()=>{e==="setu"&&(o===null||s===null)&&i()},[e,o,s,i]),{fetchBalance:i}}const Bo=u.forwardRef(function({provider:A,model:g,onChange:Q,disabled:B=!1},o){const{data:s,isLoading:E}=Tt(),[i,C]=u.useState(!1),[a,I]=u.useState(""),[l,r]=u.useState(0),n=u.useRef(null),d=u.useRef(null),c=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{C(!0)}}));const D=u.useMemo(()=>{if(!s)return[];const w=[];for(const[G,p]of Object.entries(s))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[s]),N=u.useMemo(()=>new de(D,{keys:[{name:"modelLabel",weight:2},{name:"modelId",weight:1},{name:"providerLabel",weight:.5}],threshold:.3,ignoreLocation:!0,includeScore:!0,distance:100,minMatchCharLength:1}),[D]),h=u.useMemo(()=>{if(!s)return{};if(!a.trim())return s;const G=N.search(a).sort((U,k)=>{const J=U.score??1,S=k.score??1;if(Math.abs(J-S)<.001){const Y=U.item.modelLabel.toLowerCase(),q=k.item.modelLabel.toLowerCase(),R=a.toLowerCase(),O=Y.indexOf(R),K=q.indexOf(R);if(O>=0&&K<0)return-1;if(K>=0&&O<0)return 1;if(O>=0&&K>=0)return O-K}return J-S}),p={};for(const U of G){const k=U.item;p[k.providerKey]||(p[k.providerKey]={label:k.providerLabel,models:[]}),p[k.providerKey].models.find(S=>S.id===k.modelId)||p[k.providerKey].models.push({id:k.modelId,label:k.modelLabel,toolCall:k.toolCall,reasoningText:k.reasoningText})}return p},[s,a,N]),m=u.useMemo(()=>{const w=[];for(const[G,p]of Object.entries(h))for(const U of p.models)w.push({providerKey:G,providerLabel:p.label,modelId:U.id,modelLabel:U.label,toolCall:U.toolCall,reasoningText:U.reasoningText});return w},[h]);u.useEffect(()=>{i&&r(0)},[i]),u.useEffect(()=>{i&&l>=0&&l<c.current.length&&c.current[l]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[l,i]),u.useEffect(()=>{const w=p=>{n.current&&!n.current.contains(p.target)&&C(!1)},G=p=>{const U=p.target,k=U.tagName==="INPUT"||U.tagName==="TEXTAREA"||U.isContentEditable;(p.key==="Escape"||p.key==="q"&&!k)&&C(!1)};return i&&(document.addEventListener("mousedown",w),document.addEventListener("keydown",G),setTimeout(()=>d.current?.focus(),0)),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",G)}},[i]);const y=(w,G)=>{Q(w,G),C(!1),I("")},x=w=>{if(m.length!==0){if(w.key==="ArrowDown"||w.ctrlKey&&w.key==="j")w.preventDefault(),r(G=>G<m.length-1?G+1:0);else if(w.key==="ArrowUp"||w.ctrlKey&&w.key==="k")w.preventDefault(),r(G=>G>0?G-1:m.length-1);else if(w.key==="Enter"){w.preventDefault();const G=m[l];G&&y(G.providerKey,G.modelId)}}},f=s?.[A]?.label||A,M=s?.[A]?.models.find(w=>w.id===g)?.label||g;return t.jsxs("div",{ref:n,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&C(!i),disabled:B||E,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsxs("span",{className:"flex items-center gap-2 text-sm truncate",children:[t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]",children:f}),t.jsx("span",{className:"text-[hsl(var(--muted-foreground))]/50",children:"/"}),t.jsx("span",{className:"text-[hsl(var(--foreground))]",children:M})]}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${i?"rotate-180":""}`})]}),i&&!E&&s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:d,type:"text",value:a,onChange:w=>I(w.target.value),onKeyDown:x,placeholder:"Search providers and models...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:Object.keys(h).length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No models found"}):Object.entries(h).map(([w,G])=>t.jsxs("div",{className:"border-b border-[hsl(var(--border))] last:border-0",children:[t.jsx("div",{className:"sticky top-0 px-3 py-2 text-xs font-semibold text-[hsl(var(--muted-foreground))] uppercase tracking-wider bg-[hsl(var(--muted))] z-10",children:G.label}),t.jsx("div",{children:G.models.map(p=>{const U=w===A&&p.id===g,k=m.findIndex(S=>S.providerKey===w&&S.modelId===p.id),J=k===l;return t.jsxs("button",{ref:S=>{k>=0&&(c.current[k]=S)},type:"button",onClick:()=>y(w,p.id),onMouseEnter:()=>r(k),className:`w-full text-left px-4 py-2 text-sm flex items-center justify-between transition-colors ${J?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${U?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:[t.jsx("span",{className:"truncate",children:p.label}),(p.toolCall||p.reasoningText)&&t.jsxs("div",{className:"flex gap-1 ml-2 flex-shrink-0",children:[p.toolCall&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-green-600/20 text-green-400 rounded",children:"Tools"}),p.reasoningText&&t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-purple-600/20 text-purple-400 rounded",children:"Reasoning"})]})]},p.id)})})]},w))})]})]})}),ir=u.forwardRef(function({agent:A,agents:g,onChange:Q,disabled:B=!1},o){const[s,E]=u.useState(!1),[i,C]=u.useState(""),[a,I]=u.useState(0),l=u.useRef(null),r=u.useRef(null),n=u.useRef([]);u.useImperativeHandle(o,()=>({openAndFocus:()=>{E(!0)}}));const d=u.useMemo(()=>new de(g,{threshold:.4,ignoreLocation:!0}),[g]),c=u.useMemo(()=>i.trim()?d.search(i).map(m=>m.item):g,[g,i,d]);u.useEffect(()=>{s&&I(0)},[s]),u.useEffect(()=>{s&&a>=0&&a<n.current.length&&n.current[a]?.scrollIntoView({block:"nearest",behavior:"smooth"})},[a,s]),u.useEffect(()=>{const h=y=>{l.current&&!l.current.contains(y.target)&&E(!1)},m=y=>{const x=y.target,f=x.tagName==="INPUT"||x.tagName==="TEXTAREA"||x.isContentEditable;(y.key==="Escape"||y.key==="q"&&!f)&&E(!1)};return s&&(document.addEventListener("mousedown",h),document.addEventListener("keydown",m),setTimeout(()=>r.current?.focus(),0)),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",m)}},[s]);const D=h=>{Q(h),E(!1),C("")},N=h=>{if(c.length!==0){if(h.key==="ArrowDown"||h.ctrlKey&&h.key==="j")h.preventDefault(),I(m=>m<c.length-1?m+1:0);else if(h.key==="ArrowUp"||h.ctrlKey&&h.key==="k")h.preventDefault(),I(m=>m>0?m-1:c.length-1);else if(h.key==="Enter"){h.preventDefault();const m=c[a];m&&D(m)}}};return t.jsxs("div",{ref:l,className:"relative w-full",children:[t.jsxs("button",{type:"button",onClick:()=>!B&&E(!s),disabled:B,className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded-md hover:bg-[hsl(var(--accent))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[t.jsx("span",{className:"text-sm text-[hsl(var(--foreground))] truncate",children:A}),t.jsx(ZA,{className:`w-4 h-4 text-[hsl(var(--muted-foreground))] transition-transform ${s?"rotate-180":""}`})]}),s&&t.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-[hsl(var(--popover))] border border-[hsl(var(--border))] rounded-md shadow-lg max-h-80 overflow-hidden flex flex-col",children:[t.jsx("div",{className:"p-2 border-b border-[hsl(var(--border))]",children:t.jsxs("div",{className:"relative",children:[t.jsx($e,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[hsl(var(--muted-foreground))]"}),t.jsx("input",{ref:r,type:"text",value:i,onChange:h=>C(h.target.value),onKeyDown:N,placeholder:"Search agents...",className:"w-full pl-9 pr-3 py-2 bg-[hsl(var(--secondary))] border border-[hsl(var(--border))] rounded text-sm text-[hsl(var(--foreground))] placeholder-[hsl(var(--muted-foreground))] focus:outline-none focus:ring-2 focus:ring-[hsl(var(--ring))]"})]})}),t.jsx("div",{className:"overflow-y-auto",children:c.length===0?t.jsx("div",{className:"p-4 text-center text-[hsl(var(--muted-foreground))] text-sm",children:"No agents found"}):c.map((h,m)=>{const y=h===A,x=m===a;return t.jsx("button",{ref:f=>{n.current[m]=f},type:"button",onClick:()=>D(h),onMouseEnter:()=>I(m),className:`w-full text-left px-4 py-2 text-sm transition-colors ${x?"bg-[hsl(var(--accent))]":"hover:bg-[hsl(var(--accent))]"} ${y?"text-[hsl(var(--accent-foreground))] font-medium":"text-[hsl(var(--foreground))]"}`,children:t.jsx("span",{className:"truncate",children:h})},h)})})]})]})});function ar({isOpen:e,onClose:A,initialFocus:g,chatInputRef:Q,agent:B,provider:o,model:s,modelSupportsReasoning:E,onAgentChange:i,onProviderChange:C,onModelChange:a,onModelSelectorChange:I}){const{data:l,isLoading:r}=Yg(),{preferences:n,updatePreferences:d}=ot(),c=u.useRef(null),D=u.useRef(null);u.useEffect(()=>{e&&g&&setTimeout(()=>{g==="agent"?c.current?.openAndFocus():g==="model"&&D.current?.openAndFocus()},100)},[e,g]);const N=()=>{A(),setTimeout(()=>{Q?.current?.focus()},100)},h=(m,y)=>{I?I(m,y):(C(m),a(y))};return t.jsx(qe,{isOpen:e,onClose:N,title:"Configuration",closeOnEscape:!0,closeOnBackdropClick:!0,children:r?t.jsx("div",{className:"text-center text-muted-foreground py-8",children:"Loading configuration..."}):l?t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Agent"}),t.jsx(ir,{ref:c,agent:B,agents:l.agents,onChange:i})]}),t.jsxs("div",{children:[t.jsx("div",{className:"block text-sm font-medium text-foreground mb-2",children:"Provider / Model"}),t.jsx(Bo,{ref:D,provider:o,model:s,onChange:h})]}),E&&t.jsxs("div",{className:"flex items-center justify-between py-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-foreground",children:"Extended Thinking"}),t.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable reasoning for deeper analysis"})]}),t.jsx("button",{type:"button",role:"switch","aria-checked":n.reasoningEnabled,onClick:()=>d({reasoningEnabled:!n.reasoningEnabled}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${n.reasoningEnabled?"bg-primary":"bg-muted"}`,children:t.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full transition-transform ${n.reasoningEnabled?"translate-x-6":"translate-x-1"} ${n.reasoningEnabled?"bg-primary-foreground":"bg-foreground"}`})})]})]}):null})}const rr=u.memo(u.forwardRef(function({sessionId:A,userContext:g,onNewSession:Q,onDeleteSession:B},o){const s=XB(A),[E,i]=u.useState(""),[C,a]=u.useState(""),[I,l]=u.useState(""),[r,n]=u.useState(!1),[d,c]=u.useState(null),[D,N]=u.useState(0),h=u.useRef(null),m=Wa(A);Mt(A);const y=_B(A),x=Va(),{data:f}=Tt(),{preferences:M}=ot(),{data:w}=vt(),G=jt(),p=CA(H=>H.openCommitModalForSession),U=CA(H=>H.setActiveSessionId),k=nA(),{images:J,documents:S,isDragging:Y,removeFile:q,clearFiles:R,handlePaste:O}=or(),K=f?.[C]?.models?.find(H=>H.id===I)?.reasoningText,v=f?.[C]?.models?.find(H=>H.id===I)?.vision,V=Dt(H=>H.pendingContexts),_=Dt(H=>H.removeContext),X=Dt(H=>H.consumeContexts),iA=V.get(A)||[],mA=u.useMemo(()=>iA.map(H=>({id:H.id,label:H.label})),[iA]),j=u.useCallback(H=>{_(A,H)},[A,_]),L=f?.[C]?.authType,{fetchBalance:AA}=Ht(C),EA=sA(H=>H.isLoading);u.useEffect(()=>{s&&(i(s.agent),a(s.provider),l(s.model))},[s]),u.useEffect(()=>(U(A),()=>U(null)),[A,U]),u.useEffect(()=>{N(H=>H+1)},[]);const NA=ug(H=>H.pendingRestoreText),DA=ug(H=>H.consumeRestoreText);u.useEffect(()=>{if(NA){const H=DA();H&&h.current?.setValue(H)}},[NA,DA]),u.useImperativeHandle(o,()=>({focus:()=>{h.current?.focus()}}));const yA=u.useCallback(async H=>{try{const oA=X(A),eA=Cr(oA),GA=eA?`${eA}
83
83
 
84
84
  ${H}`:H,ee=J.length>0?J.map(OA=>({data:OA.data,mediaType:OA.mediaType})):void 0,Ge=S.length>0?S.map(OA=>({type:OA.type,name:OA.name,data:OA.data,mediaType:OA.mediaType,textContent:OA.textContent})):void 0;await m.mutateAsync({content:GA,images:ee,files:Ge,agent:E||void 0,provider:C||void 0,model:I||void 0,userContext:g||void 0,reasoningText:K&&M.reasoningEnabled?!0:void 0}),R()}catch(oA){console.error("Failed to send message:",oA)}},[m,S,J,R,E,C,I,g,K,M.reasoningEnabled,A,X]),ue=u.useCallback(()=>{n(H=>!H)},[]),Te=u.useCallback(()=>{n(!1),c(null)},[]),oe=u.useCallback(async H=>{if(H==="models")c("model"),n(!0);else if(H==="agents")c("agent"),n(!0);else if(H==="new")Q?.();else if(H==="stage"){const oA=w?.unstaged?.map(ee=>ee.path)??[],eA=w?.untracked?.map(ee=>ee.path)??[],GA=[...oA,...eA];GA.length>0&&G.mutate(GA)}else if(H==="commit")p(A);else if(H==="compact")yA("/compact");else if(H==="delete")x.mutate(A,{onSuccess:()=>{B?.()}});else if(H==="share"){const oA=tA.loading("Sharing session...");try{const eA=await T.shareSession(A);eA.shared&&(tA.successWithAction(eA.message==="Already shared"?"Already shared":"Session shared!",{label:"Open",href:eA.url}),k.invalidateQueries({queryKey:["share-status",A]}))}catch(eA){tA.error(eA instanceof Error?eA.message:"Failed to share")}finally{_A.getState().removeToast(oA)}}else if(H==="sync"){const oA=tA.loading("Syncing session...");try{const eA=await T.syncSession(A);if(eA.synced){const GA=eA.newMessages>0?`Synced ${eA.newMessages} new messages`:"Already synced";tA.successWithAction(GA,{label:"Open",href:eA.url}),k.invalidateQueries({queryKey:["share-status",A]})}}catch(eA){tA.error(eA instanceof Error?eA.message:"Failed to sync")}finally{_A.getState().removeToast(oA)}}},[Q,w,G,p,yA,x,A,B,k]),Ie=u.useCallback(async H=>{i(H);try{await y.mutateAsync({agent:H})}catch(oA){console.error("Failed to update agent:",oA)}},[y]),KA=u.useCallback(async(H,oA)=>{a(H),l(oA);try{await y.mutateAsync({provider:H,model:oA})}catch(eA){console.error("Failed to update model:",eA)}},[y]),he=u.useCallback(async H=>{if(a(H),I)try{await y.mutateAsync({provider:H,model:I})}catch(oA){console.error("Failed to update provider:",oA)}},[I,y]),zA=u.useCallback(async H=>{l(H);try{await y.mutateAsync({provider:C,model:H})}catch(oA){console.error("Failed to update model:",oA)}},[C,y]),De=u.useCallback(async H=>{const oA=H?"plan":"build";i(oA);try{await y.mutateAsync({agent:oA})}catch(eA){console.error("Failed to switch agent:",eA)}},[y]);return t.jsxs(t.Fragment,{children:[t.jsx(ar,{isOpen:r,onClose:Te,initialFocus:d,chatInputRef:h,agent:E,provider:C,model:I,modelSupportsReasoning:K,onAgentChange:Ie,onProviderChange:he,onModelChange:zA,onModelSelectorChange:KA}),t.jsx(Pa,{ref:h,onSend:yA,onCommand:oe,disabled:m.isPending,onConfigClick:ue,onPlanModeToggle:De,isPlanMode:E==="plan",reasoningEnabled:K&&M.reasoningEnabled,sessionId:A,images:J,documents:S,onFileRemove:q,isDragging:Y,onPaste:O,visionEnabled:v,modelName:I,providerName:C,authType:L,researchContexts:mA,onResearchContextRemove:j,onRefreshBalance:C==="setu"?AA:void 0,isBalanceLoading:EA,onModelInfoClick:()=>{c("model"),n(!0)}},D)]})}));function Ir({sessionId:e,onStop:A,disabled:g}){const[Q,B]=u.useState(!1),o=async()=>{if(!Q){B(!0);try{await T.abortSession(e),A?.()}catch(s){console.error("Failed to abort stream:",s)}finally{setTimeout(()=>B(!1),1e3)}}};return t.jsxs("button",{type:"button",onClick:o,disabled:g||Q,className:"flex items-center gap-1.5 text-sm text-destructive hover:text-destructive/80 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",title:"Stop generation",children:[t.jsx(zQ,{className:"w-4 h-4"}),t.jsx("span",{className:"font-medium",children:Q?"Stopping...":"Stop"})]})}function nr(e){const A=e.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"text",svelte:"svelte"}[A||""]||"javascript"}function lr(e){const A=e.split(`
85
85
  `),g=[];let Q=0,B=0,o=!1,s="";for(const E of A){if(E.startsWith("*** Update File:")||E.startsWith("*** Add File:")){const C=E.match(/\*\*\* (?:Update|Add) File: (.+)/);C&&(s=C[1]),o=!0,B=1,Q=1}if(E.startsWith("+++")||E.startsWith("*** Update File:")){const C=E.match(/\+\+\+ b\/(.+)/)||E.match(/\*\*\* Update File: (.+)/);C&&(s=C[1])}const i=E.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(i){Q=Number.parseInt(i[1],10),B=Number.parseInt(i[2],10),o=!0,g.push({content:E,codeContent:E,type:"header"});continue}if(E.startsWith("@@")&&!E.match(/^@@ -\d+/)){o=!0,g.push({content:E,codeContent:E,type:"header"});continue}if(E.startsWith("***")||E.startsWith("diff ")||E.startsWith("index ")||E.startsWith("---")||E.startsWith("+++")){g.push({content:E,codeContent:E,type:"meta"});continue}o?E.startsWith("+")?g.push({content:E,codeContent:E.slice(1),type:"add",newLineNum:B++}):E.startsWith("-")?g.push({content:E,codeContent:E.slice(1),type:"remove",oldLineNum:Q++}):E.startsWith(" ")||E===""?g.push({content:E,codeContent:E.startsWith(" ")?E.slice(1):E,type:"context",oldLineNum:Q++,newLineNum:B++}):g.push({content:E,codeContent:E,type:"context"}):g.push({content:E,codeContent:E,type:"meta"})}return{lines:g,filePath:s}}function Re({patch:e}){const{lines:A,filePath:g}=lr(e),Q=nr(g),B=document?.documentElement.classList.contains("dark")?ae:re;return t.jsx("div",{className:"bg-card/60 border border-border rounded-lg overflow-hidden max-h-96 max-w-full",children:t.jsx("div",{className:"overflow-x-auto overflow-y-auto max-h-96 text-xs font-mono",children:A.map((o,s)=>{const E=`line-${s}-${o.content.slice(0,20)}`;if(o.type==="meta"||o.type==="header")return t.jsx("div",{className:`px-3 py-0.5 whitespace-pre-wrap break-all ${o.type==="header"?"text-muted-foreground/80 bg-muted/20":"text-muted-foreground/80"}`,children:o.content},E);let i="",C="";switch(o.type){case"add":i="text-emerald-700 dark:text-emerald-300",C="bg-emerald-500/10";break;case"remove":i="text-red-600 dark:text-red-300",C="bg-red-500/10";break;default:i="text-foreground/80"}let a=o.content;return o.codeContent.trim()&&Q!=="text"&&(a=t.jsx(jA,{language:Q,style:B,customStyle:{margin:0,padding:0,background:"transparent",display:"inline",fontSize:"inherit",lineHeight:"inherit"},codeTagProps:{style:{fontFamily:"inherit",background:"transparent"}},PreTag:"span",children:o.codeContent}),o.type==="add"?a=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:"+"}),a]}):o.type==="remove"?a=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:"-"}),a]}):o.type==="context"&&(a=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"select-none",children:" "}),a]}))),t.jsxs("div",{className:`flex ${C}`,children:[t.jsx("div",{className:"px-2 py-0.5 text-right text-muted-foreground/40 select-none w-12 flex-shrink-0",children:o.oldLineNum||""}),t.jsx("div",{className:"px-2 py-0.5 text-right text-muted-foreground/40 select-none w-12 flex-shrink-0 border-r border-border/50",children:o.newLineNum||""}),t.jsx("div",{className:`px-3 py-0.5 flex-1 min-w-0 whitespace-pre-wrap break-all ${i}`,children:a})]},E)})})})}function cr(e){const A=e.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"text",svelte:"svelte"}[A||""]||"javascript"}function dr(e,A){if(!A)return null;const Q={read:["path"],write:["path"],edit:["path"],apply_patch:["path"],glob:["pattern"],grep:["query","pattern"],ripgrep:["query","pattern"],bash:["cmd","command"],terminal:["command"],git_commit:["message"],git_diff:["file"],tree:["path"],ls:["path"],web_search:["query","url"],skill:["name"]}[e];if(!Q){for(const[B,o]of Object.entries(A))if(typeof o=="string"&&o.length>0&&o.length<200)return{key:B,value:o};return null}for(const B of Q){const o=A[B];if(typeof o=="string"&&o.length>0)return{key:B,value:o}}return null}function ur(e){if(!e)return null;const A=e.cmd??e.command;return typeof A=="string"&&A.length>0?A:null}const hr=u.memo(function({toolName:A,args:g,pendingApproval:Q,onApprove:B,onReject:o}){const[s,E]=u.useState(!1),i=A.replace(/_/g," "),C=dr(A,g),I=(A==="bash"?ur(g):null)||C?.value,l=typeof g?.path=="string"?g.path:"",r=cr(l),n=document?.documentElement.classList.contains("dark")?ae:re,d=()=>{E(!0),B(Q.callId)},c=()=>{E(!0),o(Q.callId)},D=()=>{if(A==="apply_patch"&&g?.patch)return t.jsx("div",{className:"ml-6 max-w-full overflow-hidden",children:t.jsx(Re,{patch:String(g.patch)})});if(A==="write"&&g?.content){const N=String(g.content);return t.jsx("div",{className:"ml-6 max-w-full overflow-hidden",children:t.jsx("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-lg overflow-hidden max-h-96",children:t.jsx("div",{className:"overflow-x-auto overflow-y-auto max-h-96 text-xs",children:t.jsx(jA,{language:r,style:n,customStyle:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"inherit"},showLineNumbers:!0,lineNumberStyle:{minWidth:"2.5em",paddingRight:"1em",color:"var(--muted-foreground)",opacity:.4,userSelect:"none"},children:N})})})})}if(A==="bash"&&g?.cmd){const N=String(g.cmd);return t.jsx("div",{className:"ml-6 max-w-full overflow-hidden",children:t.jsx("div",{className:"bg-card/60 border border-border rounded-lg overflow-hidden",children:t.jsx("div",{className:"overflow-x-auto text-xs",children:t.jsx(jA,{language:"bash",style:n,customStyle:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"inherit"},children:N})})})})}return null};return t.jsxs("div",{className:"flex flex-col gap-2 py-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx(XQ,{className:"h-4 w-4 text-amber-500 flex-shrink-0"}),t.jsx("span",{className:"font-medium text-foreground text-sm",children:i}),I&&A!=="bash"&&t.jsx("code",{className:"text-xs font-mono text-foreground/80 bg-muted/50 px-1.5 py-0.5 rounded truncate max-w-xs",children:I}),t.jsx("span",{className:"text-amber-600 dark:text-amber-400 font-medium text-sm",children:"requires approval"})]}),D(),t.jsxs("div",{className:"flex items-center gap-2 ml-6",children:[t.jsxs("button",{type:"button",onClick:c,disabled:s,title:"Reject (N or Esc)",className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded border border-border bg-background hover:bg-muted transition-colors disabled:opacity-50",children:[t.jsx(MA,{className:"w-3 h-3"}),"Reject",t.jsx("kbd",{className:"ml-1 text-[10px] text-muted-foreground opacity-70",children:"N"})]}),t.jsxs("button",{type:"button",onClick:d,disabled:s,title:"Approve (Y)",className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded bg-amber-600 text-white hover:bg-amber-700 transition-colors disabled:opacity-50",children:[t.jsx(XA,{className:"w-3 h-3"}),s?"Approving...":"Approve",!s&&t.jsx("kbd",{className:"ml-1 text-[10px] opacity-70",children:"Y"})]})]})]})});function JA(e){return e?e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`:""}function Oe(e){if(!e||typeof e!="object")return!1;const A=e;return A.ok===!1||"error"in A||A.success===!1}function Ye(e){if(!e||typeof e!="object")return null;const A=e,g=["error","stderr","message","detail","details","reason"];for(const Q of g){const B=A[Q];if(typeof B=="string"){const o=B.trim();if(o.length)return o}}return null}function qA({error:e,stack:A,showStack:g=!1}){return t.jsx("div",{className:"mt-2 ml-5 p-3 bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded text-sm",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Be,{className:"h-4 w-4 flex-shrink-0 text-red-600 dark:text-red-400 mt-0.5"}),t.jsxs("div",{className:"flex-1 space-y-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:"Tool Error:"}),t.jsx("div",{className:"mt-1 text-red-900 dark:text-red-200 whitespace-pre-wrap",children:e})]}),g&&A&&t.jsxs("details",{className:"mt-2",children:[t.jsx("summary",{className:"cursor-pointer text-xs text-red-700 dark:text-red-300 hover:text-red-600 dark:hover:text-red-200",children:"View stack trace"}),t.jsx("pre",{className:"mt-2 p-2 bg-red-100/50 dark:bg-red-900/20 rounded text-xs overflow-x-auto text-red-800 dark:text-red-300",children:A})]})]})]})})}function Dr(e){const A=e.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",css:"css",scss:"scss",md:"markdown",txt:"text"}[A||""]||"text"}function wr(e){if(!e)return;const A=e.match(/@(\d+)-(\d+)/);if(A)return Number.parseInt(A[1],10)}function pr({contentJson:e,toolDurationMs:A,isExpanded:g,onToggle:Q,compact:B}){const o=e.result||{},s=e.args||{},E=typeof o=="object"&&"ok"in o&&o.ok===!1,i=E&&"error"in o&&typeof o.error=="string"?o.error:null,C=E&&"stack"in o&&typeof o.stack=="string"?o.stack:void 0,a=String(o.path||s.path||""),I=String(o.content||""),l=o.lineRange,r=I.split(`
@@ -18,7 +18,7 @@
18
18
  .app-loader-spinner{width:24px;height:24px;border:2px solid hsl(240,5%,25%);border-top-color:hsl(240,5%,65%);border-radius:50%;animation:spin .6s linear infinite}
19
19
  @keyframes spin{to{transform:rotate(360deg)}}
20
20
  </style>
21
- <script type="module" crossorigin src="/assets/index-4CCsfDpp.js"></script>
21
+ <script type="module" crossorigin src="/assets/index-DvMKuo32.js"></script>
22
22
  <link rel="modulepreload" crossorigin href="/assets/react-C7bPzU82.js">
23
23
  <link rel="modulepreload" crossorigin href="/assets/router-DAZla045.js">
24
24
  <link rel="modulepreload" crossorigin href="/assets/icons-CauB6tyl.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ottocode/web-ui",
3
- "version": "0.1.176",
3
+ "version": "0.1.177",
4
4
  "description": "Embeddable web UI for ottocode - pre-built static assets",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",