@townco/gui-template 0.1.19 → 0.1.20

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.
@@ -0,0 +1,10 @@
1
+ import{r as i,j as t,P as Yt,e as Zt,f as es,M as ts,h as ss,a as ns}from"./react-DWDN8s0r.js";import{L as H,M as T,N as I,O as h,P as Te,Q as M,R as E,S as D,T as _,U as os,W as G,X as te,Y as rs,Z as as,$ as is,a0 as ls,a1 as W,a2 as cs,a3 as be}from"./vendor-BxtqxsLB.js";import{P as ds,a as us}from"./acp-sdk-BiGbXeF1.js";import{S as X,L as ke,T as Ie,C as Ee,R as ps,O as Re,P as fs,a as Me,b as ms,c as Ue,D as Ae,d as De,e as _e,f as gs,g as Le,I as Pe,h as ze,i as Oe,j as Fe,k as He,l as $e,m as Be,n as We,o as hs,p as Ve,q as qe,r as xs,s as Qe,V as bs,t as Ke,u as Ge,v as ys,w as ws,x as Xe}from"./radix-C1pEulHa.js";import{C as Je,S as vs,P as Ns,M as js,A as Cs,a as Ye,F as Ze,D as et,X as Ss,b as tt,c as st,d as ue,W as Ts,L as nt,e as ks,f as pe,g as Is,h as Es,i as ot,j as ye,k as Rs,l as Ms}from"./icons-B7gv8oe5.js";import{r as Us}from"./markdown-DP5OEpQP.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&o(u)}).observe(document,{childList:!0,subtree:!0});function n(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function o(a){if(a.ep)return;a.ep=!0;const l=n(a);fetch(a.href,l)}})();const le=typeof process<"u"&&process.versions?.node;let As,Ds=0;const _s=new Set;function Ls(s){for(const e of _s)e(s)}const we={trace:0,debug:1,info:2,warn:3,error:4,fatal:5};class Ps{service;minLevel;logFilePath;logsDir;writeQueue=[];isWriting=!1;constructor(e,n="debug"){this.service=e,this.minLevel=n,typeof process<"u"&&(this.minLevel="info")}setupFileLogging(){}async writeToFile(e){if(!(!this.logFilePath||!le)&&(this.writeQueue.push(e),!this.isWriting)){for(this.isWriting=!0;this.writeQueue.length>0;){const o=`${this.writeQueue.splice(0,this.writeQueue.length).join(`
2
+ `)}
3
+ `;try{await require("node:fs").promises.appendFile(this.logFilePath,o,"utf-8")}catch{}}this.isWriting=!1}}shouldLog(e){return we[e]>=we[this.minLevel]}log(e,n,o){if(!this.shouldLog(e))return;const a={id:`log_${++Ds}`,timestamp:new Date().toISOString(),level:e,service:this.service,message:n,...o&&{metadata:o}};if(Ls(a),le&&this.logFilePath,le&&this.logFilePath){const l={timestamp:a.timestamp,level:a.level,service:a.service,message:a.message,...a.metadata&&{metadata:a.metadata}};this.writeToFile(JSON.stringify(l)).catch(()=>{})}}trace(e,n){this.log("trace",e,n)}debug(e,n){this.log("debug",e,n)}info(e,n){this.log("info",e,n)}warn(e,n){this.log("warn",e,n)}error(e,n){this.log("error",e,n)}fatal(e,n){this.log("fatal",e,n)}}function $(s,e="debug"){return new Ps(s,e)}const rt=H(["pending","in_progress","completed","failed"]),zs=H(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),at=T({path:h(),line:I().nullable().optional()}),fe=T({inputTokens:I().optional(),outputTokens:I().optional(),totalTokens:I().optional()}),it=Te("type",[T({type:M("content"),content:T({type:M("text"),text:h()})}),T({type:M("text"),text:h()}),T({type:M("diff"),path:h(),oldText:h(),newText:h(),line:I().nullable().optional()}),T({type:M("terminal"),terminalId:h()})]),lt=T({id:h(),title:h(),kind:zs,status:rt,locations:E(at).optional(),rawInput:D(h(),_()).optional(),rawOutput:D(h(),_()).optional(),content:E(it).optional(),error:h().optional(),startedAt:I().optional(),completedAt:I().optional(),tokenUsage:fe.optional()}),Os=T({id:h(),status:rt.optional(),locations:E(at).optional(),rawOutput:D(h(),_()).optional(),content:E(it).optional(),error:h().optional(),completedAt:I().optional(),tokenUsage:fe.optional()});function ve(s,e){return{...s,status:e.status??s.status,locations:e.locations??s.locations,rawOutput:e.rawOutput??s.rawOutput,content:e.content?[...s.content??[],...e.content]:s.content,error:e.error??s.error,completedAt:e.completedAt??s.completedAt,tokenUsage:e.tokenUsage??s.tokenUsage}}const V=$("chat-store","debug"),S=os(s=>({connectionStatus:"disconnected",sessionId:null,error:null,messages:[],isStreaming:!1,streamingStartTime:null,toolCalls:{},totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},currentModel:"claude-sonnet-4-5-20250929",tokenDisplayMode:"context",logs:[],activeTab:"chat",input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:e=>s({connectionStatus:e}),setSessionId:e=>s({sessionId:e}),setError:e=>s({error:e}),addMessage:e=>s(n=>({messages:[...n.messages,e]})),updateMessage:(e,n)=>s(o=>{const a=o.messages.find(r=>r.id===e);let l=o.totalBilled,u=o.currentContext,f=n;if(n.tokenUsage){const r=a?.tokenUsage;V.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:r});const c={inputTokens:Math.max(n.tokenUsage.inputTokens??0,r?.inputTokens??0),outputTokens:Math.max(n.tokenUsage.outputTokens??0,r?.outputTokens??0),totalTokens:Math.max(n.tokenUsage.inputTokens??0,r?.inputTokens??0)+Math.max(n.tokenUsage.outputTokens??0,r?.outputTokens??0)};V.debug("updateMessage: merged tokenUsage",{merged:c}),f={...n,tokenUsage:c};const d=c.inputTokens-(r?.inputTokens??0),m=c.outputTokens-(r?.outputTokens??0),x=c.totalTokens-(r?.totalTokens??0);l={inputTokens:o.totalBilled.inputTokens+d,outputTokens:o.totalBilled.outputTokens+m,totalTokens:o.totalBilled.totalTokens+x},u={inputTokens:c.inputTokens,outputTokens:o.currentContext.outputTokens+m,totalTokens:c.totalTokens}}const p=o.messages.map(r=>r.id===e?{...r,...f}:r);if(n.tokenUsage){const r=a?.tokenUsage,c=f.tokenUsage,d=(c.inputTokens??0)-(r?.inputTokens??0),m=(c.outputTokens??0)-(r?.outputTokens??0),x=(c.totalTokens??0)-(r?.totalTokens??0),b=p.filter(w=>w.tokenUsage).map(w=>({id:w.id,role:w.role,tokens:w.tokenUsage})),y=p.reduce((w,v)=>({inputTokens:w.inputTokens+(v.tokenUsage?.inputTokens??0),outputTokens:w.outputTokens+(v.tokenUsage?.outputTokens??0),totalTokens:w.totalTokens+(v.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),j=y.inputTokens===l.inputTokens&&y.outputTokens===l.outputTokens&&y.totalTokens===l.totalTokens;V.debug("updateMessage: tokenUsage update",{messageId:e,updates:n.tokenUsage,existing:r,messageMax:c,delta:{inputDelta:d,outputDelta:m,totalDelta:x},totalBilled:l,currentContext:u,actualSum:y,billedCorrect:j?"✅":"❌",messageCount:p.length,messagesWithTokens:b.length,breakdown:b})}return{messages:p,totalBilled:l,currentContext:u}}),clearMessages:()=>s({messages:[]}),setIsStreaming:e=>s({isStreaming:e}),setStreamingStartTime:e=>s({streamingStartTime:e}),addToolCall:(e,n)=>s(o=>({toolCalls:{...o.toolCalls,[e]:[...o.toolCalls[e]||[],n]}})),addToolCallToCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(u=>u.role==="assistant");if(o===-1)return V.warn("No assistant message found to add tool call to"),n;const a=[...n.messages],l=a[o];return l?(a[o]={...l,toolCalls:[...l.toolCalls||[],e]},{messages:a}):n}),updateToolCallInCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(c=>c.role==="assistant");if(o===-1)return V.warn("No assistant message found to update tool call in"),n;const a=[...n.messages],l=a[o];if(!l)return n;const u=l.toolCalls||[],f=u.findIndex(c=>c.id===e.id);if(f===-1)return V.warn(`Tool call ${e.id} not found in message`),n;const p=u[f];if(!p)return n;const r=[...u];return r[f]=ve(p,e),a[o]={...l,toolCalls:r},{messages:a}}),updateToolCall:(e,n)=>s(o=>{const a=o.toolCalls[e]||[],l=a.findIndex(p=>p.id===n.id);if(l===-1)return o;const u=a[l];if(!u)return o;const f=[...a];return f[l]=ve(u,n),{toolCalls:{...o.toolCalls,[e]:f}}}),setInputValue:e=>s(n=>({input:{...n.input,value:e}})),setInputSubmitting:e=>s(n=>({input:{...n.input,isSubmitting:e}})),addFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,e]}})),removeFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((o,a)=>a!==e)}})),clearInput:()=>s(e=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}})),addTokenUsage:e=>s(n=>({totalBilled:{inputTokens:n.totalBilled.inputTokens+(e.inputTokens??0),outputTokens:n.totalBilled.outputTokens+(e.outputTokens??0),totalTokens:n.totalBilled.totalTokens+(e.totalTokens??0)},currentContext:{inputTokens:e.inputTokens??n.currentContext.inputTokens,outputTokens:n.currentContext.outputTokens+(e.outputTokens??0),totalTokens:(e.inputTokens??n.currentContext.inputTokens)+(n.currentContext.outputTokens+(e.outputTokens??0))}})),setCurrentModel:e=>s({currentModel:e}),resetTokens:()=>s({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0}}),cycleTokenDisplayMode:()=>s(e=>{const n=["context","input","output"],a=(n.indexOf(e.tokenDisplayMode)+1)%n.length,l=n[a];return l?{tokenDisplayMode:l}:e}),addLog:e=>s(n=>({logs:[...n.logs,e]})),clearLogs:()=>s({logs:[]}),setActiveTab:e=>s({activeTab:e})})),ce=$("use-chat-messages","debug");function ct(s){const e=S(c=>c.messages),n=S(c=>c.isStreaming),o=S(c=>c.sessionId),a=S(c=>c.setIsStreaming),l=S(c=>c.setStreamingStartTime),u=S(c=>c.addMessage),f=S(c=>c.updateMessage),p=S(c=>c.setError),r=i.useCallback(async c=>{if(!s){ce.error("No client available"),p("No client available");return}if(!o){ce.error("No active session"),p("No active session");return}try{const d=Date.now();a(!0),l(d);const m={id:`msg_${Date.now()}_user`,role:"user",content:c,timestamp:new Date().toISOString(),isStreaming:!1};u(m);const x=`msg_${Date.now()}_assistant`,b={id:x,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:d};u(b);const y=e.filter(N=>N.role!=="system").map(N=>`${N.role==="user"?"Human":"Assistant"}: ${N.content}`).join(`
4
+
5
+ `),j=y?`${y}
6
+
7
+ Human: ${c}`:c,w=s.receiveMessages();s.sendMessage(j,o).catch(N=>{const U=N instanceof Error?N.message:String(N);p(U),a(!1),l(null)});let v="";for await(const N of w)if(N.tokenUsage&&ce.debug("chunk.tokenUsage",{tokenUsage:N.tokenUsage}),N.isComplete){f(x,{content:v,isStreaming:!1,streamingStartTime:void 0,...N.tokenUsage?{tokenUsage:N.tokenUsage}:{}}),a(!1),l(null);break}else N.contentDelta.type==="text"&&(v+=N.contentDelta.text,f(x,{content:v,...N.tokenUsage?{tokenUsage:N.tokenUsage}:{}}),await new Promise(U=>setTimeout(U,16)))}catch(d){const m=d instanceof Error?d.message:String(d);p(m),a(!1),l(null)}},[s,o,e,u,f,a,l,p]);return{messages:e,isStreaming:n,sendMessage:r}}const Fs=$("use-chat-input","debug");function Hs(s){const e=S(d=>d.input),n=S(d=>d.setInputValue),o=S(d=>d.setInputSubmitting),a=S(d=>d.addFileAttachment),l=S(d=>d.removeFileAttachment),{sendMessage:u}=ct(s),f=i.useCallback(d=>{n(d)},[n]),p=i.useCallback(async()=>{if(!e.value.trim()||e.isSubmitting)return;const d=e.value;n(""),o(!0);try{await u(d)}catch(m){Fs.error("Failed to send message",{error:m instanceof Error?m.message:String(m)})}finally{o(!1)}},[e,n,o,u]),r=i.useCallback(d=>{a(d)},[a]),c=i.useCallback(d=>{l(d)},[l]);return{value:e.value,isSubmitting:e.isSubmitting,attachedFiles:e.attachedFiles,onChange:f,onSubmit:p,onAttachFile:r,onRemoveFile:c}}const $s=$("use-chat-session","debug");function Bs(s){const e=S(d=>d.connectionStatus),n=S(d=>d.sessionId),o=S(d=>d.setConnectionStatus),a=S(d=>d.setSessionId),l=S(d=>d.setError),u=S(d=>d.clearMessages),f=S(d=>d.resetTokens),p=i.useCallback(async()=>{if(!s){l("No client available");return}try{o("connecting"),l(null),await s.connect(),o("connected")}catch(d){$s.error("Failed to connect",{error:d instanceof Error?d.message:String(d)});const m=d instanceof Error?d.message:String(d);l(m),o("error")}},[s,o,l]),r=i.useCallback(async()=>{if(!s){l("No client available");return}try{const d=await s.startSession();a(d),u(),f()}catch(d){const m=d instanceof Error?d.message:String(d);l(m)}},[s,a,l,u,f]),c=i.useCallback(async()=>{if(s)try{await s.disconnect(),o("disconnected"),a(null)}catch(d){const m=d instanceof Error?d.message:String(d);l(m)}},[s,o,a,l]);return i.useEffect(()=>{s&&e==="disconnected"&&p()},[s,e,p]),i.useEffect(()=>{e==="connected"&&!n&&r()},[e,n,r]),{connectionStatus:e,sessionId:n,connect:p,startSession:r,disconnect:c}}function Ws(s){const e=S(u=>u.toolCalls),n=S(u=>u.addToolCall),o=S(u=>u.updateToolCall),a=S(u=>u.addToolCallToCurrentMessage),l=S(u=>u.updateToolCallInCurrentMessage);return i.useEffect(()=>{if(!s)return;const u=s.onSessionUpdate(f=>{f.type==="tool_call"?(n(f.sessionId,f.toolCall),a(f.toolCall)):f.type==="tool_call_update"&&(o(f.sessionId,f.toolCallUpdate),l(f.toolCallUpdate))});return()=>{u()}},[s,n,o,a,l]),{toolCalls:e,getToolCallsForSession:u=>{const f=e[u];return f&&f.length>0?f:Object.values(e).flat()}}}const Vs=T({id:h(),role:H(["user","assistant","system"]),content:h(),timestamp:te(),isStreaming:G().default(!1),streamingStartTime:I().optional(),metadata:D(h(),_()).optional(),toolCalls:E(lt).optional(),tokenUsage:fe.optional()}),qs=T({value:h(),isSubmitting:G(),attachedFiles:E(T({name:h(),path:h(),size:I(),mimeType:h()}))});T({sessionId:h().nullable(),isConnected:G(),isStreaming:G(),messages:E(Vs),input:qs,error:h().nullable()});H(["disconnected","connecting","connected","error"]);const k=$("http-transport");class Qs{connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;messageQueue=[];currentSessionId=null;chunkResolvers=[];streamComplete=!1;sseAbortController=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;reconnecting=!1;abortController=null;options;constructor(e){this.options={...e,baseUrl:e.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const e={protocolVersion:ds,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",e);k.info("ACP connection initialized",{initResponse:n});const o={cwd:"/",mcpServers:[]},a=await this.sendRpcRequest("session/new",o);this.currentSessionId=a.sessionId,k.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(e){this.connected=!1;const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async disconnect(){if(this.connected)try{this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.connected=!1,this.currentSessionId=null,this.messageQueue=[],this.chunkResolvers=[],this.streamComplete=!1,this.reconnecting=!1,this.reconnectAttempts=0}catch(e){const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async send(e){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");try{this.streamComplete=!1,this.messageQueue=[];const n=e.content.filter(u=>u.type==="text").map(u=>u.text).join(`
8
+ `),o={sessionId:this.currentSessionId,prompt:[{type:"text",text:n}]},a=await this.sendRpcRequest("session/prompt",o);k.debug("Prompt sent",{promptResponse:a}),this.streamComplete=!0;const l=this.chunkResolvers.shift();l?l({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(n){this.streamComplete=!0;const o=n instanceof Error?n:new Error(String(n));throw this.notifyError(o),o}}async*receive(){for(;!this.streamComplete;)if(this.messageQueue.length>0){const e=this.messageQueue.shift();if(e&&(yield e,e.isComplete))return}else{const e=await new Promise(n=>{this.chunkResolvers.push(n)});if(e.isComplete){yield e;return}else yield e}for(;this.messageQueue.length>0;){const e=this.messageQueue.shift();e&&(yield e)}yield{id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}async sendRpcRequest(e,n){const a={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:n},l={"Content-Type":"application/json",...this.options.headers},u=this.options.timeout??600*1e3,f=new AbortController,p=setTimeout(()=>f.abort(),u);try{const r=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:l,body:JSON.stringify(a),signal:f.signal});if(clearTimeout(p),!r.ok){const d=await r.text();throw new Error(`HTTP ${r.status}: ${d}`)}const c=await r.json();if(c.error)throw new Error(`ACP error: ${c.error.message||JSON.stringify(c.error)}`);return c.result||c}catch(r){throw clearTimeout(p),r instanceof Error&&r.name==="AbortError"?new Error(`Request timeout after ${u}ms`):r}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const e=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const o=await fetch(e,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!o.ok)throw new Error(`SSE connection failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response body is null");k.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const a=o.body.getReader(),l=new TextDecoder;let u="";(async()=>{try{for(;;){const{done:f,value:p}=await a.read();if(f){k.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}u+=l.decode(p,{stream:!0});const r=u.split(`
9
+ `);u=r.pop()||"";let c={event:"message",data:""};for(const d of r)d.startsWith("event:")?c.event=d.substring(6).trim():d.startsWith("data:")?c.data=d.substring(5).trim():d===""&&(c.event==="message"&&c.data&&this.handleSSEMessage(c.data),c={event:"message",data:""})}}catch(f){if(f instanceof Error&&f.name==="AbortError"){k.debug("SSE stream aborted");return}k.error("Error reading SSE stream",{error:f}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(o){throw k.error("SSE connection error",{error:o}),o}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const n=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(n),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);k.debug("SSE reconnecting",{delay:e,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(n=>setTimeout(n,e));try{await this.connectSSE(),k.info("SSE reconnected successfully"),this.reconnecting=!1}catch(n){k.error("SSE reconnection failed",{error:n}),this.reconnecting=!1}}handleSSEMessage(e){try{const n=JSON.parse(e);k.debug("Received SSE message",{message:n});const o=us.safeParse(n);if(!o.success){k.error("Invalid ACP message from SSE",{issues:o.error.issues});return}const a=o.data;k.debug("Parsed ACP message",{method:"method"in a?a.method:"(no method)"}),"method"in a&&a.method==="session/update"&&(k.debug("Received session/update notification"),"params"in a&&a.params&&(k.debug("Calling handleSessionNotification",{params:a.params}),this.handleSessionNotification(a.params)))}catch(n){k.error("Error parsing SSE message",{error:n}),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(e){k.debug("handleSessionNotification called",{params:e});const o=e.update,a=this.currentSessionId||e.sessionId;if(k.debug("Update session type",{sessionUpdate:o?.sessionUpdate}),o?.sessionUpdate==="tool_call"){k.debug("Tool call notification",{tokenUsage:o.tokenUsage});const l=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,u={id:o.toolCallId??"",title:o.title??"",kind:o.kind||"other",status:o.status||"pending",locations:o.locations,rawInput:o.rawInput,tokenUsage:o.tokenUsage,content:o.content?.map(p=>{if(typeof p!="object"||p===null)return{type:"text",text:""};const r=p;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const c=r.content;if(c.type==="text")return{type:"content",content:{type:"text",text:typeof c.text=="string"?c.text:""}}}return r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:r.type==="diff"?{type:"diff",path:typeof r.path=="string"?r.path:"",oldText:typeof r.oldText=="string"?r.oldText:"",newText:typeof r.newText=="string"?r.newText:"",line:typeof r.line=="number"?r.line:null}:r.type==="terminal"?{type:"terminal",terminalId:typeof r.terminalId=="string"?r.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now()},f={type:"tool_call",sessionId:a,status:"active",toolCall:u,messageId:l};this.notifySessionUpdate(f)}else if(o?.sessionUpdate==="tool_call_update"){const l=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,u={id:o.toolCallId??"",status:o.status,locations:o.locations,rawOutput:o.rawOutput,tokenUsage:o.tokenUsage,content:o.content?.map(p=>{if(typeof p!="object"||p===null)return{type:"text",text:""};const r=p;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const c=r.content;if(c.type==="text")return{type:"content",content:{type:"text",text:typeof c.text=="string"?c.text:""}}}return r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:r.type==="diff"?{type:"diff",path:typeof r.path=="string"?r.path:"",oldText:typeof r.oldText=="string"?r.oldText:"",newText:typeof r.newText=="string"?r.newText:"",line:typeof r.line=="number"?r.line:null}:r.type==="terminal"?{type:"terminal",terminalId:typeof r.terminalId=="string"?r.terminalId:""}:{type:"text",text:""}}),error:o.error,completedAt:o.status==="completed"||o.status==="failed"?Date.now():void 0},f={type:"tool_call_update",sessionId:a,status:"active",toolCallUpdate:u,messageId:l};k.debug("Notifying tool_call_update session update",{sessionUpdate:f}),this.notifySessionUpdate(f)}else if(o&&"sessionUpdate"in o&&o.sessionUpdate==="tool_output"){const l=o,u=l._meta&&typeof l._meta=="object"&&"messageId"in l._meta?String(l._meta.messageId):void 0,f={id:l.toolCallId??"",rawOutput:l.rawOutput,content:l.content?.map(r=>{if(typeof r!="object"||r===null)return{type:"text",text:""};const c=r;if(c.type==="content"&&typeof c.content=="object"&&c.content!==null){const d=c.content;if(d.type==="text")return{type:"content",content:{type:"text",text:typeof d.text=="string"?d.text:""}}}return c.type==="text"?{type:"text",text:typeof c.text=="string"?c.text:""}:c.type==="diff"?{type:"diff",path:typeof c.path=="string"?c.path:"",oldText:typeof c.oldText=="string"?c.oldText:"",newText:typeof c.newText=="string"?c.newText:"",line:typeof c.line=="number"?c.line:null}:c.type==="terminal"?{type:"terminal",terminalId:typeof c.terminalId=="string"?c.terminalId:""}:{type:"text",text:""}})},p={type:"tool_call_update",sessionId:a,status:"active",toolCallUpdate:f,messageId:u};k.debug("Notifying tool_output as tool_call_update",{sessionUpdate:p}),this.notifySessionUpdate(p)}else if(o?.sessionUpdate==="agent_message_chunk"){const l={type:"generic",sessionId:a,status:"active"},u=o._meta&&typeof o._meta=="object"&&"tokenUsage"in o._meta?o._meta.tokenUsage:void 0;k.debug("Agent message chunk",{tokenUsage:u});const f=o.content;if(f&&typeof f=="object"){const p=f;let r=null;if(p.type==="text"&&typeof p.text=="string"&&(r={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:p.text},tokenUsage:u,isComplete:!1}),r){const c=this.chunkResolvers.shift();c?c(r):this.messageQueue.push(r)}}this.notifySessionUpdate(l)}else{const l={type:"generic",sessionId:a,status:"active"};this.notifySessionUpdate(l)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(e){for(const n of this.sessionUpdateCallbacks)try{n(e)}catch(o){k.error("Error in session update callback",{error:o})}}notifyError(e){for(const n of this.errorCallbacks)try{n(e)}catch(o){k.error("Error in error callback",{error:o})}}}class Ks{constructor(){throw new Error("StdioTransport is not available in the browser. Use HttpTransport or WebSocketTransport instead.")}async connect(){throw new Error("StdioTransport not available in browser")}async disconnect(){}async send(){throw new Error("StdioTransport not available in browser")}async*receive(){throw new Error("StdioTransport not available in browser")}isConnected(){return!1}onSessionUpdate(){return()=>{}}onError(){return()=>{}}}class Gs{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(e){}async connect(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async disconnect(){this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}async send(e){throw!this.connected||!this.ws?new Error("Transport not connected"):new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async*receive(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}}const de=$("acp-client","debug");class Xs{config;transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;constructor(e){this.config=e,this.transport=this.createTransport(),this.setupTransportListeners(),e.autoConnect&&this.connect().catch(n=>{de.error("Failed to auto-connect",{error:n instanceof Error?n.message:String(n)})})}async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(e){const n=this.generateSessionId(),o=new Date().toISOString(),a={id:n,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};return this.sessions.set(n,a),this.currentSessionId=n,this.updateSessionStatus(n,"connected"),n}async sendMessage(e,n){const o=n||this.currentSessionId;if(!o)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(o);if(!a)throw new Error(`Session ${o} not found`);const l={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};a.messages.push(l),this.updateSessionStatus(o,"active"),await this.transport.send(l)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(e){return this.sessions.get(e)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(e){return this.sessionUpdateHandlers.add(e),()=>{this.sessionUpdateHandlers.delete(e)}}onError(e){return this.errorHandlers.add(e),()=>{this.errorHandlers.delete(e)}}createTransport(){switch(this.config.type){case"stdio":return new Ks(this.config.options);case"http":return new Qs(this.config.options);case"websocket":return new Gs(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(e=>{this.handleSessionUpdate(e)}),this.transport.onError(e=>{this.handleError(e)})}handleSessionUpdate(e){if(e.sessionId){const n=this.sessions.get(e.sessionId);n&&(e.status&&(n.status=e.status),e.message&&n.messages.push(e.message),e.error&&(n.error=e.error))}for(const n of this.sessionUpdateHandlers)try{n(e)}catch(o){de.error("Error in session update handler",{error:o instanceof Error?o.message:String(o)})}}handleError(e){for(const n of this.errorHandlers)try{n(e)}catch(o){de.error("Error in error handler",{error:o instanceof Error?o.message:String(o)})}}updateSessionStatus(e,n){const o=this.sessions.get(e);o&&(o.status=n,this.handleSessionUpdate({sessionId:e,status:n}))}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}const Js=T({name:h(),description:h().optional(),parameters:D(h(),_()).optional()}),Ys=T({name:h(),description:h(),parameters:D(h(),_()),required:E(h()).optional()}),Zs=T({name:h(),version:h().optional(),description:h().optional(),author:h().optional(),capabilities:E(Js).optional(),tools:E(Ys).optional(),supportedFormats:E(h()).optional()}),en=H(["initializing","ready","busy","error","terminated"]);T({status:en,info:Zs.optional(),pid:I().optional(),error:h().optional(),uptime:I().optional()});const dt=H(["user","assistant","system","tool"]),tn=H(["text","image","file","tool_call","tool_result"]),J=T({type:tn}),sn=J.extend({type:M("text"),text:h()}),nn=J.extend({type:M("image"),url:h().url().optional(),data:h().optional(),mimeType:h().optional()}),on=J.extend({type:M("file"),name:h(),path:h().optional(),url:h().url().optional(),mimeType:h(),size:I().optional()}),rn=J.extend({type:M("tool_call"),id:h(),name:h(),arguments:D(h(),_())}),an=J.extend({type:M("tool_result"),callId:h(),result:_(),error:h().optional()}),ut=Te("type",[sn,nn,on,rn,an]),pt=T({id:h(),role:dt,content:E(ut),timestamp:te(),metadata:D(h(),_()).optional()});T({id:h(),role:dt,contentDelta:ut,isComplete:G(),tokenUsage:T({inputTokens:I().optional(),outputTokens:I().optional(),totalTokens:I().optional()}).optional()});const ft=H(["idle","connecting","connected","active","streaming","error","disconnected"]),ln=T({agentPath:h(),agentArgs:E(h()).optional(),environment:D(h(),h()).optional(),workingDirectory:h().optional(),timeout:I().optional()}),cn=T({agentName:h().optional(),agentVersion:h().optional(),capabilities:E(h()).optional(),startedAt:te(),lastActivityAt:te().optional()});T({id:h(),status:ft,config:ln,metadata:cn.optional(),messages:E(pt),error:h().optional()});const se=T({sessionId:h(),status:ft.optional(),message:pt.optional(),error:h().optional()}),dn=se.extend({type:M("tool_call"),toolCall:lt,messageId:h().optional()}),un=se.extend({type:M("tool_call_update"),toolCallUpdate:Os,messageId:h().optional()}),pn=se.extend({type:M("tool_output"),toolOutput:T({id:h(),content:E(rs()).optional(),rawOutput:D(h(),_()).optional()}),messageId:h().optional()}),fn=se.extend({type:M("generic").optional()});as([dn,un,pn,fn]);function g(...s){return is(ls(s))}const mn=W("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 cursor-pointer",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Y=i.forwardRef(({className:s,variant:e,size:n,asChild:o=!1,...a},l)=>{const u=o?X:"button";return t.jsx(u,{className:g(mn({variant:e,size:n,className:s})),ref:l,...a})});Y.displayName="Button";const gn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));gn.displayName="Card";const hn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex flex-col space-y-1.5 p-6",s),...e}));hn.displayName="CardHeader";const xn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-2xl font-semibold leading-none tracking-tight",s),...e}));xn.displayName="CardTitle";const bn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-sm text-muted-foreground",s),...e}));bn.displayName="CardDescription";const yn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("p-6 pt-0",s),...e}));yn.displayName="CardContent";const wn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex items-center p-6 pt-0",s),...e}));wn.displayName="CardFooter";const mt=i.forwardRef(({title:s,description:e,guideUrl:n,guideText:o="Guide",suggestedPrompts:a=[],onPromptClick:l,onGuideClick:u,className:f,...p},r)=>{const c=x=>{l?.(x)},d=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),u?.()},m=[];for(let x=0;x<a.length;x+=2)m.push(a.slice(x,x+2));return t.jsxs("div",{ref:r,className:g("flex flex-col items-start gap-6",f),...p,children:[t.jsx("h3",{className:"text-heading-3 text-text-primary hidden lg:block",children:s}),t.jsx("p",{className:"text-subheading text-text-secondary max-w-prose",children:e}),(n||u)&&t.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm font-medium leading-normal text-text-primary",children:o}),t.jsx(Je,{className:"size-4 text-text-primary"})]}),a.length>0&&t.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[t.jsx("p",{className:"text-label text-text-tertiary",children:"Suggested Prompts"}),t.jsx("div",{className:"flex flex-col gap-2.5",children:m.map(x=>t.jsx("div",{className:"flex gap-2.5 items-center",children:x.map(b=>t.jsx("button",{type:"button",onClick:()=>c(b),className:"flex-1 flex items-start gap-2 p-3 bg-secondary hover:bg-secondary/80 rounded-2xl transition-colors min-w-0",children:t.jsx("span",{className:"text-base font-normal leading-normal text-text-tertiary truncate",children:b})},b))},x.join("-")))})]})]})});mt.displayName="ChatEmptyState";const gt=i.createContext(void 0),me=()=>{const s=i.useContext(gt);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},ht=i.forwardRef(({defaultExpanded:s=!1,expanded:e,onExpandedChange:n,className:o,children:a,...l},u)=>{const[f,p]=i.useState(s),r=e??f,c=i.useCallback(b=>{p(b),n?.(b)},[n]),d=i.Children.toArray(a),m=d.find(b=>i.isValidElement(b)&&typeof b.type=="function"&&b.type.displayName==="ChatHeader.ExpandablePanel"),x=d.filter(b=>b!==m);return t.jsxs(gt.Provider,{value:{isExpanded:r,setIsExpanded:c},children:[t.jsx("div",{ref:u,className:g("flex items-center justify-between px-6 py-4",o),...l,children:x}),m]})});ht.displayName="ChatHeader.Root";const vn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("h1",{ref:o,className:g("m-0 text-xl font-semibold",s),...n,children:e}));vn.displayName="ChatHeader.Title";const Nn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center gap-3",s),...n,children:e}));Nn.displayName="ChatHeader.Actions";const jn=s=>{switch(s){case"connected":return"bg-green-500";case"connecting":return"bg-yellow-500";case"error":return"bg-red-500";default:return"bg-gray-500"}},Cn=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},Sn=i.forwardRef(({status:s,statusText:e,className:n,...o},a)=>{const l=e??Cn(s),u=jn(s);return t.jsxs("div",{ref:a,className:g("flex items-center gap-2",n),...o,children:[t.jsx("div",{className:g("h-2 w-2 rounded-full",u)}),t.jsx("span",{className:"text-sm text-muted-foreground",children:l})]})});Sn.displayName="ChatHeader.StatusIndicator";const Tn=i.forwardRef(({icon:s,className:e,children:n,onClick:o,...a},l)=>{const{isExpanded:u,setIsExpanded:f}=me(),p=r=>{f(!u),o?.(r)};return t.jsxs("button",{ref:l,type:"button",onClick:p,className:g("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":u?"Collapse header":"Expand header",...a,children:[s&&t.jsx("div",{className:g("transition-transform duration-200",u&&"rotate-180"),children:s}),n]})});Tn.displayName="ChatHeader.Toggle";const xt=i.forwardRef(({className:s,children:e,...n},o)=>{const{isExpanded:a}=me();return a?t.jsx("div",{ref:o,className:g("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",s),...n,children:e}):null});xt.displayName="ChatHeader.ExpandablePanel";const bt=i.forwardRef(({commands:s=[],showCommandMenu:e,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:a,setMenuItemCount:l,triggerCounter:u,onChange:f,className:p,...r},c)=>{const d=i.useCallback((x,b)=>{const y=x.toLowerCase(),j=b.toLowerCase();if(!b)return 1;if(y.includes(j))return 1-j.length/y.length;let w=0;for(let v=0;v<y.length&&w<j.length;v++)y[v]===j[w]&&w++;return w===j.length?.5-w/y.length:0},[]),m=i.useMemo(()=>s.map(x=>({...x,score:Math.max(d(x.label,n),x.description?d(x.description,n):0)})).filter(x=>x.score>0).sort((x,b)=>b.score-x.score),[s,n,d]);return i.useEffect(()=>{l(m.length)},[m.length,l]),i.useEffect(()=>{a(0)},[a]),i.useEffect(()=>{u>0&&m[o]&&(m[o].onSelect(),f(""))},[u,m,o,f]),!e||m.length===0?null:t.jsxs("div",{ref:c,className:g("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",p),...r,children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),t.jsx("div",{className:"max-h-64 overflow-y-auto",children:m.map((x,b)=>t.jsxs("button",{type:"button",onClick:()=>x.onSelect(),className:g("w-full rounded-sm px-2 py-2 text-left text-sm transition-colors","flex items-start gap-2","hover:bg-muted",b===o&&"bg-muted"),children:[x.icon&&t.jsx("span",{className:"shrink-0 mt-0.5",children:x.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-medium",children:x.label}),x.description&&t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:x.description})]})]},x.id))})]})});bt.displayName="ChatInputCommandMenu";const yt=i.createContext(void 0),ne=()=>{const s=i.useContext(yt);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},wt=i.forwardRef(({client:s,value:e,onChange:n,onSubmit:o,disabled:a=!1,isSubmitting:l,submitOnEnter:u=!0,className:f,children:p,...r},c)=>{const d=i.useRef(null),m=Hs(s??null),x=S(R=>R.isStreaming),b=m?m.value:e||"",y=m?m.onChange:n||(()=>{}),j=m?m.onSubmit:o||(async()=>{}),w=m?m.isSubmitting||x:l||!1,[v,N]=i.useState(!1),[U,L]=i.useState(""),[O,C]=i.useState(0),[A,P]=i.useState(0),[ae,ie]=i.useState(0),Qt=i.useCallback(()=>{ie(R=>R+1)},[]),Kt=async R=>{R.preventDefault(),b.trim()&&!w&&!a&&(await j(),setTimeout(()=>{d.current?.focus()},0))},Gt=R=>{const z=R.target;!(z.tagName==="BUTTON"||z.tagName==="INPUT"||z.tagName==="TEXTAREA"||z.closest("button"))&&d.current&&d.current.focus()},Xt=R=>{const z=R.target;!(z.tagName==="BUTTON"||z.tagName==="INPUT"||z.tagName==="TEXTAREA"||z.closest("button"))&&R.key===" "&&(R.preventDefault(),d.current&&d.current.focus())};return i.useEffect(()=>{const R=document.querySelector('textarea[name="chat-input"]');R&&d.current!==R&&(d.current=R)},[]),i.useEffect(()=>{!b&&d.current&&(d.current.style.height="auto",d.current.style.overflowY="hidden")},[b]),t.jsx(yt.Provider,{value:{value:b,onChange:y,onSubmit:j,disabled:a,isSubmitting:w,submitOnEnter:u,showCommandMenu:v,setShowCommandMenu:N,commandMenuQuery:U,setCommandMenuQuery:L,selectedMenuIndex:O,setSelectedMenuIndex:C,menuItemCount:A,setMenuItemCount:P,triggerMenuSelect:Qt,triggerCounter:ae},children:t.jsx("form",{ref:c,onSubmit:Kt,onClick:Gt,onKeyDown:Xt,className:g("relative w-full divide-y rounded-xl border bg-background shadow-md",f),...r,children:p})})});wt.displayName="ChatInput.Root";const vt=i.forwardRef(({asChild:s=!1,className:e,onKeyDown:n,children:o,...a},l)=>{const{value:u,onChange:f,onSubmit:p,disabled:r,isSubmitting:c,submitOnEnter:d,showCommandMenu:m,setShowCommandMenu:x,setCommandMenuQuery:b,setSelectedMenuIndex:y,menuItemCount:j,triggerMenuSelect:w}=ne(),v=i.useRef(null),O={ref:i.useCallback(C=>{v.current=C,typeof l=="function"?l(C):l&&(l.current=C)},[l]),name:"chat-input",value:u,onChange:C=>{const A=C.target.value;if(f(A),A.startsWith("/")&&!A.includes(`
10
+ `)){x(!0);const ie=A.slice(1);b(ie)}else x(!1),b("");const P=v.current;if(!P)return;P.style.height="auto";const ae=Math.min(P.scrollHeight,164);P.style.height=`${ae}px`,P.scrollHeight>164?P.style.overflowY="auto":P.style.overflowY="hidden"},onKeyDown:C=>{if(m&&j>0){if(C.key==="ArrowDown"){C.preventDefault(),y(A=>(A+1)%j);return}else if(C.key==="ArrowUp"){C.preventDefault(),y(A=>(A-1+j)%j);return}else if(C.key==="Enter"&&!C.shiftKey){C.preventDefault(),w();return}else if(C.key==="Escape"){C.preventDefault(),x(!1),b("");return}}d&&C.key==="Enter"&&!C.shiftKey&&(u.trim()&&!c&&!r?(C.preventDefault(),p()):(c||r)&&C.preventDefault()),n?.(C)},disabled:r,...a};return s&&i.isValidElement(o)?i.cloneElement(o,O):t.jsx("textarea",{...O,className:g("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 field-sizing-content max-h-[6lh]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});vt.displayName="ChatInput.Field";const Nt=i.forwardRef(({asChild:s=!1,className:e,disabled:n,children:o,...a},l)=>{const{value:u,disabled:f,isSubmitting:p}=ne(),r=n||f||p||!u.trim(),c=s?X:Y;return t.jsx(c,{ref:l,type:"submit",disabled:r,variant:s?void 0:"default",size:"icon",className:g(!s&&"gap-1.5 rounded-full",e),...a,children:o})});Nt.displayName="ChatInput.Submit";const jt=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center justify-between p-2",s),...n,children:e}));jt.displayName="ChatInput.Toolbar";const Ct=i.forwardRef(({asChild:s=!1,className:e,children:n,onClick:o,...a},l)=>{const{value:u,onChange:f,setShowCommandMenu:p,setCommandMenuQuery:r}=ne(),c=m=>{u.startsWith("/")||(f("/"),p(!0),r("")),o?.(m)},d=s?X:Y;return t.jsx(d,{ref:l,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),onClick:c,...a,children:n||t.jsx(vs,{className:"size-4"})})});Ct.displayName="ChatInput.Actions";const St=i.forwardRef(({asChild:s=!1,className:e,children:n,...o},a)=>{const l=s?X:Y;return t.jsx(l,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(Ns,{className:"size-4"})})});St.displayName="ChatInput.Attachment";const Tt=i.forwardRef(({asChild:s=!1,className:e,children:n,...o},a)=>{const l=s?X:Y;return t.jsx(l,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(js,{className:"size-4"})})});Tt.displayName="ChatInput.VoiceInput";const kt=i.forwardRef(({commands:s=[],className:e,onChange:n,...o},a)=>{const{showCommandMenu:l,commandMenuQuery:u,selectedMenuIndex:f,setSelectedMenuIndex:p,setMenuItemCount:r,triggerCounter:c,onChange:d}=ne();return t.jsx(bt,{ref:a,commands:s,showCommandMenu:l,commandMenuQuery:u,selectedMenuIndex:f,setSelectedMenuIndex:p,setMenuItemCount:r,triggerCounter:c,onChange:d,className:e,...o})});kt.displayName="ChatInput.CommandMenu";const kn=({className:s,...e})=>t.jsx(Yt,{className:g("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...e}),It=({className:s,...e})=>t.jsx(Zt,{className:g(s),...e}),In=({withHandle:s,className:e,...n})=>t.jsx(es,{className:g("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",e),...n,children:s&&t.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"h-2.5 w-2.5",children:[t.jsx("title",{children:"Resize Handle"}),t.jsx("circle",{cx:"9",cy:"12",r:"1"}),t.jsx("circle",{cx:"9",cy:"5",r:"1"}),t.jsx("circle",{cx:"9",cy:"19",r:"1"}),t.jsx("circle",{cx:"15",cy:"12",r:"1"}),t.jsx("circle",{cx:"15",cy:"5",r:"1"}),t.jsx("circle",{cx:"15",cy:"19",r:"1"})]})})}),En=({...s})=>t.jsx(cs,{position:"top-center",className:"toaster group",style:{"--top-offset":"16px","--width:":"calc(100% - 2 * var(--top-offset))",position:"absolute",zIndex:5,top:"var(--top-offset)",left:"50%",transform:"translateX(-50%)",width:"calc(100% - 2 * var(--top-offset))",maxWidth:"480px"},offset:0,toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...s}),Et=i.createContext(void 0),ge=()=>{const s=i.useContext(Et);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},Rt=i.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:e="hidden",defaultActiveTab:n="todo",className:o,children:a,...l},u)=>{const[f,p]=i.useState(s),[r,c]=i.useState(e),[d,m]=i.useState(n);return t.jsx(Et.Provider,{value:{sidebarOpen:f,setSidebarOpen:p,panelSize:r,setPanelSize:c,activeTab:d,setActiveTab:m},children:t.jsx("div",{ref:u,className:g("flex h-screen flex-row bg-background text-foreground",o),...l,children:t.jsx(kn,{direction:"horizontal",className:"flex-1",children:a})})})});Rt.displayName="ChatLayout.Root";const Rn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("relative z-10 border-b border-border bg-card shrink-0",s),...n,children:e}));Rn.displayName="ChatLayout.Header";const Mt=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx(It,{defaultSize:75,minSize:50,children:t.jsx("div",{ref:o,className:g("flex flex-1 flex-col overflow-hidden h-full",s),...n,children:e})}));Mt.displayName="ChatLayout.Main";const Ut=i.forwardRef(({showToaster:s=!0,className:e,children:n,...o},a)=>t.jsxs("div",{ref:a,className:g("relative flex flex-1 flex-col overflow-hidden",e),...o,children:[n,s&&t.jsx(En,{})]}));Ut.displayName="ChatLayout.Body";const At=i.forwardRef(({className:s,children:e,onScrollChange:n,showScrollToBottom:o=!0,...a},l)=>{const[u,f]=i.useState(!1),p=i.useRef(null);i.useImperativeHandle(l,()=>p.current);const r=i.useCallback(()=>{const m=p.current;if(!m)return;const{scrollTop:x,scrollHeight:b,clientHeight:y}=m,w=b-x-y<100;f(!w&&o),n?.(w)},[n,o]),c=i.useCallback(()=>{r()},[r]),d=i.useCallback(()=>{const m=p.current;m&&m.scrollTo({top:m.scrollHeight,behavior:"smooth"})},[]);return i.useEffect(()=>{r()},[r]),t.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[t.jsx("div",{ref:p,className:g("h-full overflow-y-auto",s),onScroll:c,...a,children:t.jsx("div",{className:"mx-auto max-w-chat min-h-full flex flex-col",children:e})}),u&&t.jsx("button",{type:"button",onClick:d,className:g("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:t.jsx(Cs,{className:"size-4"})})]})});At.displayName="ChatLayout.Messages";const Dt=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("bg-linear-to-t from-background to-transparent px-4 pb-4",s),...n,children:t.jsx("div",{className:"mx-auto max-w-chat",children:e})}));Dt.displayName="ChatLayout.Footer";const Mn=i.forwardRef(({className:s,children:e,...n},o)=>{const{sidebarOpen:a}=ge();return a?t.jsx("div",{ref:o,className:g("border-r border-border bg-card w-64 overflow-y-auto",s),...n,children:e}):null});Mn.displayName="ChatLayout.Sidebar";const _t=i.forwardRef(({breakpoint:s="lg",className:e,children:n,...o},a)=>{const{panelSize:l}=ge();return l==="hidden"?null:t.jsxs(t.Fragment,{children:[t.jsx(In,{withHandle:!0}),t.jsx(It,{defaultSize:25,minSize:15,maxSize:50,children:t.jsx("div",{ref:a,className:g("hidden h-full border-l border-border bg-card overflow-y-auto transition-all duration-300",s==="md"&&"md:block",s==="lg"&&"lg:block",s==="xl"&&"xl:block",s==="2xl"&&"2xl:block",e),...o,children:n})})]})});_t.displayName="ChatLayout.Aside";const oe=i.forwardRef(({todos:s,className:e,...n},o)=>t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No todos yet"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a.text},a.id))}));oe.displayName="TodoTabContent";const re=i.forwardRef(({files:s=[],className:e,...n},o)=>t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No files attached"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a},a))}));re.displayName="FilesTabContent";const Un=i.forwardRef(({data:s,className:e,...n},o)=>t.jsxs("div",{ref:o,className:g("space-y-4",e),...n,children:[t.jsx("h3",{className:"font-semibold text-lg",children:"Database"}),t.jsxs("div",{className:"text-sm text-muted-foreground",children:[t.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),t.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[t.jsx("p",{children:"Your large data table would go here"}),s&&typeof s=="object"?t.jsx("pre",{className:"mt-2 text-xs overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));Un.displayName="DatabaseTabContent";const he=ps,Q=i.forwardRef(({className:s,...e},n)=>t.jsx(ke,{ref:n,className:g("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...e}));Q.displayName=ke.displayName;const K=i.forwardRef(({className:s,...e},n)=>t.jsx(Ie,{ref:n,className:g("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",s),...e}));K.displayName=Ie.displayName;const F=i.forwardRef(({className:s,...e},n)=>t.jsx(Ee,{ref:n,className:g("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...e}));F.displayName=Ee.displayName;const Lt=i.forwardRef(({todo:s,className:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center gap-3 px-3 py-2 rounded-lg",e),...n,children:t.jsx("span",{className:g("flex-1 text-[var(--font-size)] font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"shimmer-animation"),children:s.text})}));Lt.displayName="TodoListItem";const Pt=i.forwardRef(({client:s,todos:e,className:n,...o},a)=>{const l=e||[];return t.jsx("div",{ref:a,className:g("space-y-2 max-h-64 overflow-y-auto",n),...o,children:l.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic",children:"No tasks yet."}):l.map(u=>t.jsx(Lt,{todo:u},u.id))})});Pt.displayName="TodoList";const An=i.forwardRef(({client:s,todos:e,variant:n="animated",showIcons:o=!1,visibleTabs:a=["todo","files","database"],className:l,...u},f)=>{const p=e||[],[r,c]=i.useState(a[0]||"todo"),d=i.useRef(null),m=i.useRef(null);i.useEffect(()=>{const j=setTimeout(()=>{const w=d.current;if(r&&w){const v=m.current;if(v){const N=w.getBoundingClientRect(),U=v.getBoundingClientRect(),L=U.left-N.left,O=U.width,C=L/N.width*100,A=100-(L+O)/N.width*100;w.style.clipPath=`inset(0 ${A.toFixed(2)}% 0 ${C.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(j)},[r]);const b=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:Ye},{id:"files",label:"Files",icon:Ze},{id:"database",label:"Database",icon:et}].filter(y=>a.includes(y.id));return t.jsx("div",{ref:f,className:g("select-none",l),...u,children:t.jsxs(he,{value:r,onValueChange:c,className:"w-full",children:[n==="pills"?t.jsx(Q,{className:g("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:b.map(y=>{const j=y.icon;return t.jsxs(K,{value:y.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&j&&t.jsx(j,{className:"size-4"}),y.label]},y.id)})}):t.jsxs("div",{className:"relative mb-4 border-border",children:[t.jsx(Q,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:b.map(y=>t.jsx(K,{value:y.id,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:y.label},y.id))}),t.jsx("div",{ref:d,className:"absolute top-0 left-0 w-full overflow-hidden z-10 pointer-events-none",style:{clipPath:"inset(0 100% 0 0% round 999px)",transition:"clip-path 0.25s ease-out"},children:t.jsx(Q,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:b.map(y=>t.jsx(K,{value:y.id,ref:r===y.id?m:null,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:y.label},y.id))})})]}),t.jsx(F,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?t.jsx(oe,{todos:p}):t.jsx(Pt,{todos:p})}),t.jsx(F,{value:"files",className:n==="pills"?"mt-0":"",children:t.jsx(re,{})}),t.jsx(F,{value:"database",className:n==="pills"?"mt-0":"",children:t.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})})]})})});An.displayName="ChatSecondaryPanel";const Dn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex h-full flex-col",s),...n,children:e}));Dn.displayName="ChatSidebar.Root";const _n=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("border-b border-border px-4 py-3",s),...n,children:e}));_n.displayName="ChatSidebar.Header";const Ln=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex-1 overflow-y-auto p-4",s),...n,children:e}));Ln.displayName="ChatSidebar.Content";const Pn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("border-t border-border px-4 py-3",s),...n,children:e}));Pn.displayName="ChatSidebar.Footer";const zn=i.forwardRef(({children:s,className:e,...n},o)=>{const[a,l]=i.useState(s),[u,f]=i.useState(!1),p=i.useRef(s),r=i.useRef(!0);return i.useEffect(()=>{if(r.current){r.current=!1,p.current=s;return}if(p.current===s)return;f(!0);const c=setTimeout(()=>{l(s),p.current=s,requestAnimationFrame(()=>{f(!1)})},150);return()=>{clearTimeout(c)}},[s]),t.jsx("span",{ref:o,className:g("text-sm text-foreground opacity-60 transition-opacity duration-300",u?"opacity-0":"opacity-60",e),...n,children:a})});zn.displayName="ChatStatus";const On=i.forwardRef(({autoScroll:s=!0,isStreaming:e=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:a=!0,scrollButton:l,className:u,children:f,...p},r)=>{const c=i.useRef(null),[d,m]=i.useState(!0),[x,b]=i.useState(!1),y=i.useRef(0);i.useImperativeHandle(r,()=>{if(!c.current)throw new Error("Container ref not initialized");return c.current});const j=i.useCallback(()=>{const v=c.current;if(!v)return;const{scrollTop:N,scrollHeight:U,clientHeight:L}=v,C=U-N-L<o;m(C),b(!C&&a),y.current=N},[o,a]),w=i.useCallback((v=n)=>{const N=c.current;N&&N.scrollTo({top:N.scrollHeight,behavior:v})},[n]);return i.useEffect(()=>{!s||!c.current||(e&&d?w("auto"):!e&&d&&w())},[s,e,d,w]),i.useEffect(()=>{const v=c.current;if(!v)return;const N=()=>{j()};return v.addEventListener("scroll",N,{passive:!0}),j(),()=>{v.removeEventListener("scroll",N)}},[j]),i.useEffect(()=>{const v=c.current;if(!v)return;const N=new ResizeObserver(()=>{d&&s&&w("auto")});return N.observe(v),()=>{N.disconnect()}},[d,s,w]),t.jsxs("div",{className:"relative flex-1",children:[t.jsx("div",{ref:c,className:g("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",u),...p,children:t.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:f})}),x&&t.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:l||t.jsxs("button",{type:"button",onClick:()=>w(),className:"px-4 py-2 rounded-full bg-card border border-border shadow-lg hover:shadow-xl hover:bg-card/90 transition-all text-sm font-medium text-foreground flex items-center gap-2","aria-label":"Scroll to bottom",children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Down arrow",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})}),"Scroll to bottom"]})})]})});On.displayName="Conversation";const Fn=fs,zt=i.forwardRef(({className:s,...e},n)=>t.jsx(Re,{ref:n,className:g("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e}));zt.displayName=Re.displayName;const Hn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Fn,{children:[t.jsx(zt,{}),t.jsxs(Me,{ref:o,className:g("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...n,children:[e,t.jsxs(ms,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[t.jsx(Ss,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hn.displayName=Me.displayName;const $n=i.forwardRef(({className:s,...e},n)=>t.jsx(Ue,{ref:n,className:g("text-lg font-semibold leading-none tracking-tight",s),...e}));$n.displayName=Ue.displayName;const Bn=i.forwardRef(({className:s,...e},n)=>t.jsx(Ae,{ref:n,className:g("text-sm text-muted-foreground",s),...e}));Bn.displayName=Ae.displayName;const Wn=i.forwardRef(({className:s,inset:e,children:n,...o},a)=>t.jsxs(De,{ref:a,className:g("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",s),...o,children:[n,t.jsx(Je,{className:"ml-auto h-4 w-4"})]}));Wn.displayName=De.displayName;const Vn=i.forwardRef(({className:s,...e},n)=>t.jsx(_e,{ref:n,className:g("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",s),...e}));Vn.displayName=_e.displayName;const qn=i.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(gs,{children:t.jsx(Le,{ref:o,sideOffset:e,className:g("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",s),...n})}));qn.displayName=Le.displayName;const Qn=i.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(Pe,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",s),...n}));Qn.displayName=Pe.displayName;const Kn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(ze,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(Oe,{children:t.jsx(tt,{className:"h-4 w-4"})})}),e]}));Kn.displayName=ze.displayName;const Gn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Fe,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(Oe,{children:t.jsx(st,{className:"h-2 w-2 fill-current"})})}),e]}));Gn.displayName=Fe.displayName;const Xn=i.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(He,{ref:o,className:g("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",s),...n}));Xn.displayName=He.displayName;const Jn=i.forwardRef(({className:s,...e},n)=>t.jsx($e,{ref:n,className:g("-mx-1 my-1 h-px bg-border",s),...e}));Jn.displayName=$e.displayName;const Yn=W("flex h-10 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),Zn=i.forwardRef(({className:s,type:e,variant:n,...o},a)=>t.jsx("input",{type:e,className:g(Yn({variant:n,className:s})),ref:a,...o}));Zn.displayName="Input";const eo=i.forwardRef(({className:s,...e},n)=>t.jsx(Be,{ref:n,className:g("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...e}));eo.displayName=Be.displayName;const to=W("flex animate-fadeIn",{variants:{role:{user:"max-w-[80%] self-end ml-auto mr-2",assistant:"self-start mr-auto",system:"self-start mr-auto max-w-full"},layout:{default:"",full:"max-w-full",compact:"max-w-[90%]"}},defaultVariants:{role:"assistant",layout:"default"}}),Ot=i.forwardRef(({message:s,role:e,layout:n,className:o,children:a,messageId:l,autoScroll:u,isLastMessage:f=!1,...p},r)=>{const c=s?s.role:e||"assistant",d=s?s.id:l,m=i.useRef(null),[x,b]=i.useState(void 0);return i.useImperativeHandle(r,()=>m.current),i.useEffect(()=>{if(!f||c!=="assistant"){b(void 0);return}const y=()=>{const w=m.current;if(!w)return;let v=w.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(!v)return;const N=w.previousElementSibling;if(!N||N.getAttribute("aria-label")!=="user message"){b(void 0);return}const U=v.clientHeight,L=N.offsetHeight,C=Math.max(0,U-L-32);b(C)};y();const j=new ResizeObserver(y);if(m.current){j.observe(m.current);let w=m.current.parentElement;for(;w&&!w.classList.contains("overflow-y-auto");)w=w.parentElement;w&&j.observe(w)}return()=>j.disconnect()},[f,c]),i.useEffect(()=>{if((u!==void 0?u:c==="user")&&m.current){const j=setTimeout(()=>{m.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(j)}},[c,u]),t.jsx("article",{ref:m,"aria-label":`${c} message`,"data-message-id":d,className:g(to({role:c,layout:n}),o),style:{minHeight:x!==void 0?`${x}px`:void 0},...p,children:a})});Ot.displayName="Message";const ee=128e3,Ne={"claude-sonnet-4-5-20250929":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-haiku-20240307":2e5,"gpt-4-turbo":128e3,"gpt-4-turbo-preview":128e3,"gpt-4-0125-preview":128e3,"gpt-4-1106-preview":128e3,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,default:ee};function so(s){if(!s)return ee;if(s in Ne)return Ne[s]??ee;const e=s.toLowerCase();return e.includes("claude")?2e5:e.includes("gpt-4-turbo")?128e3:e.includes("gpt-4-32k")?32768:e.includes("gpt-4")?8192:e.includes("gpt-3.5")?16385:ee}function no(s,e){const n=so(e);return s/n*100}function oo(s,e,n=1){return`${no(s,e).toFixed(n)}%`}const je=W("mb-3 rounded-lg bg-card border border-border transition-all",{variants:{variant:{default:"opacity-70",subtle:"opacity-50",prominent:"opacity-90 shadow-sm"}},defaultVariants:{variant:"default"}}),ro=W("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Ft=i.forwardRef(({content:s,isStreaming:e=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:a=!1,autoCollapse:l=!0,autoCollapseDelay:u=2e3,label:f="Thinking",variant:p,className:r},c)=>{const[d,m]=i.useState(n==="inline"?!0:o),[x,b]=i.useState(!1);return i.useEffect(()=>{if(l&&!e&&s&&n==="collapsible"){const y=setTimeout(()=>{b(!0),m(!1)},u);return()=>clearTimeout(y)}},[e,s,l,u,n]),i.useEffect(()=>{a&&e&&n==="collapsible"&&!x&&m(!0)},[a,e,n,x]),!s&&!e?null:n==="inline"?t.jsxs("div",{ref:c,className:g(je({variant:p}),"p-3",r),children:[t.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:f}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse"})]}),t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):t.jsxs("div",{ref:c,className:g("mb-3",r),children:[t.jsxs("button",{type:"button",onClick:()=>{m(!d),b(!1)},className:"w-full flex items-center justify-between p-2.5 rounded-lg bg-card border border-border hover:bg-card/80 hover:shadow-sm transition-all text-left","aria-expanded":d,"aria-label":`${d?"Collapse":"Expand"} reasoning`,children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide shrink-0",children:f}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!d&&s&&t.jsxs("span",{className:"text-xs text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),t.jsx(ue,{className:ro({expanded:d}),"aria-hidden":"true"})]}),d&&t.jsx("div",{className:g(je({variant:p}),"mt-2 p-3 animate-fadeIn"),children:t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});Ft.displayName="Reasoning";const Ht=i.forwardRef(({content:s,isStreaming:e=!1,showEmpty:n=!0,emptyMessage:o="",className:a,...l},u)=>{if(!s&&e&&n)return t.jsx("div",{ref:u,className:g("opacity-70 italic text-sm",a),...l,children:o});if(!s)return null;const f={table:({node:p,...r})=>t.jsx("div",{className:"overflow-x-auto my-4",children:t.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...r})}),thead:({node:p,...r})=>t.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:p,...r})=>t.jsx("tbody",{...r}),tr:({node:p,...r})=>t.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:p,...r})=>t.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...r}),td:({node:p,...r})=>t.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:p,checked:r,...c})=>c.type==="checkbox"?t.jsx("input",{type:"checkbox",checked:r||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...c}):t.jsx("input",{...c}),code:({node:p,...r})=>r.className?.includes("language-")?t.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-sm font-mono text-foreground shadow-sm",...r}):t.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-sm font-mono text-foreground",...r}),pre:({node:p,...r})=>t.jsx("pre",{className:"my-4 rounded-lg",...r}),h1:({node:p,...r})=>t.jsx("h1",{className:"text-2xl font-bold mt-6 mb-4 text-foreground border-b border-border pb-2",...r}),h2:({node:p,...r})=>t.jsx("h2",{className:"text-xl font-semibold mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...r}),h3:({node:p,...r})=>t.jsx("h3",{className:"text-lg font-semibold mt-4 mb-2 text-foreground",...r}),h4:({node:p,...r})=>t.jsx("h4",{className:"text-base font-semibold mt-3 mb-2 text-foreground",...r}),ul:({node:p,...r})=>{const c=p?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="li"&&"children"in d&&Array.isArray(d.children)&&d.children.some(m=>typeof m=="object"&&m!==null&&"type"in m&&m.type==="element"&&"tagName"in m&&m.tagName==="input"&&"properties"in m&&typeof m.properties=="object"&&m.properties!==null&&"type"in m.properties&&m.properties.type==="checkbox"));return t.jsx("ul",{className:g("my-2 space-y-1 text-foreground",c?"list-none space-y-2":"list-disc list-inside"),...r})},ol:({node:p,...r})=>t.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...r}),li:({node:p,...r})=>{const c=p?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="input"&&"properties"in d&&typeof d.properties=="object"&&d.properties!==null&&"type"in d.properties&&d.properties.type==="checkbox");return t.jsx("li",{className:g("flex items-start",c?"gap-2":"ml-2"),...r})},a:({node:p,...r})=>t.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:p,...r})=>t.jsx("p",{className:"my-2 text-foreground leading-relaxed",...r}),blockquote:({node:p,...r})=>t.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2 rounded-r-md shadow-sm",...r}),hr:({node:p,...r})=>t.jsx("hr",{className:"my-6 border-t border-border opacity-50",...r})};return t.jsxs("div",{ref:u,className:g("markdown-content prose prose-sm max-w-none dark:prose-invert",a),...l,children:[t.jsx(ts,{remarkPlugins:[Us],components:f,children:s}),e&&s&&t.jsx("span",{className:"inline-block ml-1 animate-typing text-primary",children:"..."})]})});Ht.displayName="Response";const ao={pending:"bg-transparent text-muted-foreground",in_progress:"bg-transparent text-muted-foreground",completed:"bg-transparent text-muted-foreground",failed:"bg-transparent text-muted-foreground"};function io({toolCall:s}){const[e,n]=i.useState(!1);return t.jsxs("div",{className:"flex flex-col",children:[t.jsxs("button",{type:"button",className:"flex items-center gap-1.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>n(!e),"aria-expanded":e,children:[t.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded ${ao[s.status]}`,children:[t.jsx(Ts,{className:"h-3 w-3"}),t.jsx("span",{children:s.title}),s.status==="completed"&&t.jsx("span",{children:"✓"})]}),t.jsx("span",{className:"text-gray-400 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:e?"▲":"▼"})]}),e&&t.jsxs("div",{className:"mt-2 space-y-3 text-sm border border-gray-200 rounded-md p-3 bg-white shadow-sm max-w-full",children:[s.locations&&s.locations.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5",children:"Files"}),t.jsx("ul",{className:"space-y-1",children:s.locations.map(o=>t.jsxs("li",{className:"font-mono text-xs text-gray-700 bg-gray-50 px-2 py-1 rounded",children:[o.path,o.line!==null&&o.line!==void 0&&`:${o.line}`]},`${o.path}:${o.line??""}`))})]}),s.rawInput&&Object.keys(s.rawInput).length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5",children:"Input"}),t.jsx("div",{className:"bg-gray-50 p-2 rounded border border-gray-200",children:t.jsx(be,{value:s.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent"}})})]}),s.content&&s.content.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5",children:"Output"}),t.jsx("div",{className:"space-y-2",children:s.content.map((o,a)=>{const l=()=>o.type==="diff"&&"path"in o?`diff-${o.path}-${a}`:o.type==="terminal"&&"terminalId"in o?`terminal-${o.terminalId}`:o.type==="text"&&"text"in o?`text-${o.text.substring(0,20)}-${a}`:o.type==="content"&&"content"in o?`content-${o.content.text?.substring(0,20)}-${a}`:`block-${a}`,u=(f,p)=>{try{const r=JSON.parse(f);if(typeof r=="object"&&r!==null)return t.jsx("div",{className:"bg-gray-50 p-2 rounded border border-gray-200",children:t.jsx(be,{value:r,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent"}})},p)}catch{}return t.jsx("pre",{className:"bg-gray-50 p-2.5 rounded border border-gray-200 text-xs overflow-x-auto font-mono text-gray-800",children:f},p)};if(o.type==="content"&&"content"in o){const f=o.content;if(f.type==="text"&&f.text)return u(f.text,l())}return o.type==="text"&&"text"in o?u(o.text,l()):o.type==="diff"&&"path"in o&&"oldText"in o&&"newText"in o?t.jsxs("div",{className:"border rounded",children:[t.jsxs("div",{className:"bg-gray-100 px-2 py-1 text-xs font-mono",children:[o.path,"line"in o&&o.line!==null&&o.line!==void 0&&`:${o.line}`]}),t.jsxs("div",{className:"p-2 font-mono text-xs",children:[t.jsxs("div",{className:"text-red-600",children:["- ",o.oldText]}),t.jsxs("div",{className:"text-green-600",children:["+ ",o.newText]})]})]},l()):o.type==="terminal"&&"terminalId"in o?t.jsxs("div",{className:"bg-black text-green-400 p-2 rounded text-xs font-mono",children:["Terminal: ",o.terminalId]},l()):null})})]}),s.error&&t.jsxs("div",{className:"bg-red-50 border border-red-200 rounded p-2.5 text-red-700",children:[t.jsx("div",{className:"text-xs font-semibold text-red-600 uppercase tracking-wide mb-1.5",children:"Error"}),t.jsx("div",{className:"text-xs",children:s.error})]}),s.tokenUsage&&t.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded p-2.5",children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2",children:"Token Usage"}),t.jsxs("div",{className:"grid grid-cols-3 gap-3 text-xs text-gray-700",children:[s.tokenUsage.inputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-gray-500 text-[10px] uppercase tracking-wide mb-0.5",children:"Input"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.inputTokens.toLocaleString()})]}),s.tokenUsage.outputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-gray-500 text-[10px] uppercase tracking-wide mb-0.5",children:"Output"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.outputTokens.toLocaleString()})]}),s.tokenUsage.totalTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-gray-500 text-[10px] uppercase tracking-wide mb-0.5",children:"Total"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.totalTokens.toLocaleString()})]})]})]}),s.startedAt&&t.jsxs("div",{className:"text-xs text-gray-500",children:["Started: ",new Date(s.startedAt).toLocaleTimeString(),s.completedAt&&t.jsxs(t.Fragment,{children:[" ","| Completed:"," ",new Date(s.completedAt).toLocaleTimeString()," (",Math.round((s.completedAt-s.startedAt)/1e3),"s)"]})]})]})]})}const Z=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],Ce=["...","·..",".·.","..·",".·.","·.."];function lo({startTime:s}){const[e,n]=i.useState(0),[o,a]=i.useState(()=>Z[Math.floor(Math.random()*Z.length)]),[l,u]=i.useState(0);i.useEffect(()=>{const r=setInterval(()=>{const d=Date.now()-s;n(d)},100);return()=>clearInterval(r)},[s]),i.useEffect(()=>{const r=setInterval(()=>{const c=Math.floor(Math.random()*Z.length);a(Z[c])},1500);return()=>clearInterval(r)},[]),i.useEffect(()=>{const r=setInterval(()=>{u(c=>(c+1)%Ce.length)},100);return()=>clearInterval(r)},[]);const f=(e/1e3).toFixed(1),p=Ce[l];return t.jsxs("span",{className:"text-muted-foreground text-sm",children:[o,p," ",f,"s"]})}const co=W("w-full px-4 py-3 rounded-xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-primary text-primary-foreground shadow-sm",assistant:"text-foreground",system:"bg-card border border-border text-foreground opacity-80 text-sm"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),$t=i.forwardRef(({role:s,variant:e,isStreaming:n,message:o,thinkingDisplayStyle:a="collapsible",className:l,children:u,...f},p)=>{const r=S(y=>y.streamingStartTime),c=S(y=>y.currentModel),d=o&&!u,m=d?o.role:s||"assistant",x=d?o.isStreaming:n;let b=u;if(d){const y=o.metadata?.thinking,j=!!y,w=o.isStreaming&&!o.content&&o.role==="assistant";b=t.jsxs(t.Fragment,{children:[o.role==="assistant"&&j&&t.jsx(Ft,{content:y,isStreaming:o.isStreaming,mode:a,autoCollapse:!0}),w&&r&&t.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[t.jsx(nt,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx(lo,{startTime:r})]}),o.role==="assistant"&&o.toolCalls&&o.toolCalls.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mb-3",children:o.toolCalls.map(v=>t.jsx(io,{toolCall:v},v.id))}),o.role==="user"?t.jsx("div",{className:"whitespace-pre-wrap",children:o.content}):t.jsx(Ht,{content:o.content,isStreaming:o.isStreaming,showEmpty:!1}),o.role==="assistant"&&o.tokenUsage&&t.jsx("div",{className:"mt-3 pt-2 border-t border-border/30 text-xs text-muted-foreground/60",children:t.jsxs("span",{children:["Context:"," ",oo(o.tokenUsage.totalTokens??0,c??void 0)," ","(",(o.tokenUsage.totalTokens??0).toLocaleString()," ","tokens)"]})})]})}return t.jsx("div",{ref:p,className:g(co({role:m,variant:e}),x&&"animate-pulse-subtle",l),...f,children:b})});$t.displayName="MessageContent";const xe=i.forwardRef(({showIcons:s=!0,visibleTabs:e=["todo","files"],variant:n="default",className:o,...a},l)=>{const f=[{id:"todo",label:"To-do",icon:Ye},{id:"files",label:"Files",icon:Ze},{id:"database",label:"Database",icon:et}].filter(r=>e.includes(r.id)),p=n==="compact"?"gap-[4px]":"gap-3";return t.jsx(Q,{ref:l,className:g("w-full justify-start bg-transparent p-0 h-auto",p,o),...a,children:f.map(r=>{const c=r.icon;return t.jsxs(K,{value:r.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[s&&c&&t.jsx(c,{className:"size-4"}),r.label]},r.id)})})});xe.displayName="PanelTabsHeader";const uo=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(We,{ref:o,className:g("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...n,children:[e,t.jsx(hs,{asChild:!0,children:t.jsx(ks,{className:"h-4 w-4 opacity-50"})})]}));uo.displayName=We.displayName;const Bt=i.forwardRef(({className:s,...e},n)=>t.jsx(Ve,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(pe,{className:"h-4 w-4"})}));Bt.displayName=Ve.displayName;const Wt=i.forwardRef(({className:s,...e},n)=>t.jsx(qe,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(ue,{className:"h-4 w-4"})}));Wt.displayName=qe.displayName;const po=i.forwardRef(({className:s,children:e,position:n="popper",...o},a)=>t.jsx(xs,{children:t.jsxs(Qe,{ref:a,className:g("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:n,...o,children:[t.jsx(Bt,{}),t.jsx(bs,{className:g("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),t.jsx(Wt,{})]})}));po.displayName=Qe.displayName;const fo=i.forwardRef(({className:s,...e},n)=>t.jsx(Ke,{ref:n,className:g("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...e}));fo.displayName=Ke.displayName;const mo=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Ge,{ref:o,className:g("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(ys,{children:t.jsx(tt,{className:"h-4 w-4"})})}),t.jsx(ws,{children:e})]}));mo.displayName=Ge.displayName;const go=i.forwardRef(({className:s,...e},n)=>t.jsx(Xe,{ref:n,className:g("-mx-1 my-1 h-px bg-muted",s),...e}));go.displayName=Xe.displayName;const Vt=i.forwardRef(({task:s,collapsible:e=!0,defaultExpanded:n=!1,onTaskClick:o,className:a,...l},u)=>{const[f,p]=i.useState(n),r=!!(s.details||s.files&&s.files.length>0),c={pending:st,in_progress:nt,completed:Is}[s.status],d=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},m=()=>{r&&e&&p(!f),o?.(s)};return t.jsxs("div",{ref:u,className:g("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",a),...l,children:[t.jsxs("button",{type:"button",onClick:m,className:g("w-full flex items-center gap-3 px-3 py-2.5 text-left",r&&e&&"cursor-pointer"),disabled:!r&&!e,children:[t.jsx(c,{className:g("w-4 h-4 shrink-0",d(),s.status==="in_progress"&&"animate-spin")}),t.jsx("span",{className:g("flex-1 text-sm font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"font-medium"),children:s.text}),r&&e&&t.jsx(ue,{className:g("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",f&&"rotate-180"),"aria-hidden":"true"})]}),r&&f&&t.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[s.details&&t.jsx("p",{className:"text-sm text-foreground opacity-80 leading-relaxed mb-2",children:s.details}),s.files&&s.files.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),t.jsx("div",{className:"space-y-1",children:s.files.map(x=>t.jsx("div",{className:"text-xs font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:x},x))})]})]})]})});Vt.displayName="Task";const ho=i.forwardRef(({tasks:s,collapsible:e=!0,onTaskClick:n,emptyMessage:o="No tasks yet.",className:a,...l},u)=>t.jsx("div",{ref:u,className:g("space-y-2 max-h-96 overflow-y-auto",a),...l,children:s.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic py-4 text-center",children:o}):s.map(f=>t.jsx(Vt,{task:f,collapsible:e,...n?{onTaskClick:n}:{}},f.id))}));ho.displayName="TaskList";const xo=W("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-none",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),bo=i.forwardRef(({className:s,autoResize:e=!1,maxHeight:n=200,variant:o,...a},l)=>{const u=i.useRef(null),f=i.useCallback(r=>{u.current=r,typeof l=="function"?l(r):l&&(l.current=r)},[l]),p=i.useCallback(()=>{const r=u.current;if(!r||!e)return;r.style.height="auto";const c=Math.min(r.scrollHeight,n);r.style.height=`${c}px`,r.scrollHeight>n?r.style.overflowY="auto":r.style.overflowY="hidden"},[e,n]);return i.useEffect(()=>{p()},[p]),t.jsx("textarea",{className:g(xo({variant:o}),e&&"overflow-y-hidden",s),ref:f,...a})});bo.displayName="Textarea";const B=$("gui");function yo({agentName:s}){const{isExpanded:e,setIsExpanded:n}=me();return t.jsxs("div",{className:"flex lg:hidden items-center gap-2 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx("h1",{className:"text-[20px] font-semibold leading-[1.2] tracking-[-0.4px] text-foreground",children:s}),t.jsx("div",{className:"flex items-center justify-center shrink-0",children:t.jsx(pe,{className:"size-4 rotate-180 text-muted-foreground"})})]}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle menu",onClick:()=>n(!e),children:t.jsx(ot,{className:"size-4 text-muted-foreground"})})]})}function wo({agentName:s,todos:e,showHeader:n}){const{panelSize:o,setPanelSize:a}=ge();return t.jsxs(ht,{className:g("border-b border-border bg-card relative lg:p-0","[border-bottom-width:0.5px]"),children:[t.jsxs("div",{className:"hidden lg:flex items-center gap-2 w-full h-16 py-5 pl-6 pr-4",children:[n&&t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx("h1",{className:"text-[20px] font-semibold leading-[1.2] tracking-[-0.4px] text-foreground",children:s}),t.jsx("div",{className:"flex items-center justify-center shrink-0",children:t.jsx(pe,{className:"size-4 rotate-180 text-muted-foreground"})})]}),!n&&t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle sidebar",onClick:()=>{a(o==="hidden"?"small":"hidden")},children:t.jsx(ot,{className:"size-4 text-muted-foreground"})})]}),t.jsx(yo,{agentName:s}),t.jsx(xt,{className:g("pt-6 pb-8 px-6","border-b border-border bg-card","shadow-[0_4px_16px_0_rgba(0,0,0,0.04)]","[border-bottom-width:0.5px]"),children:t.jsxs(he,{defaultValue:"todo",className:"w-full",children:[t.jsx(xe,{showIcons:!0,visibleTabs:["todo","files"],variant:"default"}),t.jsx(F,{value:"todo",className:"mt-4",children:t.jsx(oe,{todos:e})}),t.jsx(F,{value:"files",className:"mt-4",children:t.jsx(re,{})})]})})]})}function vo({client:s}){const{connectionStatus:e,connect:n,sessionId:o}=Bs(s),{messages:a}=ct(s);Ws(s);const l=S(m=>m.error),[u,f]=i.useState("Agent"),[p,r]=i.useState(typeof window<"u"?window.innerWidth>=1024:!0);i.useEffect(()=>{B.debug("Connection status changed",{status:e}),e==="error"&&l&&B.error("Connection error occurred",{error:l})},[e,l]),i.useEffect(()=>{if(s&&o){const m=s.getCurrentSession();m?.metadata?.agentName&&f(m.metadata.agentName)}},[s,o]),i.useEffect(()=>{const m=window.matchMedia("(min-width: 1024px)"),x=b=>{r(b.matches)};return r(m.matches),m.addEventListener("change",x),()=>{m.removeEventListener("change",x)}},[]);const c=[],d=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:t.jsx(ye,{className:"h-4 w-4"}),category:"model",onSelect:()=>{B.info("User selected Sonnet 4.5 model")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:t.jsx(ye,{className:"h-4 w-4"}),category:"model",onSelect:()=>{B.info("User selected Opus model")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:t.jsx(Rs,{className:"h-4 w-4"}),category:"action",onSelect:()=>{B.info("User opened settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:t.jsx(Ms,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{B.info("User enabled code mode")}}];return t.jsxs(Rt,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[t.jsxs(Mt,{children:[t.jsx(wo,{agentName:u,todos:c,showHeader:a.length>0}),e==="error"&&l&&t.jsx("div",{className:"border-b border-red-500/20 bg-red-500/10 px-6 py-4",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"mb-1 text-sm font-semibold text-red-500",children:"Connection Error"}),t.jsx("p",{className:"whitespace-pre-line text-sm text-foreground",children:l})]}),t.jsx("button",{type:"button",onClick:n,className:"rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600",children:"Retry"})]})}),t.jsxs(Ut,{children:[t.jsx(At,{className:a.length>0?"pt-4":"",children:a.length===0?t.jsx("div",{className:"flex flex-1 items-center px-4",children:t.jsx(mt,{title:u,description:"This agent can help you with your tasks. Start a conversation by typing a message below.",suggestedPrompts:["Help me debug this code","Explain how this works","Create a new feature","Review my changes"],onPromptClick:m=>{B.info("Prompt clicked",{prompt:m})}})}):t.jsx("div",{className:"flex flex-col gap-4 px-4",children:a.map((m,x)=>t.jsx(Ot,{message:m,isLastMessage:x===a.length-1,children:t.jsx($t,{message:m,thinkingDisplayStyle:"collapsible"})},m.id))})}),t.jsx(Dt,{children:t.jsxs(wt,{client:s,children:[t.jsx(kt,{commands:d}),t.jsx(vt,{placeholder:"Type a message or / for commands...",autoFocus:!0}),t.jsxs(jt,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Ct,{}),t.jsx(St,{})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Tt,{}),t.jsx(Nt,{children:t.jsx(Es,{className:"size-4"})})]})]})]})})]})]}),p&&t.jsx(_t,{breakpoint:"lg",children:t.jsxs(he,{defaultValue:"todo",className:"flex flex-col h-full",children:[t.jsx("div",{className:g("border-b border-border bg-card","px-6 py-2 h-16","flex items-center","[border-bottom-width:0.5px]"),children:t.jsx(xe,{showIcons:!0,visibleTabs:["todo","files"],variant:"compact"})}),t.jsx(F,{value:"todo",className:"flex-1 p-4 mt-0",children:t.jsx(oe,{todos:c})}),t.jsx(F,{value:"files",className:"flex-1 p-4 mt-0",children:t.jsx(re,{})})]})})]})}function No(){return"http://localhost:3100"}const Se={agentServerUrl:No()},q=$("gui");function jo(){const[s,e]=i.useState(null),[n,o]=i.useState(null);return i.useEffect(()=>{try{q.info("Initializing ACP client",{serverUrl:Se.agentServerUrl});const a=new Xs({type:"http",options:{baseUrl:Se.agentServerUrl}});return e(a),q.info("ACP client initialized successfully"),()=>{q.debug("Disconnecting ACP client"),a.disconnect().catch(l=>{q.error("Failed to disconnect ACP client",{error:l instanceof Error?l.message:String(l)})})}}catch(a){const l=a instanceof Error?a.message:"Failed to initialize ACP client";o(l),q.error("Failed to initialize ACP client",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0});return}},[]),n?t.jsx("div",{className:"flex items-center justify-center h-screen bg-[var(--color-bg)]",children:t.jsxs("div",{className:"text-center p-8 max-w-md",children:[t.jsx("h1",{className:"text-2xl font-bold text-red-500 mb-4",children:"Initialization Error"}),t.jsx("p",{className:"text-[var(--color-text)] mb-4",children:n}),t.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Failed to initialize the ACP client. Check the console for details."})]})}):t.jsx(vo,{client:s})}const qt=document.getElementById("root");if(!qt)throw new Error("Root element not found");ss.createRoot(qt).render(t.jsx(ns.StrictMode,{children:t.jsx(jo,{})}));
package/dist/index.html CHANGED
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Agent Chat</title>
7
- <script type="module" crossorigin src="/assets/index-CRzODFvQ.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-C0mV9pei.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="/assets/vendor-BxtqxsLB.js">
9
9
  <link rel="modulepreload" crossorigin href="/assets/react-DWDN8s0r.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/acp-sdk-BiGbXeF1.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@townco/gui-template",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -22,14 +22,14 @@
22
22
  "check": "tsc --noEmit"
23
23
  },
24
24
  "dependencies": {
25
- "@townco/ui": "0.1.22",
25
+ "@townco/ui": "0.1.23",
26
26
  "lucide-react": "^0.552.0",
27
27
  "react": "^19.2.0",
28
28
  "react-dom": "^19.2.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@tailwindcss/postcss": "^4.1.17",
32
- "@townco/tsconfig": "0.1.19",
32
+ "@townco/tsconfig": "0.1.20",
33
33
  "@types/react": "^19.2.2",
34
34
  "@types/react-dom": "^19.2.2",
35
35
  "@vitejs/plugin-react": "^5.1.0",
@@ -1,8 +0,0 @@
1
- import{r as l,j as t,P as Gt,e as Jt,f as Kt,M as Xt,h as Yt,a as Zt}from"./react-DWDN8s0r.js";import{L as F,M as T,N as I,O as h,P as Ne,Q as U,R as E,S as D,T as _,U as es,W as Q,X as Z,Y as ts,Z as ss,$ as ns,a0 as os,a1 as B,a2 as rs,a3 as me}from"./vendor-BxtqxsLB.js";import{P as as,a as is}from"./acp-sdk-BiGbXeF1.js";import{S as G,L as je,T as Ce,C as Se,R as ls,O as Te,P as cs,a as ke,b as ds,c as Ie,D as Ee,d as Re,e as Ue,f as us,g as Me,I as Ae,h as De,i as _e,j as Le,k as ze,l as Pe,m as Oe,n as He,o as ps,p as Fe,q as $e,r as fs,s as Be,V as ms,t as Ve,u as We,v as xs,w as hs,x as qe}from"./radix-C1pEulHa.js";import{C as Qe,S as gs,P as bs,M as ys,A as ws,a as Ge,F as Je,D as Ke,X as vs,b as Xe,c as Ye,d as ae,W as Ns,L as Ze,e as js,f as ie,g as Cs,h as Ss,i as et,j as xe,k as Ts,l as ks}from"./icons-B7gv8oe5.js";import{r as Is}from"./markdown-DP5OEpQP.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const u of i.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&o(u)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();const tt=F(["pending","in_progress","completed","failed"]),Es=F(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),st=T({path:h(),line:I().nullable().optional()}),le=T({inputTokens:I().optional(),outputTokens:I().optional(),totalTokens:I().optional()}),nt=Ne("type",[T({type:U("content"),content:T({type:U("text"),text:h()})}),T({type:U("text"),text:h()}),T({type:U("diff"),path:h(),oldText:h(),newText:h(),line:I().nullable().optional()}),T({type:U("terminal"),terminalId:h()})]),ot=T({id:h(),title:h(),kind:Es,status:tt,locations:E(st).optional(),rawInput:D(h(),_()).optional(),rawOutput:D(h(),_()).optional(),content:E(nt).optional(),error:h().optional(),startedAt:I().optional(),completedAt:I().optional(),tokenUsage:le.optional()}),Rs=T({id:h(),status:tt.optional(),locations:E(st).optional(),rawOutput:D(h(),_()).optional(),content:E(nt).optional(),error:h().optional(),completedAt:I().optional(),tokenUsage:le.optional()});function he(s,e){return{...s,status:e.status??s.status,locations:e.locations??s.locations,rawOutput:e.rawOutput??s.rawOutput,content:e.content?[...s.content??[],...e.content]:s.content,error:e.error??s.error,completedAt:e.completedAt??s.completedAt,tokenUsage:e.tokenUsage??s.tokenUsage}}const S=es(s=>({connectionStatus:"disconnected",sessionId:null,error:null,messages:[],isStreaming:!1,streamingStartTime:null,toolCalls:{},totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},currentModel:"claude-sonnet-4-5-20250929",tokenDisplayMode:"context",input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:e=>s({connectionStatus:e}),setSessionId:e=>s({sessionId:e}),setError:e=>s({error:e}),addMessage:e=>s(n=>({messages:[...n.messages,e]})),updateMessage:(e,n)=>s(o=>{const a=o.messages.find(r=>r.id===e);let i=o.totalBilled,u=o.currentContext,f=n;if(n.tokenUsage){const r=a?.tokenUsage;console.error("DEBUG updateMessage: incoming tokenUsage:",JSON.stringify(n.tokenUsage),"existing:",JSON.stringify(r));const c={inputTokens:Math.max(n.tokenUsage.inputTokens??0,r?.inputTokens??0),outputTokens:Math.max(n.tokenUsage.outputTokens??0,r?.outputTokens??0),totalTokens:Math.max(n.tokenUsage.inputTokens??0,r?.inputTokens??0)+Math.max(n.tokenUsage.outputTokens??0,r?.outputTokens??0)};console.error("DEBUG updateMessage: merged tokenUsage:",JSON.stringify(c)),f={...n,tokenUsage:c};const d=c.inputTokens-(r?.inputTokens??0),m=c.outputTokens-(r?.outputTokens??0),g=c.totalTokens-(r?.totalTokens??0);i={inputTokens:o.totalBilled.inputTokens+d,outputTokens:o.totalBilled.outputTokens+m,totalTokens:o.totalBilled.totalTokens+g},u={inputTokens:c.inputTokens,outputTokens:o.currentContext.outputTokens+m,totalTokens:c.totalTokens}}const p=o.messages.map(r=>r.id===e?{...r,...f}:r);if(n.tokenUsage){const r=a?.tokenUsage,c=f.tokenUsage,d=(c.inputTokens??0)-(r?.inputTokens??0),m=(c.outputTokens??0)-(r?.outputTokens??0),g=(c.totalTokens??0)-(r?.totalTokens??0),b=p.filter(w=>w.tokenUsage).map(w=>({id:w.id,role:w.role,tokens:w.tokenUsage})),y=p.reduce((w,v)=>({inputTokens:w.inputTokens+(v.tokenUsage?.inputTokens??0),outputTokens:w.outputTokens+(v.tokenUsage?.outputTokens??0),totalTokens:w.totalTokens+(v.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),j=y.inputTokens===i.inputTokens&&y.outputTokens===i.outputTokens&&y.totalTokens===i.totalTokens;console.error("DEBUG updateMessage: tokenUsage update",JSON.stringify({messageId:e,updates:n.tokenUsage,existing:r,messageMax:c,delta:{inputDelta:d,outputDelta:m,totalDelta:g},totalBilled:i,currentContext:u,actualSum:y,billedCorrect:j?"✅":"❌",messageCount:p.length,messagesWithTokens:b.length,breakdown:b}))}return{messages:p,totalBilled:i,currentContext:u}}),clearMessages:()=>s({messages:[]}),setIsStreaming:e=>s({isStreaming:e}),setStreamingStartTime:e=>s({streamingStartTime:e}),addToolCall:(e,n)=>s(o=>({toolCalls:{...o.toolCalls,[e]:[...o.toolCalls[e]||[],n]}})),addToolCallToCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(u=>u.role==="assistant");if(o===-1)return console.warn("No assistant message found to add tool call to"),n;const a=[...n.messages],i=a[o];return i?(a[o]={...i,toolCalls:[...i.toolCalls||[],e]},{messages:a}):n}),updateToolCallInCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(c=>c.role==="assistant");if(o===-1)return console.warn("No assistant message found to update tool call in"),n;const a=[...n.messages],i=a[o];if(!i)return n;const u=i.toolCalls||[],f=u.findIndex(c=>c.id===e.id);if(f===-1)return console.warn(`Tool call ${e.id} not found in message`),n;const p=u[f];if(!p)return n;const r=[...u];return r[f]=he(p,e),a[o]={...i,toolCalls:r},{messages:a}}),updateToolCall:(e,n)=>s(o=>{const a=o.toolCalls[e]||[],i=a.findIndex(p=>p.id===n.id);if(i===-1)return o;const u=a[i];if(!u)return o;const f=[...a];return f[i]=he(u,n),{toolCalls:{...o.toolCalls,[e]:f}}}),setInputValue:e=>s(n=>({input:{...n.input,value:e}})),setInputSubmitting:e=>s(n=>({input:{...n.input,isSubmitting:e}})),addFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,e]}})),removeFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((o,a)=>a!==e)}})),clearInput:()=>s(e=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}})),addTokenUsage:e=>s(n=>({totalBilled:{inputTokens:n.totalBilled.inputTokens+(e.inputTokens??0),outputTokens:n.totalBilled.outputTokens+(e.outputTokens??0),totalTokens:n.totalBilled.totalTokens+(e.totalTokens??0)},currentContext:{inputTokens:e.inputTokens??n.currentContext.inputTokens,outputTokens:n.currentContext.outputTokens+(e.outputTokens??0),totalTokens:(e.inputTokens??n.currentContext.inputTokens)+(n.currentContext.outputTokens+(e.outputTokens??0))}})),setCurrentModel:e=>s({currentModel:e}),resetTokens:()=>s({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0}}),cycleTokenDisplayMode:()=>s(e=>{const n=["context","input","output"],a=(n.indexOf(e.tokenDisplayMode)+1)%n.length,i=n[a];return i?{tokenDisplayMode:i}:e})}));function rt(s){const e=S(c=>c.messages),n=S(c=>c.isStreaming),o=S(c=>c.sessionId),a=S(c=>c.setIsStreaming),i=S(c=>c.setStreamingStartTime),u=S(c=>c.addMessage),f=S(c=>c.updateMessage),p=S(c=>c.setError),r=l.useCallback(async c=>{if(!s){console.error("❌ No client available"),p("No client available");return}if(!o){console.error("❌ No active session"),p("No active session");return}try{const d=Date.now();a(!0),i(d);const m={id:`msg_${Date.now()}_user`,role:"user",content:c,timestamp:new Date().toISOString(),isStreaming:!1};u(m);const g=`msg_${Date.now()}_assistant`,b={id:g,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:d};u(b);const y=e.filter(N=>N.role!=="system").map(N=>`${N.role==="user"?"Human":"Assistant"}: ${N.content}`).join(`
2
-
3
- `),j=y?`${y}
4
-
5
- Human: ${c}`:c,w=s.receiveMessages();s.sendMessage(j,o).catch(N=>{const M=N instanceof Error?N.message:String(N);p(M),a(!1),i(null)});let v="";for await(const N of w)if(N.tokenUsage&&console.error("DEBUG use-chat-messages: chunk.tokenUsage:",JSON.stringify(N.tokenUsage)),N.isComplete){f(g,{content:v,isStreaming:!1,streamingStartTime:void 0,...N.tokenUsage?{tokenUsage:N.tokenUsage}:{}}),a(!1),i(null);break}else N.contentDelta.type==="text"&&(v+=N.contentDelta.text,f(g,{content:v,...N.tokenUsage?{tokenUsage:N.tokenUsage}:{}}),await new Promise(M=>setTimeout(M,16)))}catch(d){const m=d instanceof Error?d.message:String(d);p(m),a(!1),i(null)}},[s,o,e,u,f,a,i,p]);return{messages:e,isStreaming:n,sendMessage:r}}function Us(s){const e=S(d=>d.input),n=S(d=>d.setInputValue),o=S(d=>d.setInputSubmitting),a=S(d=>d.addFileAttachment),i=S(d=>d.removeFileAttachment),{sendMessage:u}=rt(s),f=l.useCallback(d=>{n(d)},[n]),p=l.useCallback(async()=>{if(!e.value.trim()||e.isSubmitting)return;const d=e.value;n(""),o(!0);try{await u(d)}catch(m){console.error("Failed to send message:",m)}finally{o(!1)}},[e,n,o,u]),r=l.useCallback(d=>{a(d)},[a]),c=l.useCallback(d=>{i(d)},[i]);return{value:e.value,isSubmitting:e.isSubmitting,attachedFiles:e.attachedFiles,onChange:f,onSubmit:p,onAttachFile:r,onRemoveFile:c}}function Ms(s){const e=S(d=>d.connectionStatus),n=S(d=>d.sessionId),o=S(d=>d.setConnectionStatus),a=S(d=>d.setSessionId),i=S(d=>d.setError),u=S(d=>d.clearMessages),f=S(d=>d.resetTokens),p=l.useCallback(async()=>{if(!s){i("No client available");return}try{o("connecting"),i(null),await s.connect(),o("connected")}catch(d){console.log(d);const m=d instanceof Error?d.message:String(d);i(m),o("error")}},[s,o,i]),r=l.useCallback(async()=>{if(!s){i("No client available");return}try{const d=await s.startSession();a(d),u(),f()}catch(d){const m=d instanceof Error?d.message:String(d);i(m)}},[s,a,i,u,f]),c=l.useCallback(async()=>{if(s)try{await s.disconnect(),o("disconnected"),a(null)}catch(d){const m=d instanceof Error?d.message:String(d);i(m)}},[s,o,a,i]);return l.useEffect(()=>{s&&e==="disconnected"&&p()},[s,e,p]),l.useEffect(()=>{e==="connected"&&!n&&r()},[e,n,r]),{connectionStatus:e,sessionId:n,connect:p,startSession:r,disconnect:c}}function As(s){const e=S(u=>u.toolCalls),n=S(u=>u.addToolCall),o=S(u=>u.updateToolCall),a=S(u=>u.addToolCallToCurrentMessage),i=S(u=>u.updateToolCallInCurrentMessage);return l.useEffect(()=>{if(!s)return;const u=s.onSessionUpdate(f=>{f.type==="tool_call"?(n(f.sessionId,f.toolCall),a(f.toolCall)):f.type==="tool_call_update"&&(o(f.sessionId,f.toolCallUpdate),i(f.toolCallUpdate))});return()=>{u()}},[s,n,o,a,i]),{toolCalls:e,getToolCallsForSession:u=>{const f=e[u];return f&&f.length>0?f:Object.values(e).flat()}}}const ge={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},Ds={trace:"color: #6B7280",debug:"color: #3B82F6; font-weight: bold",info:"color: #10B981; font-weight: bold",warn:"color: #F59E0B; font-weight: bold",error:"color: #EF4444; font-weight: bold",fatal:"color: #DC2626; font-weight: bold; background: #FEE2E2"};class _s{service;minLevel;constructor(e,n="debug"){this.service=e,this.minLevel=n,typeof process<"u"&&(this.minLevel="info")}shouldLog(e){return ge[e]>=ge[this.minLevel]}log(e,n,o){if(!this.shouldLog(e))return;const a={timestamp:new Date().toISOString(),level:e,service:this.service,message:n,...o&&{metadata:o}},i=Ds[e],u=e.toUpperCase().padEnd(5);if(typeof console<"u"){const f=`%c[${a.timestamp}] [${this.service}] [${u}]`,p=o?`${n} %o`:n;switch(e){case"trace":case"debug":case"info":console.log(f,i,p,...o?[o]:[]);break;case"warn":console.warn(f,i,p,...o?[o]:[]);break;case"error":case"fatal":console.error(f,i,p,...o?[o]:[]);break}}(e==="fatal"||e==="error")&&console.debug("Structured log:",JSON.stringify(a))}trace(e,n){this.log("trace",e,n)}debug(e,n){this.log("debug",e,n)}info(e,n){this.log("info",e,n)}warn(e,n){this.log("warn",e,n)}error(e,n){this.log("error",e,n)}fatal(e,n){this.log("fatal",e,n)}}function ce(s,e="debug"){return new _s(s,e)}const Ls=T({id:h(),role:F(["user","assistant","system"]),content:h(),timestamp:Z(),isStreaming:Q().default(!1),streamingStartTime:I().optional(),metadata:D(h(),_()).optional(),toolCalls:E(ot).optional(),tokenUsage:le.optional()}),zs=T({value:h(),isSubmitting:Q(),attachedFiles:E(T({name:h(),path:h(),size:I(),mimeType:h()}))});T({sessionId:h().nullable(),isConnected:Q(),isStreaming:Q(),messages:E(Ls),input:zs,error:h().nullable()});F(["disconnected","connecting","connected","error"]);const k=ce("http-transport");class Ps{connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;messageQueue=[];currentSessionId=null;chunkResolvers=[];streamComplete=!1;sseAbortController=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;reconnecting=!1;abortController=null;options;constructor(e){this.options={...e,baseUrl:e.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const e={protocolVersion:as,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",e);k.info("ACP connection initialized",{initResponse:n});const o={cwd:"/",mcpServers:[]},a=await this.sendRpcRequest("session/new",o);this.currentSessionId=a.sessionId,k.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(e){this.connected=!1;const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async disconnect(){if(this.connected)try{this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.connected=!1,this.currentSessionId=null,this.messageQueue=[],this.chunkResolvers=[],this.streamComplete=!1,this.reconnecting=!1,this.reconnectAttempts=0}catch(e){const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async send(e){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");try{this.streamComplete=!1,this.messageQueue=[];const n=e.content.filter(u=>u.type==="text").map(u=>u.text).join(`
6
- `),o={sessionId:this.currentSessionId,prompt:[{type:"text",text:n}]},a=await this.sendRpcRequest("session/prompt",o);k.debug("Prompt sent",{promptResponse:a}),this.streamComplete=!0;const i=this.chunkResolvers.shift();i?i({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(n){this.streamComplete=!0;const o=n instanceof Error?n:new Error(String(n));throw this.notifyError(o),o}}async*receive(){for(;!this.streamComplete;)if(this.messageQueue.length>0){const e=this.messageQueue.shift();if(e&&(yield e,e.isComplete))return}else{const e=await new Promise(n=>{this.chunkResolvers.push(n)});if(e.isComplete){yield e;return}else yield e}for(;this.messageQueue.length>0;){const e=this.messageQueue.shift();e&&(yield e)}yield{id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}async sendRpcRequest(e,n){const a={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:n},i={"Content-Type":"application/json",...this.options.headers},u=this.options.timeout??600*1e3,f=new AbortController,p=setTimeout(()=>f.abort(),u);try{const r=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(a),signal:f.signal});if(clearTimeout(p),!r.ok){const d=await r.text();throw new Error(`HTTP ${r.status}: ${d}`)}const c=await r.json();if(c.error)throw new Error(`ACP error: ${c.error.message||JSON.stringify(c.error)}`);return c.result||c}catch(r){throw clearTimeout(p),r instanceof Error&&r.name==="AbortError"?new Error(`Request timeout after ${u}ms`):r}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const e=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const o=await fetch(e,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!o.ok)throw new Error(`SSE connection failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response body is null");k.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const a=o.body.getReader(),i=new TextDecoder;let u="";(async()=>{try{for(;;){const{done:f,value:p}=await a.read();if(f){k.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}u+=i.decode(p,{stream:!0});const r=u.split(`
7
- `);u=r.pop()||"";let c={event:"message",data:""};for(const d of r)d.startsWith("event:")?c.event=d.substring(6).trim():d.startsWith("data:")?c.data=d.substring(5).trim():d===""&&(c.event==="message"&&c.data&&this.handleSSEMessage(c.data),c={event:"message",data:""})}}catch(f){if(f instanceof Error&&f.name==="AbortError"){k.debug("SSE stream aborted");return}k.error("Error reading SSE stream",{error:f}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(o){throw k.error("SSE connection error",{error:o}),o}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const n=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(n),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);k.debug("SSE reconnecting",{delay:e,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(n=>setTimeout(n,e));try{await this.connectSSE(),k.info("SSE reconnected successfully"),this.reconnecting=!1}catch(n){k.error("SSE reconnection failed",{error:n}),this.reconnecting=!1}}handleSSEMessage(e){try{const n=JSON.parse(e);k.debug("Received SSE message",{message:n});const o=is.safeParse(n);if(!o.success){k.error("Invalid ACP message from SSE",{issues:o.error.issues});return}const a=o.data;k.debug("Parsed ACP message",{method:"method"in a?a.method:"(no method)"}),"method"in a&&a.method==="session/update"&&(k.debug("Received session/update notification"),"params"in a&&a.params&&(k.debug("Calling handleSessionNotification",{params:a.params}),this.handleSessionNotification(a.params)))}catch(n){k.error("Error parsing SSE message",{error:n}),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(e){k.debug("handleSessionNotification called",{params:e});const o=e.update,a=this.currentSessionId||e.sessionId;if(k.debug("Update session type",{sessionUpdate:o?.sessionUpdate}),o?.sessionUpdate==="tool_call"){k.debug("Tool call notification",{tokenUsage:o.tokenUsage});const i=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,u={id:o.toolCallId??"",title:o.title??"",kind:o.kind||"other",status:o.status||"pending",locations:o.locations,rawInput:o.rawInput,tokenUsage:o.tokenUsage,content:o.content?.map(p=>{if(typeof p!="object"||p===null)return{type:"text",text:""};const r=p;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const c=r.content;if(c.type==="text")return{type:"content",content:{type:"text",text:typeof c.text=="string"?c.text:""}}}return r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:r.type==="diff"?{type:"diff",path:typeof r.path=="string"?r.path:"",oldText:typeof r.oldText=="string"?r.oldText:"",newText:typeof r.newText=="string"?r.newText:"",line:typeof r.line=="number"?r.line:null}:r.type==="terminal"?{type:"terminal",terminalId:typeof r.terminalId=="string"?r.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now()},f={type:"tool_call",sessionId:a,status:"active",toolCall:u,messageId:i};this.notifySessionUpdate(f)}else if(o?.sessionUpdate==="tool_call_update"){const i=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,u={id:o.toolCallId??"",status:o.status,locations:o.locations,rawOutput:o.rawOutput,tokenUsage:o.tokenUsage,content:o.content?.map(p=>{if(typeof p!="object"||p===null)return{type:"text",text:""};const r=p;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const c=r.content;if(c.type==="text")return{type:"content",content:{type:"text",text:typeof c.text=="string"?c.text:""}}}return r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:r.type==="diff"?{type:"diff",path:typeof r.path=="string"?r.path:"",oldText:typeof r.oldText=="string"?r.oldText:"",newText:typeof r.newText=="string"?r.newText:"",line:typeof r.line=="number"?r.line:null}:r.type==="terminal"?{type:"terminal",terminalId:typeof r.terminalId=="string"?r.terminalId:""}:{type:"text",text:""}}),error:o.error,completedAt:o.status==="completed"||o.status==="failed"?Date.now():void 0},f={type:"tool_call_update",sessionId:a,status:"active",toolCallUpdate:u,messageId:i};k.debug("Notifying tool_call_update session update",{sessionUpdate:f}),this.notifySessionUpdate(f)}else if(o&&"sessionUpdate"in o&&o.sessionUpdate==="tool_output"){const i=o,u=i._meta&&typeof i._meta=="object"&&"messageId"in i._meta?String(i._meta.messageId):void 0,f={id:i.toolCallId??"",rawOutput:i.rawOutput,content:i.content?.map(r=>{if(typeof r!="object"||r===null)return{type:"text",text:""};const c=r;if(c.type==="content"&&typeof c.content=="object"&&c.content!==null){const d=c.content;if(d.type==="text")return{type:"content",content:{type:"text",text:typeof d.text=="string"?d.text:""}}}return c.type==="text"?{type:"text",text:typeof c.text=="string"?c.text:""}:c.type==="diff"?{type:"diff",path:typeof c.path=="string"?c.path:"",oldText:typeof c.oldText=="string"?c.oldText:"",newText:typeof c.newText=="string"?c.newText:"",line:typeof c.line=="number"?c.line:null}:c.type==="terminal"?{type:"terminal",terminalId:typeof c.terminalId=="string"?c.terminalId:""}:{type:"text",text:""}})},p={type:"tool_call_update",sessionId:a,status:"active",toolCallUpdate:f,messageId:u};k.debug("Notifying tool_output as tool_call_update",{sessionUpdate:p}),this.notifySessionUpdate(p)}else if(o?.sessionUpdate==="agent_message_chunk"){const i={type:"generic",sessionId:a,status:"active"},u=o._meta&&typeof o._meta=="object"&&"tokenUsage"in o._meta?o._meta.tokenUsage:void 0;k.debug("Agent message chunk",{tokenUsage:u});const f=o.content;if(f&&typeof f=="object"){const p=f;let r=null;if(p.type==="text"&&typeof p.text=="string"&&(r={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:p.text},tokenUsage:u,isComplete:!1}),r){const c=this.chunkResolvers.shift();c?c(r):this.messageQueue.push(r)}}this.notifySessionUpdate(i)}else{const i={type:"generic",sessionId:a,status:"active"};this.notifySessionUpdate(i)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(e){for(const n of this.sessionUpdateCallbacks)try{n(e)}catch(o){k.error("Error in session update callback",{error:o})}}notifyError(e){for(const n of this.errorCallbacks)try{n(e)}catch(o){k.error("Error in error callback",{error:o})}}}class Os{constructor(){throw new Error("StdioTransport is not available in the browser. Use HttpTransport or WebSocketTransport instead.")}async connect(){throw new Error("StdioTransport not available in browser")}async disconnect(){}async send(){throw new Error("StdioTransport not available in browser")}async*receive(){throw new Error("StdioTransport not available in browser")}isConnected(){return!1}onSessionUpdate(){return()=>{}}onError(){return()=>{}}}class Hs{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(e){}async connect(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async disconnect(){this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}async send(e){throw!this.connected||!this.ws?new Error("Transport not connected"):new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async*receive(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}}class Fs{config;transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;constructor(e){this.config=e,this.transport=this.createTransport(),this.setupTransportListeners(),e.autoConnect&&this.connect().catch(n=>{console.error("Failed to auto-connect:",n)})}async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(e){const n=this.generateSessionId(),o=new Date().toISOString(),a={id:n,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};return this.sessions.set(n,a),this.currentSessionId=n,this.updateSessionStatus(n,"connected"),n}async sendMessage(e,n){const o=n||this.currentSessionId;if(!o)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(o);if(!a)throw new Error(`Session ${o} not found`);const i={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};a.messages.push(i),this.updateSessionStatus(o,"active"),await this.transport.send(i)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(e){return this.sessions.get(e)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(e){return this.sessionUpdateHandlers.add(e),()=>{this.sessionUpdateHandlers.delete(e)}}onError(e){return this.errorHandlers.add(e),()=>{this.errorHandlers.delete(e)}}createTransport(){switch(this.config.type){case"stdio":return new Os(this.config.options);case"http":return new Ps(this.config.options);case"websocket":return new Hs(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(e=>{this.handleSessionUpdate(e)}),this.transport.onError(e=>{this.handleError(e)})}handleSessionUpdate(e){if(e.sessionId){const n=this.sessions.get(e.sessionId);n&&(e.status&&(n.status=e.status),e.message&&n.messages.push(e.message),e.error&&(n.error=e.error))}for(const n of this.sessionUpdateHandlers)try{n(e)}catch(o){console.error("Error in session update handler:",o)}}handleError(e){for(const n of this.errorHandlers)try{n(e)}catch(o){console.error("Error in error handler:",o)}}updateSessionStatus(e,n){const o=this.sessions.get(e);o&&(o.status=n,this.handleSessionUpdate({sessionId:e,status:n}))}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}const $s=T({name:h(),description:h().optional(),parameters:D(h(),_()).optional()}),Bs=T({name:h(),description:h(),parameters:D(h(),_()),required:E(h()).optional()}),Vs=T({name:h(),version:h().optional(),description:h().optional(),author:h().optional(),capabilities:E($s).optional(),tools:E(Bs).optional(),supportedFormats:E(h()).optional()}),Ws=F(["initializing","ready","busy","error","terminated"]);T({status:Ws,info:Vs.optional(),pid:I().optional(),error:h().optional(),uptime:I().optional()});const at=F(["user","assistant","system","tool"]),qs=F(["text","image","file","tool_call","tool_result"]),J=T({type:qs}),Qs=J.extend({type:U("text"),text:h()}),Gs=J.extend({type:U("image"),url:h().url().optional(),data:h().optional(),mimeType:h().optional()}),Js=J.extend({type:U("file"),name:h(),path:h().optional(),url:h().url().optional(),mimeType:h(),size:I().optional()}),Ks=J.extend({type:U("tool_call"),id:h(),name:h(),arguments:D(h(),_())}),Xs=J.extend({type:U("tool_result"),callId:h(),result:_(),error:h().optional()}),it=Ne("type",[Qs,Gs,Js,Ks,Xs]),lt=T({id:h(),role:at,content:E(it),timestamp:Z(),metadata:D(h(),_()).optional()});T({id:h(),role:at,contentDelta:it,isComplete:Q(),tokenUsage:T({inputTokens:I().optional(),outputTokens:I().optional(),totalTokens:I().optional()}).optional()});const ct=F(["idle","connecting","connected","active","streaming","error","disconnected"]),Ys=T({agentPath:h(),agentArgs:E(h()).optional(),environment:D(h(),h()).optional(),workingDirectory:h().optional(),timeout:I().optional()}),Zs=T({agentName:h().optional(),agentVersion:h().optional(),capabilities:E(h()).optional(),startedAt:Z(),lastActivityAt:Z().optional()});T({id:h(),status:ct,config:Ys,metadata:Zs.optional(),messages:E(lt),error:h().optional()});const ee=T({sessionId:h(),status:ct.optional(),message:lt.optional(),error:h().optional()}),en=ee.extend({type:U("tool_call"),toolCall:ot,messageId:h().optional()}),tn=ee.extend({type:U("tool_call_update"),toolCallUpdate:Rs,messageId:h().optional()}),sn=ee.extend({type:U("tool_output"),toolOutput:T({id:h(),content:E(ts()).optional(),rawOutput:D(h(),_()).optional()}),messageId:h().optional()}),nn=ee.extend({type:U("generic").optional()});ss([en,tn,sn,nn]);function x(...s){return ns(os(s))}const on=B("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 cursor-pointer",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),K=l.forwardRef(({className:s,variant:e,size:n,asChild:o=!1,...a},i)=>{const u=o?G:"button";return t.jsx(u,{className:x(on({variant:e,size:n,className:s})),ref:i,...a})});K.displayName="Button";const rn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:x("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));rn.displayName="Card";const an=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:x("flex flex-col space-y-1.5 p-6",s),...e}));an.displayName="CardHeader";const ln=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:x("text-2xl font-semibold leading-none tracking-tight",s),...e}));ln.displayName="CardTitle";const cn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:x("text-sm text-muted-foreground",s),...e}));cn.displayName="CardDescription";const dn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:x("p-6 pt-0",s),...e}));dn.displayName="CardContent";const un=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:x("flex items-center p-6 pt-0",s),...e}));un.displayName="CardFooter";const dt=l.forwardRef(({title:s,description:e,guideUrl:n,guideText:o="Guide",suggestedPrompts:a=[],onPromptClick:i,onGuideClick:u,className:f,...p},r)=>{const c=g=>{i?.(g)},d=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),u?.()},m=[];for(let g=0;g<a.length;g+=2)m.push(a.slice(g,g+2));return t.jsxs("div",{ref:r,className:x("flex flex-col items-start gap-6",f),...p,children:[t.jsx("h3",{className:"text-heading-3 text-text-primary hidden lg:block",children:s}),t.jsx("p",{className:"text-subheading text-text-secondary max-w-prose",children:e}),(n||u)&&t.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm font-medium leading-normal text-text-primary",children:o}),t.jsx(Qe,{className:"size-4 text-text-primary"})]}),a.length>0&&t.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[t.jsx("p",{className:"text-label text-text-tertiary",children:"Suggested Prompts"}),t.jsx("div",{className:"flex flex-col gap-2.5",children:m.map(g=>t.jsx("div",{className:"flex gap-2.5 items-center",children:g.map(b=>t.jsx("button",{type:"button",onClick:()=>c(b),className:"flex-1 flex items-start gap-2 p-3 bg-secondary hover:bg-secondary/80 rounded-2xl transition-colors min-w-0",children:t.jsx("span",{className:"text-base font-normal leading-normal text-text-tertiary truncate",children:b})},b))},g.join("-")))})]})]})});dt.displayName="ChatEmptyState";const ut=l.createContext(void 0),de=()=>{const s=l.useContext(ut);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},pt=l.forwardRef(({defaultExpanded:s=!1,expanded:e,onExpandedChange:n,className:o,children:a,...i},u)=>{const[f,p]=l.useState(s),r=e??f,c=l.useCallback(b=>{p(b),n?.(b)},[n]),d=l.Children.toArray(a),m=d.find(b=>l.isValidElement(b)&&typeof b.type=="function"&&b.type.displayName==="ChatHeader.ExpandablePanel"),g=d.filter(b=>b!==m);return t.jsxs(ut.Provider,{value:{isExpanded:r,setIsExpanded:c},children:[t.jsx("div",{ref:u,className:x("flex items-center justify-between px-6 py-4",o),...i,children:g}),m]})});pt.displayName="ChatHeader.Root";const pn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("h1",{ref:o,className:x("m-0 text-xl font-semibold",s),...n,children:e}));pn.displayName="ChatHeader.Title";const fn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("flex items-center gap-3",s),...n,children:e}));fn.displayName="ChatHeader.Actions";const mn=s=>{switch(s){case"connected":return"bg-green-500";case"connecting":return"bg-yellow-500";case"error":return"bg-red-500";default:return"bg-gray-500"}},xn=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},hn=l.forwardRef(({status:s,statusText:e,className:n,...o},a)=>{const i=e??xn(s),u=mn(s);return t.jsxs("div",{ref:a,className:x("flex items-center gap-2",n),...o,children:[t.jsx("div",{className:x("h-2 w-2 rounded-full",u)}),t.jsx("span",{className:"text-sm text-muted-foreground",children:i})]})});hn.displayName="ChatHeader.StatusIndicator";const gn=l.forwardRef(({icon:s,className:e,children:n,onClick:o,...a},i)=>{const{isExpanded:u,setIsExpanded:f}=de(),p=r=>{f(!u),o?.(r)};return t.jsxs("button",{ref:i,type:"button",onClick:p,className:x("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":u?"Collapse header":"Expand header",...a,children:[s&&t.jsx("div",{className:x("transition-transform duration-200",u&&"rotate-180"),children:s}),n]})});gn.displayName="ChatHeader.Toggle";const ft=l.forwardRef(({className:s,children:e,...n},o)=>{const{isExpanded:a}=de();return a?t.jsx("div",{ref:o,className:x("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",s),...n,children:e}):null});ft.displayName="ChatHeader.ExpandablePanel";const mt=l.forwardRef(({commands:s=[],showCommandMenu:e,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:a,setMenuItemCount:i,triggerCounter:u,onChange:f,className:p,...r},c)=>{const d=l.useCallback((g,b)=>{const y=g.toLowerCase(),j=b.toLowerCase();if(!b)return 1;if(y.includes(j))return 1-j.length/y.length;let w=0;for(let v=0;v<y.length&&w<j.length;v++)y[v]===j[w]&&w++;return w===j.length?.5-w/y.length:0},[]),m=l.useMemo(()=>s.map(g=>({...g,score:Math.max(d(g.label,n),g.description?d(g.description,n):0)})).filter(g=>g.score>0).sort((g,b)=>b.score-g.score),[s,n,d]);return l.useEffect(()=>{i(m.length)},[m.length,i]),l.useEffect(()=>{a(0)},[a]),l.useEffect(()=>{u>0&&m[o]&&(m[o].onSelect(),f(""))},[u,m,o,f]),!e||m.length===0?null:t.jsxs("div",{ref:c,className:x("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",p),...r,children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),t.jsx("div",{className:"max-h-64 overflow-y-auto",children:m.map((g,b)=>t.jsxs("button",{type:"button",onClick:()=>g.onSelect(),className:x("w-full rounded-sm px-2 py-2 text-left text-sm transition-colors","flex items-start gap-2","hover:bg-muted",b===o&&"bg-muted"),children:[g.icon&&t.jsx("span",{className:"shrink-0 mt-0.5",children:g.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-medium",children:g.label}),g.description&&t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:g.description})]})]},g.id))})]})});mt.displayName="ChatInputCommandMenu";const xt=l.createContext(void 0),te=()=>{const s=l.useContext(xt);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},ht=l.forwardRef(({client:s,value:e,onChange:n,onSubmit:o,disabled:a=!1,isSubmitting:i,submitOnEnter:u=!0,className:f,children:p,...r},c)=>{const d=l.useRef(null),m=Us(s??null),g=S(R=>R.isStreaming),b=m?m.value:e||"",y=m?m.onChange:n||(()=>{}),j=m?m.onSubmit:o||(async()=>{}),w=m?m.isSubmitting||g:i||!1,[v,N]=l.useState(!1),[M,L]=l.useState(""),[O,C]=l.useState(0),[A,z]=l.useState(0),[oe,re]=l.useState(0),Bt=l.useCallback(()=>{re(R=>R+1)},[]),Vt=async R=>{R.preventDefault(),b.trim()&&!w&&!a&&(await j(),setTimeout(()=>{d.current?.focus()},0))},Wt=R=>{const P=R.target;!(P.tagName==="BUTTON"||P.tagName==="INPUT"||P.tagName==="TEXTAREA"||P.closest("button"))&&d.current&&d.current.focus()},qt=R=>{const P=R.target;!(P.tagName==="BUTTON"||P.tagName==="INPUT"||P.tagName==="TEXTAREA"||P.closest("button"))&&R.key===" "&&(R.preventDefault(),d.current&&d.current.focus())};return l.useEffect(()=>{const R=document.querySelector('textarea[name="chat-input"]');R&&d.current!==R&&(d.current=R)},[]),l.useEffect(()=>{!b&&d.current&&(d.current.style.height="auto",d.current.style.overflowY="hidden")},[b]),t.jsx(xt.Provider,{value:{value:b,onChange:y,onSubmit:j,disabled:a,isSubmitting:w,submitOnEnter:u,showCommandMenu:v,setShowCommandMenu:N,commandMenuQuery:M,setCommandMenuQuery:L,selectedMenuIndex:O,setSelectedMenuIndex:C,menuItemCount:A,setMenuItemCount:z,triggerMenuSelect:Bt,triggerCounter:oe},children:t.jsx("form",{ref:c,onSubmit:Vt,onClick:Wt,onKeyDown:qt,className:x("relative w-full divide-y rounded-xl border bg-background shadow-md",f),...r,children:p})})});ht.displayName="ChatInput.Root";const gt=l.forwardRef(({asChild:s=!1,className:e,onKeyDown:n,children:o,...a},i)=>{const{value:u,onChange:f,onSubmit:p,disabled:r,isSubmitting:c,submitOnEnter:d,showCommandMenu:m,setShowCommandMenu:g,setCommandMenuQuery:b,setSelectedMenuIndex:y,menuItemCount:j,triggerMenuSelect:w}=te(),v=l.useRef(null),O={ref:l.useCallback(C=>{v.current=C,typeof i=="function"?i(C):i&&(i.current=C)},[i]),name:"chat-input",value:u,onChange:C=>{const A=C.target.value;if(f(A),A.startsWith("/")&&!A.includes(`
8
- `)){g(!0);const re=A.slice(1);b(re)}else g(!1),b("");const z=v.current;if(!z)return;z.style.height="auto";const oe=Math.min(z.scrollHeight,164);z.style.height=`${oe}px`,z.scrollHeight>164?z.style.overflowY="auto":z.style.overflowY="hidden"},onKeyDown:C=>{if(m&&j>0){if(C.key==="ArrowDown"){C.preventDefault(),y(A=>(A+1)%j);return}else if(C.key==="ArrowUp"){C.preventDefault(),y(A=>(A-1+j)%j);return}else if(C.key==="Enter"&&!C.shiftKey){C.preventDefault(),w();return}else if(C.key==="Escape"){C.preventDefault(),g(!1),b("");return}}d&&C.key==="Enter"&&!C.shiftKey&&(u.trim()&&!c&&!r?(C.preventDefault(),p()):(c||r)&&C.preventDefault()),n?.(C)},disabled:r,...a};return s&&l.isValidElement(o)?l.cloneElement(o,O):t.jsx("textarea",{...O,className:x("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 field-sizing-content max-h-[6lh]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});gt.displayName="ChatInput.Field";const bt=l.forwardRef(({asChild:s=!1,className:e,disabled:n,children:o,...a},i)=>{const{value:u,disabled:f,isSubmitting:p}=te(),r=n||f||p||!u.trim(),c=s?G:K;return t.jsx(c,{ref:i,type:"submit",disabled:r,variant:s?void 0:"default",size:"icon",className:x(!s&&"gap-1.5 rounded-full",e),...a,children:o})});bt.displayName="ChatInput.Submit";const yt=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("flex items-center justify-between p-2",s),...n,children:e}));yt.displayName="ChatInput.Toolbar";const wt=l.forwardRef(({asChild:s=!1,className:e,children:n,onClick:o,...a},i)=>{const{value:u,onChange:f,setShowCommandMenu:p,setCommandMenuQuery:r}=te(),c=m=>{u.startsWith("/")||(f("/"),p(!0),r("")),o?.(m)},d=s?G:K;return t.jsx(d,{ref:i,type:"button",variant:"ghost",size:"icon",className:x("rounded-full",e),onClick:c,...a,children:n||t.jsx(gs,{className:"size-4"})})});wt.displayName="ChatInput.Actions";const vt=l.forwardRef(({asChild:s=!1,className:e,children:n,...o},a)=>{const i=s?G:K;return t.jsx(i,{ref:a,type:"button",variant:"ghost",size:"icon",className:x("rounded-full",e),...o,children:n||t.jsx(bs,{className:"size-4"})})});vt.displayName="ChatInput.Attachment";const Nt=l.forwardRef(({asChild:s=!1,className:e,children:n,...o},a)=>{const i=s?G:K;return t.jsx(i,{ref:a,type:"button",variant:"ghost",size:"icon",className:x("rounded-full",e),...o,children:n||t.jsx(ys,{className:"size-4"})})});Nt.displayName="ChatInput.VoiceInput";const jt=l.forwardRef(({commands:s=[],className:e,onChange:n,...o},a)=>{const{showCommandMenu:i,commandMenuQuery:u,selectedMenuIndex:f,setSelectedMenuIndex:p,setMenuItemCount:r,triggerCounter:c,onChange:d}=te();return t.jsx(mt,{ref:a,commands:s,showCommandMenu:i,commandMenuQuery:u,selectedMenuIndex:f,setSelectedMenuIndex:p,setMenuItemCount:r,triggerCounter:c,onChange:d,className:e,...o})});jt.displayName="ChatInput.CommandMenu";const bn=({className:s,...e})=>t.jsx(Gt,{className:x("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...e}),Ct=({className:s,...e})=>t.jsx(Jt,{className:x(s),...e}),yn=({withHandle:s,className:e,...n})=>t.jsx(Kt,{className:x("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",e),...n,children:s&&t.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"h-2.5 w-2.5",children:[t.jsx("title",{children:"Resize Handle"}),t.jsx("circle",{cx:"9",cy:"12",r:"1"}),t.jsx("circle",{cx:"9",cy:"5",r:"1"}),t.jsx("circle",{cx:"9",cy:"19",r:"1"}),t.jsx("circle",{cx:"15",cy:"12",r:"1"}),t.jsx("circle",{cx:"15",cy:"5",r:"1"}),t.jsx("circle",{cx:"15",cy:"19",r:"1"})]})})}),wn=({...s})=>t.jsx(rs,{position:"top-center",className:"toaster group",style:{"--top-offset":"16px","--width:":"calc(100% - 2 * var(--top-offset))",position:"absolute",zIndex:5,top:"var(--top-offset)",left:"50%",transform:"translateX(-50%)",width:"calc(100% - 2 * var(--top-offset))",maxWidth:"480px"},offset:0,toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...s}),St=l.createContext(void 0),ue=()=>{const s=l.useContext(St);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},Tt=l.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:e="hidden",defaultActiveTab:n="todo",className:o,children:a,...i},u)=>{const[f,p]=l.useState(s),[r,c]=l.useState(e),[d,m]=l.useState(n);return t.jsx(St.Provider,{value:{sidebarOpen:f,setSidebarOpen:p,panelSize:r,setPanelSize:c,activeTab:d,setActiveTab:m},children:t.jsx("div",{ref:u,className:x("flex h-screen flex-row bg-background text-foreground",o),...i,children:t.jsx(bn,{direction:"horizontal",className:"flex-1",children:a})})})});Tt.displayName="ChatLayout.Root";const vn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("relative z-10 border-b border-border bg-card shrink-0",s),...n,children:e}));vn.displayName="ChatLayout.Header";const kt=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx(Ct,{defaultSize:75,minSize:50,children:t.jsx("div",{ref:o,className:x("flex flex-1 flex-col overflow-hidden h-full",s),...n,children:e})}));kt.displayName="ChatLayout.Main";const It=l.forwardRef(({showToaster:s=!0,className:e,children:n,...o},a)=>t.jsxs("div",{ref:a,className:x("relative flex flex-1 flex-col overflow-hidden",e),...o,children:[n,s&&t.jsx(wn,{})]}));It.displayName="ChatLayout.Body";const Et=l.forwardRef(({className:s,children:e,onScrollChange:n,showScrollToBottom:o=!0,...a},i)=>{const[u,f]=l.useState(!1),p=l.useRef(null);l.useImperativeHandle(i,()=>p.current);const r=l.useCallback(()=>{const m=p.current;if(!m)return;const{scrollTop:g,scrollHeight:b,clientHeight:y}=m,w=b-g-y<100;f(!w&&o),n?.(w)},[n,o]),c=l.useCallback(()=>{r()},[r]),d=l.useCallback(()=>{const m=p.current;m&&m.scrollTo({top:m.scrollHeight,behavior:"smooth"})},[]);return l.useEffect(()=>{r()},[r]),t.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[t.jsx("div",{ref:p,className:x("h-full overflow-y-auto",s),onScroll:c,...a,children:t.jsx("div",{className:"mx-auto max-w-chat min-h-full flex flex-col",children:e})}),u&&t.jsx("button",{type:"button",onClick:d,className:x("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:t.jsx(ws,{className:"size-4"})})]})});Et.displayName="ChatLayout.Messages";const Rt=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("bg-linear-to-t from-background to-transparent px-4 pb-4",s),...n,children:t.jsx("div",{className:"mx-auto max-w-chat",children:e})}));Rt.displayName="ChatLayout.Footer";const Nn=l.forwardRef(({className:s,children:e,...n},o)=>{const{sidebarOpen:a}=ue();return a?t.jsx("div",{ref:o,className:x("border-r border-border bg-card w-64 overflow-y-auto",s),...n,children:e}):null});Nn.displayName="ChatLayout.Sidebar";const Ut=l.forwardRef(({breakpoint:s="lg",className:e,children:n,...o},a)=>{const{panelSize:i}=ue();return i==="hidden"?null:t.jsxs(t.Fragment,{children:[t.jsx(yn,{withHandle:!0}),t.jsx(Ct,{defaultSize:25,minSize:15,maxSize:50,children:t.jsx("div",{ref:a,className:x("hidden h-full border-l border-border bg-card overflow-y-auto transition-all duration-300",s==="md"&&"md:block",s==="lg"&&"lg:block",s==="xl"&&"xl:block",s==="2xl"&&"2xl:block",e),...o,children:n})})]})});Ut.displayName="ChatLayout.Aside";const se=l.forwardRef(({todos:s,className:e,...n},o)=>t.jsx("div",{ref:o,className:x("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No todos yet"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a.text},a.id))}));se.displayName="TodoTabContent";const ne=l.forwardRef(({files:s=[],className:e,...n},o)=>t.jsx("div",{ref:o,className:x("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No files attached"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a},a))}));ne.displayName="FilesTabContent";const jn=l.forwardRef(({data:s,className:e,...n},o)=>t.jsxs("div",{ref:o,className:x("space-y-4",e),...n,children:[t.jsx("h3",{className:"font-semibold text-lg",children:"Database"}),t.jsxs("div",{className:"text-sm text-muted-foreground",children:[t.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),t.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[t.jsx("p",{children:"Your large data table would go here"}),s&&typeof s=="object"?t.jsx("pre",{className:"mt-2 text-xs overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));jn.displayName="DatabaseTabContent";const pe=ls,W=l.forwardRef(({className:s,...e},n)=>t.jsx(je,{ref:n,className:x("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...e}));W.displayName=je.displayName;const q=l.forwardRef(({className:s,...e},n)=>t.jsx(Ce,{ref:n,className:x("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",s),...e}));q.displayName=Ce.displayName;const H=l.forwardRef(({className:s,...e},n)=>t.jsx(Se,{ref:n,className:x("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...e}));H.displayName=Se.displayName;const Mt=l.forwardRef(({todo:s,className:e,...n},o)=>t.jsx("div",{ref:o,className:x("flex items-center gap-3 px-3 py-2 rounded-lg",e),...n,children:t.jsx("span",{className:x("flex-1 text-[var(--font-size)] font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"shimmer-animation"),children:s.text})}));Mt.displayName="TodoListItem";const At=l.forwardRef(({client:s,todos:e,className:n,...o},a)=>{const i=e||[];return t.jsx("div",{ref:a,className:x("space-y-2 max-h-64 overflow-y-auto",n),...o,children:i.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic",children:"No tasks yet."}):i.map(u=>t.jsx(Mt,{todo:u},u.id))})});At.displayName="TodoList";const Cn=l.forwardRef(({client:s,todos:e,variant:n="animated",showIcons:o=!1,visibleTabs:a=["todo","files","database"],className:i,...u},f)=>{const p=e||[],[r,c]=l.useState(a[0]||"todo"),d=l.useRef(null),m=l.useRef(null);l.useEffect(()=>{const j=setTimeout(()=>{const w=d.current;if(r&&w){const v=m.current;if(v){const N=w.getBoundingClientRect(),M=v.getBoundingClientRect(),L=M.left-N.left,O=M.width,C=L/N.width*100,A=100-(L+O)/N.width*100;w.style.clipPath=`inset(0 ${A.toFixed(2)}% 0 ${C.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(j)},[r]);const b=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:Ge},{id:"files",label:"Files",icon:Je},{id:"database",label:"Database",icon:Ke}].filter(y=>a.includes(y.id));return t.jsx("div",{ref:f,className:x("select-none",i),...u,children:t.jsxs(pe,{value:r,onValueChange:c,className:"w-full",children:[n==="pills"?t.jsx(W,{className:x("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:b.map(y=>{const j=y.icon;return t.jsxs(q,{value:y.id,className:x("gap-2 px-3 py-1.5 rounded-lg text-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&j&&t.jsx(j,{className:"size-4"}),y.label]},y.id)})}):t.jsxs("div",{className:"relative mb-4 border-border",children:[t.jsx(W,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:b.map(y=>t.jsx(q,{value:y.id,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:y.label},y.id))}),t.jsx("div",{ref:d,className:"absolute top-0 left-0 w-full overflow-hidden z-10 pointer-events-none",style:{clipPath:"inset(0 100% 0 0% round 999px)",transition:"clip-path 0.25s ease-out"},children:t.jsx(W,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:b.map(y=>t.jsx(q,{value:y.id,ref:r===y.id?m:null,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:y.label},y.id))})})]}),t.jsx(H,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?t.jsx(se,{todos:p}):t.jsx(At,{todos:p})}),t.jsx(H,{value:"files",className:n==="pills"?"mt-0":"",children:t.jsx(ne,{})}),t.jsx(H,{value:"database",className:n==="pills"?"mt-0":"",children:t.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})})]})})});Cn.displayName="ChatSecondaryPanel";const Sn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("flex h-full flex-col",s),...n,children:e}));Sn.displayName="ChatSidebar.Root";const Tn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("border-b border-border px-4 py-3",s),...n,children:e}));Tn.displayName="ChatSidebar.Header";const kn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("flex-1 overflow-y-auto p-4",s),...n,children:e}));kn.displayName="ChatSidebar.Content";const In=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:x("border-t border-border px-4 py-3",s),...n,children:e}));In.displayName="ChatSidebar.Footer";const En=l.forwardRef(({children:s,className:e,...n},o)=>{const[a,i]=l.useState(s),[u,f]=l.useState(!1),p=l.useRef(s),r=l.useRef(!0);return l.useEffect(()=>{if(r.current){r.current=!1,p.current=s;return}if(p.current===s)return;f(!0);const c=setTimeout(()=>{i(s),p.current=s,requestAnimationFrame(()=>{f(!1)})},150);return()=>{clearTimeout(c)}},[s]),t.jsx("span",{ref:o,className:x("text-sm text-foreground opacity-60 transition-opacity duration-300",u?"opacity-0":"opacity-60",e),...n,children:a})});En.displayName="ChatStatus";const Rn=l.forwardRef(({autoScroll:s=!0,isStreaming:e=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:a=!0,scrollButton:i,className:u,children:f,...p},r)=>{const c=l.useRef(null),[d,m]=l.useState(!0),[g,b]=l.useState(!1),y=l.useRef(0);l.useImperativeHandle(r,()=>{if(!c.current)throw new Error("Container ref not initialized");return c.current});const j=l.useCallback(()=>{const v=c.current;if(!v)return;const{scrollTop:N,scrollHeight:M,clientHeight:L}=v,C=M-N-L<o;m(C),b(!C&&a),y.current=N},[o,a]),w=l.useCallback((v=n)=>{const N=c.current;N&&N.scrollTo({top:N.scrollHeight,behavior:v})},[n]);return l.useEffect(()=>{!s||!c.current||(e&&d?w("auto"):!e&&d&&w())},[s,e,d,w]),l.useEffect(()=>{const v=c.current;if(!v)return;const N=()=>{j()};return v.addEventListener("scroll",N,{passive:!0}),j(),()=>{v.removeEventListener("scroll",N)}},[j]),l.useEffect(()=>{const v=c.current;if(!v)return;const N=new ResizeObserver(()=>{d&&s&&w("auto")});return N.observe(v),()=>{N.disconnect()}},[d,s,w]),t.jsxs("div",{className:"relative flex-1",children:[t.jsx("div",{ref:c,className:x("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",u),...p,children:t.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:f})}),g&&t.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||t.jsxs("button",{type:"button",onClick:()=>w(),className:"px-4 py-2 rounded-full bg-card border border-border shadow-lg hover:shadow-xl hover:bg-card/90 transition-all text-sm font-medium text-foreground flex items-center gap-2","aria-label":"Scroll to bottom",children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Down arrow",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})}),"Scroll to bottom"]})})]})});Rn.displayName="Conversation";const Un=cs,Dt=l.forwardRef(({className:s,...e},n)=>t.jsx(Te,{ref:n,className:x("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e}));Dt.displayName=Te.displayName;const Mn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Un,{children:[t.jsx(Dt,{}),t.jsxs(ke,{ref:o,className:x("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...n,children:[e,t.jsxs(ds,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[t.jsx(vs,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Mn.displayName=ke.displayName;const An=l.forwardRef(({className:s,...e},n)=>t.jsx(Ie,{ref:n,className:x("text-lg font-semibold leading-none tracking-tight",s),...e}));An.displayName=Ie.displayName;const Dn=l.forwardRef(({className:s,...e},n)=>t.jsx(Ee,{ref:n,className:x("text-sm text-muted-foreground",s),...e}));Dn.displayName=Ee.displayName;const _n=l.forwardRef(({className:s,inset:e,children:n,...o},a)=>t.jsxs(Re,{ref:a,className:x("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",s),...o,children:[n,t.jsx(Qe,{className:"ml-auto h-4 w-4"})]}));_n.displayName=Re.displayName;const Ln=l.forwardRef(({className:s,...e},n)=>t.jsx(Ue,{ref:n,className:x("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",s),...e}));Ln.displayName=Ue.displayName;const zn=l.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(us,{children:t.jsx(Me,{ref:o,sideOffset:e,className:x("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",s),...n})}));zn.displayName=Me.displayName;const Pn=l.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(Ae,{ref:o,className:x("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",s),...n}));Pn.displayName=Ae.displayName;const On=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(De,{ref:o,className:x("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(_e,{children:t.jsx(Xe,{className:"h-4 w-4"})})}),e]}));On.displayName=De.displayName;const Hn=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Le,{ref:o,className:x("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(_e,{children:t.jsx(Ye,{className:"h-2 w-2 fill-current"})})}),e]}));Hn.displayName=Le.displayName;const Fn=l.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(ze,{ref:o,className:x("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",s),...n}));Fn.displayName=ze.displayName;const $n=l.forwardRef(({className:s,...e},n)=>t.jsx(Pe,{ref:n,className:x("-mx-1 my-1 h-px bg-border",s),...e}));$n.displayName=Pe.displayName;const Bn=B("flex h-10 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),Vn=l.forwardRef(({className:s,type:e,variant:n,...o},a)=>t.jsx("input",{type:e,className:x(Bn({variant:n,className:s})),ref:a,...o}));Vn.displayName="Input";const Wn=l.forwardRef(({className:s,...e},n)=>t.jsx(Oe,{ref:n,className:x("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...e}));Wn.displayName=Oe.displayName;const qn=B("flex animate-fadeIn",{variants:{role:{user:"max-w-[80%] self-end ml-auto mr-2",assistant:"self-start mr-auto",system:"self-start mr-auto max-w-full"},layout:{default:"",full:"max-w-full",compact:"max-w-[90%]"}},defaultVariants:{role:"assistant",layout:"default"}}),_t=l.forwardRef(({message:s,role:e,layout:n,className:o,children:a,messageId:i,autoScroll:u,isLastMessage:f=!1,...p},r)=>{const c=s?s.role:e||"assistant",d=s?s.id:i,m=l.useRef(null),[g,b]=l.useState(void 0);return l.useImperativeHandle(r,()=>m.current),l.useEffect(()=>{if(!f||c!=="assistant"){b(void 0);return}const y=()=>{const w=m.current;if(!w)return;let v=w.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(!v)return;const N=w.previousElementSibling;if(!N||N.getAttribute("aria-label")!=="user message"){b(void 0);return}const M=v.clientHeight,L=N.offsetHeight,C=Math.max(0,M-L-32);b(C)};y();const j=new ResizeObserver(y);if(m.current){j.observe(m.current);let w=m.current.parentElement;for(;w&&!w.classList.contains("overflow-y-auto");)w=w.parentElement;w&&j.observe(w)}return()=>j.disconnect()},[f,c]),l.useEffect(()=>{if((u!==void 0?u:c==="user")&&m.current){const j=setTimeout(()=>{m.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(j)}},[c,u]),t.jsx("article",{ref:m,"aria-label":`${c} message`,"data-message-id":d,className:x(qn({role:c,layout:n}),o),style:{minHeight:g!==void 0?`${g}px`:void 0},...p,children:a})});_t.displayName="Message";const Y=128e3,be={"claude-sonnet-4-5-20250929":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-haiku-20240307":2e5,"gpt-4-turbo":128e3,"gpt-4-turbo-preview":128e3,"gpt-4-0125-preview":128e3,"gpt-4-1106-preview":128e3,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,default:Y};function Qn(s){if(!s)return Y;if(s in be)return be[s]??Y;const e=s.toLowerCase();return e.includes("claude")?2e5:e.includes("gpt-4-turbo")?128e3:e.includes("gpt-4-32k")?32768:e.includes("gpt-4")?8192:e.includes("gpt-3.5")?16385:Y}function Gn(s,e){const n=Qn(e);return s/n*100}function Jn(s,e,n=1){return`${Gn(s,e).toFixed(n)}%`}const ye=B("mb-3 rounded-lg bg-card border border-border transition-all",{variants:{variant:{default:"opacity-70",subtle:"opacity-50",prominent:"opacity-90 shadow-sm"}},defaultVariants:{variant:"default"}}),Kn=B("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Lt=l.forwardRef(({content:s,isStreaming:e=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:a=!1,autoCollapse:i=!0,autoCollapseDelay:u=2e3,label:f="Thinking",variant:p,className:r},c)=>{const[d,m]=l.useState(n==="inline"?!0:o),[g,b]=l.useState(!1);return l.useEffect(()=>{if(i&&!e&&s&&n==="collapsible"){const y=setTimeout(()=>{b(!0),m(!1)},u);return()=>clearTimeout(y)}},[e,s,i,u,n]),l.useEffect(()=>{a&&e&&n==="collapsible"&&!g&&m(!0)},[a,e,n,g]),!s&&!e?null:n==="inline"?t.jsxs("div",{ref:c,className:x(ye({variant:p}),"p-3",r),children:[t.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:f}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse"})]}),t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):t.jsxs("div",{ref:c,className:x("mb-3",r),children:[t.jsxs("button",{type:"button",onClick:()=>{m(!d),b(!1)},className:"w-full flex items-center justify-between p-2.5 rounded-lg bg-card border border-border hover:bg-card/80 hover:shadow-sm transition-all text-left","aria-expanded":d,"aria-label":`${d?"Collapse":"Expand"} reasoning`,children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide shrink-0",children:f}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!d&&s&&t.jsxs("span",{className:"text-xs text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),t.jsx(ae,{className:Kn({expanded:d}),"aria-hidden":"true"})]}),d&&t.jsx("div",{className:x(ye({variant:p}),"mt-2 p-3 animate-fadeIn"),children:t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});Lt.displayName="Reasoning";const zt=l.forwardRef(({content:s,isStreaming:e=!1,showEmpty:n=!0,emptyMessage:o="",className:a,...i},u)=>{if(!s&&e&&n)return t.jsx("div",{ref:u,className:x("opacity-70 italic text-sm",a),...i,children:o});if(!s)return null;const f={table:({node:p,...r})=>t.jsx("div",{className:"overflow-x-auto my-4",children:t.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...r})}),thead:({node:p,...r})=>t.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:p,...r})=>t.jsx("tbody",{...r}),tr:({node:p,...r})=>t.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:p,...r})=>t.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...r}),td:({node:p,...r})=>t.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:p,checked:r,...c})=>c.type==="checkbox"?t.jsx("input",{type:"checkbox",checked:r||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...c}):t.jsx("input",{...c}),code:({node:p,...r})=>r.className?.includes("language-")?t.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-sm font-mono text-foreground shadow-sm",...r}):t.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-sm font-mono text-foreground",...r}),pre:({node:p,...r})=>t.jsx("pre",{className:"my-4 rounded-lg",...r}),h1:({node:p,...r})=>t.jsx("h1",{className:"text-2xl font-bold mt-6 mb-4 text-foreground border-b border-border pb-2",...r}),h2:({node:p,...r})=>t.jsx("h2",{className:"text-xl font-semibold mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...r}),h3:({node:p,...r})=>t.jsx("h3",{className:"text-lg font-semibold mt-4 mb-2 text-foreground",...r}),h4:({node:p,...r})=>t.jsx("h4",{className:"text-base font-semibold mt-3 mb-2 text-foreground",...r}),ul:({node:p,...r})=>{const c=p?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="li"&&"children"in d&&Array.isArray(d.children)&&d.children.some(m=>typeof m=="object"&&m!==null&&"type"in m&&m.type==="element"&&"tagName"in m&&m.tagName==="input"&&"properties"in m&&typeof m.properties=="object"&&m.properties!==null&&"type"in m.properties&&m.properties.type==="checkbox"));return t.jsx("ul",{className:x("my-2 space-y-1 text-foreground",c?"list-none space-y-2":"list-disc list-inside"),...r})},ol:({node:p,...r})=>t.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...r}),li:({node:p,...r})=>{const c=p?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="input"&&"properties"in d&&typeof d.properties=="object"&&d.properties!==null&&"type"in d.properties&&d.properties.type==="checkbox");return t.jsx("li",{className:x("flex items-start",c?"gap-2":"ml-2"),...r})},a:({node:p,...r})=>t.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:p,...r})=>t.jsx("p",{className:"my-2 text-foreground leading-relaxed",...r}),blockquote:({node:p,...r})=>t.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2 rounded-r-md shadow-sm",...r}),hr:({node:p,...r})=>t.jsx("hr",{className:"my-6 border-t border-border opacity-50",...r})};return t.jsxs("div",{ref:u,className:x("markdown-content prose prose-sm max-w-none dark:prose-invert",a),...i,children:[t.jsx(Xt,{remarkPlugins:[Is],components:f,children:s}),e&&s&&t.jsx("span",{className:"inline-block ml-1 animate-typing text-primary",children:"..."})]})});zt.displayName="Response";const Xn={pending:"bg-transparent text-muted-foreground",in_progress:"bg-transparent text-muted-foreground",completed:"bg-transparent text-muted-foreground",failed:"bg-transparent text-muted-foreground"};function Yn({toolCall:s}){const[e,n]=l.useState(!1);return t.jsxs("div",{className:"flex flex-col",children:[t.jsxs("button",{type:"button",className:"flex items-center gap-1.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>n(!e),"aria-expanded":e,children:[t.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded ${Xn[s.status]}`,children:[t.jsx(Ns,{className:"h-3 w-3"}),t.jsx("span",{children:s.title}),s.status==="completed"&&t.jsx("span",{children:"✓"})]}),t.jsx("span",{className:"text-gray-400 text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:e?"▲":"▼"})]}),e&&t.jsxs("div",{className:"mt-2 space-y-3 text-sm border border-gray-200 rounded-md p-3 bg-white shadow-sm max-w-full",children:[s.locations&&s.locations.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5",children:"Files"}),t.jsx("ul",{className:"space-y-1",children:s.locations.map(o=>t.jsxs("li",{className:"font-mono text-xs text-gray-700 bg-gray-50 px-2 py-1 rounded",children:[o.path,o.line!==null&&o.line!==void 0&&`:${o.line}`]},`${o.path}:${o.line??""}`))})]}),s.rawInput&&Object.keys(s.rawInput).length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5",children:"Input"}),t.jsx("div",{className:"bg-gray-50 p-2 rounded border border-gray-200",children:t.jsx(me,{value:s.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent"}})})]}),s.content&&s.content.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5",children:"Output"}),t.jsx("div",{className:"space-y-2",children:s.content.map((o,a)=>{const i=()=>o.type==="diff"&&"path"in o?`diff-${o.path}-${a}`:o.type==="terminal"&&"terminalId"in o?`terminal-${o.terminalId}`:o.type==="text"&&"text"in o?`text-${o.text.substring(0,20)}-${a}`:o.type==="content"&&"content"in o?`content-${o.content.text?.substring(0,20)}-${a}`:`block-${a}`,u=(f,p)=>{try{const r=JSON.parse(f);if(typeof r=="object"&&r!==null)return t.jsx("div",{className:"bg-gray-50 p-2 rounded border border-gray-200",children:t.jsx(me,{value:r,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent"}})},p)}catch{}return t.jsx("pre",{className:"bg-gray-50 p-2.5 rounded border border-gray-200 text-xs overflow-x-auto font-mono text-gray-800",children:f},p)};if(o.type==="content"&&"content"in o){const f=o.content;if(f.type==="text"&&f.text)return u(f.text,i())}return o.type==="text"&&"text"in o?u(o.text,i()):o.type==="diff"&&"path"in o&&"oldText"in o&&"newText"in o?t.jsxs("div",{className:"border rounded",children:[t.jsxs("div",{className:"bg-gray-100 px-2 py-1 text-xs font-mono",children:[o.path,"line"in o&&o.line!==null&&o.line!==void 0&&`:${o.line}`]}),t.jsxs("div",{className:"p-2 font-mono text-xs",children:[t.jsxs("div",{className:"text-red-600",children:["- ",o.oldText]}),t.jsxs("div",{className:"text-green-600",children:["+ ",o.newText]})]})]},i()):o.type==="terminal"&&"terminalId"in o?t.jsxs("div",{className:"bg-black text-green-400 p-2 rounded text-xs font-mono",children:["Terminal: ",o.terminalId]},i()):null})})]}),s.error&&t.jsxs("div",{className:"bg-red-50 border border-red-200 rounded p-2.5 text-red-700",children:[t.jsx("div",{className:"text-xs font-semibold text-red-600 uppercase tracking-wide mb-1.5",children:"Error"}),t.jsx("div",{className:"text-xs",children:s.error})]}),s.tokenUsage&&t.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded p-2.5",children:[t.jsx("div",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2",children:"Token Usage"}),t.jsxs("div",{className:"grid grid-cols-3 gap-3 text-xs text-gray-700",children:[s.tokenUsage.inputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-gray-500 text-[10px] uppercase tracking-wide mb-0.5",children:"Input"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.inputTokens.toLocaleString()})]}),s.tokenUsage.outputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-gray-500 text-[10px] uppercase tracking-wide mb-0.5",children:"Output"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.outputTokens.toLocaleString()})]}),s.tokenUsage.totalTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-gray-500 text-[10px] uppercase tracking-wide mb-0.5",children:"Total"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.totalTokens.toLocaleString()})]})]})]}),s.startedAt&&t.jsxs("div",{className:"text-xs text-gray-500",children:["Started: ",new Date(s.startedAt).toLocaleTimeString(),s.completedAt&&t.jsxs(t.Fragment,{children:[" ","| Completed:"," ",new Date(s.completedAt).toLocaleTimeString()," (",Math.round((s.completedAt-s.startedAt)/1e3),"s)"]})]})]})]})}const X=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],we=["...","·..",".·.","..·",".·.","·.."];function Zn({startTime:s}){const[e,n]=l.useState(0),[o,a]=l.useState(()=>X[Math.floor(Math.random()*X.length)]),[i,u]=l.useState(0);l.useEffect(()=>{const r=setInterval(()=>{const d=Date.now()-s;n(d)},100);return()=>clearInterval(r)},[s]),l.useEffect(()=>{const r=setInterval(()=>{const c=Math.floor(Math.random()*X.length);a(X[c])},1500);return()=>clearInterval(r)},[]),l.useEffect(()=>{const r=setInterval(()=>{u(c=>(c+1)%we.length)},100);return()=>clearInterval(r)},[]);const f=(e/1e3).toFixed(1),p=we[i];return t.jsxs("span",{className:"text-muted-foreground text-sm",children:[o,p," ",f,"s"]})}const eo=B("w-full px-4 py-3 rounded-xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-primary text-primary-foreground shadow-sm",assistant:"text-foreground",system:"bg-card border border-border text-foreground opacity-80 text-sm"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),Pt=l.forwardRef(({role:s,variant:e,isStreaming:n,message:o,thinkingDisplayStyle:a="collapsible",className:i,children:u,...f},p)=>{const r=S(y=>y.streamingStartTime),c=S(y=>y.currentModel),d=o&&!u,m=d?o.role:s||"assistant",g=d?o.isStreaming:n;let b=u;if(d){const y=o.metadata?.thinking,j=!!y,w=o.isStreaming&&!o.content&&o.role==="assistant";b=t.jsxs(t.Fragment,{children:[o.role==="assistant"&&j&&t.jsx(Lt,{content:y,isStreaming:o.isStreaming,mode:a,autoCollapse:!0}),w&&r&&t.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[t.jsx(Ze,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx(Zn,{startTime:r})]}),o.role==="assistant"&&o.toolCalls&&o.toolCalls.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mb-3",children:o.toolCalls.map(v=>t.jsx(Yn,{toolCall:v},v.id))}),o.role==="user"?t.jsx("div",{className:"whitespace-pre-wrap",children:o.content}):t.jsx(zt,{content:o.content,isStreaming:o.isStreaming,showEmpty:!1}),o.role==="assistant"&&o.tokenUsage&&t.jsx("div",{className:"mt-3 pt-2 border-t border-border/30 text-xs text-muted-foreground/60",children:t.jsxs("span",{children:["Context:"," ",Jn(o.tokenUsage.totalTokens??0,c??void 0)," ","(",(o.tokenUsage.totalTokens??0).toLocaleString()," ","tokens)"]})})]})}return t.jsx("div",{ref:p,className:x(eo({role:m,variant:e}),g&&"animate-pulse-subtle",i),...f,children:b})});Pt.displayName="MessageContent";const fe=l.forwardRef(({showIcons:s=!0,visibleTabs:e=["todo","files"],variant:n="default",className:o,...a},i)=>{const f=[{id:"todo",label:"To-do",icon:Ge},{id:"files",label:"Files",icon:Je},{id:"database",label:"Database",icon:Ke}].filter(r=>e.includes(r.id)),p=n==="compact"?"gap-[4px]":"gap-3";return t.jsx(W,{ref:i,className:x("w-full justify-start bg-transparent p-0 h-auto",p,o),...a,children:f.map(r=>{const c=r.icon;return t.jsxs(q,{value:r.id,className:x("gap-2 px-3 py-1.5 rounded-lg text-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[s&&c&&t.jsx(c,{className:"size-4"}),r.label]},r.id)})})});fe.displayName="PanelTabsHeader";const to=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(He,{ref:o,className:x("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...n,children:[e,t.jsx(ps,{asChild:!0,children:t.jsx(js,{className:"h-4 w-4 opacity-50"})})]}));to.displayName=He.displayName;const Ot=l.forwardRef(({className:s,...e},n)=>t.jsx(Fe,{ref:n,className:x("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(ie,{className:"h-4 w-4"})}));Ot.displayName=Fe.displayName;const Ht=l.forwardRef(({className:s,...e},n)=>t.jsx($e,{ref:n,className:x("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(ae,{className:"h-4 w-4"})}));Ht.displayName=$e.displayName;const so=l.forwardRef(({className:s,children:e,position:n="popper",...o},a)=>t.jsx(fs,{children:t.jsxs(Be,{ref:a,className:x("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:n,...o,children:[t.jsx(Ot,{}),t.jsx(ms,{className:x("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),t.jsx(Ht,{})]})}));so.displayName=Be.displayName;const no=l.forwardRef(({className:s,...e},n)=>t.jsx(Ve,{ref:n,className:x("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...e}));no.displayName=Ve.displayName;const oo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(We,{ref:o,className:x("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(xs,{children:t.jsx(Xe,{className:"h-4 w-4"})})}),t.jsx(hs,{children:e})]}));oo.displayName=We.displayName;const ro=l.forwardRef(({className:s,...e},n)=>t.jsx(qe,{ref:n,className:x("-mx-1 my-1 h-px bg-muted",s),...e}));ro.displayName=qe.displayName;const Ft=l.forwardRef(({task:s,collapsible:e=!0,defaultExpanded:n=!1,onTaskClick:o,className:a,...i},u)=>{const[f,p]=l.useState(n),r=!!(s.details||s.files&&s.files.length>0),c={pending:Ye,in_progress:Ze,completed:Cs}[s.status],d=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},m=()=>{r&&e&&p(!f),o?.(s)};return t.jsxs("div",{ref:u,className:x("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",a),...i,children:[t.jsxs("button",{type:"button",onClick:m,className:x("w-full flex items-center gap-3 px-3 py-2.5 text-left",r&&e&&"cursor-pointer"),disabled:!r&&!e,children:[t.jsx(c,{className:x("w-4 h-4 shrink-0",d(),s.status==="in_progress"&&"animate-spin")}),t.jsx("span",{className:x("flex-1 text-sm font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"font-medium"),children:s.text}),r&&e&&t.jsx(ae,{className:x("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",f&&"rotate-180"),"aria-hidden":"true"})]}),r&&f&&t.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[s.details&&t.jsx("p",{className:"text-sm text-foreground opacity-80 leading-relaxed mb-2",children:s.details}),s.files&&s.files.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),t.jsx("div",{className:"space-y-1",children:s.files.map(g=>t.jsx("div",{className:"text-xs font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:g},g))})]})]})]})});Ft.displayName="Task";const ao=l.forwardRef(({tasks:s,collapsible:e=!0,onTaskClick:n,emptyMessage:o="No tasks yet.",className:a,...i},u)=>t.jsx("div",{ref:u,className:x("space-y-2 max-h-96 overflow-y-auto",a),...i,children:s.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic py-4 text-center",children:o}):s.map(f=>t.jsx(Ft,{task:f,collapsible:e,...n?{onTaskClick:n}:{}},f.id))}));ao.displayName="TaskList";const io=B("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-none",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),lo=l.forwardRef(({className:s,autoResize:e=!1,maxHeight:n=200,variant:o,...a},i)=>{const u=l.useRef(null),f=l.useCallback(r=>{u.current=r,typeof i=="function"?i(r):i&&(i.current=r)},[i]),p=l.useCallback(()=>{const r=u.current;if(!r||!e)return;r.style.height="auto";const c=Math.min(r.scrollHeight,n);r.style.height=`${c}px`,r.scrollHeight>n?r.style.overflowY="auto":r.style.overflowY="hidden"},[e,n]);return l.useEffect(()=>{p()},[p]),t.jsx("textarea",{className:x(io({variant:o}),e&&"overflow-y-hidden",s),ref:f,...a})});lo.displayName="Textarea";const $=ce("gui");function co({agentName:s}){const{isExpanded:e,setIsExpanded:n}=de();return t.jsxs("div",{className:"flex lg:hidden items-center gap-2 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx("h1",{className:"text-[20px] font-semibold leading-[1.2] tracking-[-0.4px] text-foreground",children:s}),t.jsx("div",{className:"flex items-center justify-center shrink-0",children:t.jsx(ie,{className:"size-4 rotate-180 text-muted-foreground"})})]}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle menu",onClick:()=>n(!e),children:t.jsx(et,{className:"size-4 text-muted-foreground"})})]})}function uo({agentName:s,todos:e,showHeader:n}){const{panelSize:o,setPanelSize:a}=ue();return t.jsxs(pt,{className:x("border-b border-border bg-card relative lg:p-0","[border-bottom-width:0.5px]"),children:[t.jsxs("div",{className:"hidden lg:flex items-center gap-2 w-full h-16 py-5 pl-6 pr-4",children:[n&&t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx("h1",{className:"text-[20px] font-semibold leading-[1.2] tracking-[-0.4px] text-foreground",children:s}),t.jsx("div",{className:"flex items-center justify-center shrink-0",children:t.jsx(ie,{className:"size-4 rotate-180 text-muted-foreground"})})]}),!n&&t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle sidebar",onClick:()=>{a(o==="hidden"?"small":"hidden")},children:t.jsx(et,{className:"size-4 text-muted-foreground"})})]}),t.jsx(co,{agentName:s}),t.jsx(ft,{className:x("pt-6 pb-8 px-6","border-b border-border bg-card","shadow-[0_4px_16px_0_rgba(0,0,0,0.04)]","[border-bottom-width:0.5px]"),children:t.jsxs(pe,{defaultValue:"todo",className:"w-full",children:[t.jsx(fe,{showIcons:!0,visibleTabs:["todo","files"],variant:"default"}),t.jsx(H,{value:"todo",className:"mt-4",children:t.jsx(se,{todos:e})}),t.jsx(H,{value:"files",className:"mt-4",children:t.jsx(ne,{})})]})})]})}function po({client:s}){const{connectionStatus:e,connect:n,sessionId:o}=Ms(s),{messages:a}=rt(s);As(s);const i=S(m=>m.error),[u,f]=l.useState("Agent"),[p,r]=l.useState(typeof window<"u"?window.innerWidth>=1024:!0);l.useEffect(()=>{$.debug("Connection status changed",{status:e}),e==="error"&&i&&$.error("Connection error occurred",{error:i})},[e,i]),l.useEffect(()=>{if(s&&o){const m=s.getCurrentSession();m?.metadata?.agentName&&f(m.metadata.agentName)}},[s,o]),l.useEffect(()=>{const m=window.matchMedia("(min-width: 1024px)"),g=b=>{r(b.matches)};return r(m.matches),m.addEventListener("change",g),()=>{m.removeEventListener("change",g)}},[]);const c=[],d=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:t.jsx(xe,{className:"h-4 w-4"}),category:"model",onSelect:()=>{$.info("User selected Sonnet 4.5 model")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:t.jsx(xe,{className:"h-4 w-4"}),category:"model",onSelect:()=>{$.info("User selected Opus model")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:t.jsx(Ts,{className:"h-4 w-4"}),category:"action",onSelect:()=>{$.info("User opened settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:t.jsx(ks,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{$.info("User enabled code mode")}}];return t.jsxs(Tt,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[t.jsxs(kt,{children:[t.jsx(uo,{agentName:u,todos:c,showHeader:a.length>0}),e==="error"&&i&&t.jsx("div",{className:"border-b border-red-500/20 bg-red-500/10 px-6 py-4",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"mb-1 text-sm font-semibold text-red-500",children:"Connection Error"}),t.jsx("p",{className:"whitespace-pre-line text-sm text-foreground",children:i})]}),t.jsx("button",{type:"button",onClick:n,className:"rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600",children:"Retry"})]})}),t.jsxs(It,{children:[t.jsx(Et,{className:a.length>0?"pt-4":"",children:a.length===0?t.jsx("div",{className:"flex flex-1 items-center px-4",children:t.jsx(dt,{title:u,description:"This agent can help you with your tasks. Start a conversation by typing a message below.",suggestedPrompts:["Help me debug this code","Explain how this works","Create a new feature","Review my changes"],onPromptClick:m=>{$.info("Prompt clicked",{prompt:m})}})}):t.jsx("div",{className:"flex flex-col gap-4 px-4",children:a.map((m,g)=>t.jsx(_t,{message:m,isLastMessage:g===a.length-1,children:t.jsx(Pt,{message:m,thinkingDisplayStyle:"collapsible"})},m.id))})}),t.jsx(Rt,{children:t.jsxs(ht,{client:s,children:[t.jsx(jt,{commands:d}),t.jsx(gt,{placeholder:"Type a message or / for commands...",autoFocus:!0}),t.jsxs(yt,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(wt,{}),t.jsx(vt,{})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Nt,{}),t.jsx(bt,{children:t.jsx(Ss,{className:"size-4"})})]})]})]})})]})]}),p&&t.jsx(Ut,{breakpoint:"lg",children:t.jsxs(pe,{defaultValue:"todo",className:"flex flex-col h-full",children:[t.jsx("div",{className:x("border-b border-border bg-card","px-6 py-2 h-16","flex items-center","[border-bottom-width:0.5px]"),children:t.jsx(fe,{showIcons:!0,visibleTabs:["todo","files"],variant:"compact"})}),t.jsx(H,{value:"todo",className:"flex-1 p-4 mt-0",children:t.jsx(se,{todos:c})}),t.jsx(H,{value:"files",className:"flex-1 p-4 mt-0",children:t.jsx(ne,{})})]})})]})}function fo(){return"http://localhost:3100"}const ve={agentServerUrl:fo()},V=ce("gui");function mo(){const[s,e]=l.useState(null),[n,o]=l.useState(null);return l.useEffect(()=>{try{V.info("Initializing ACP client",{serverUrl:ve.agentServerUrl});const a=new Fs({type:"http",options:{baseUrl:ve.agentServerUrl}});return e(a),V.info("ACP client initialized successfully"),()=>{V.debug("Disconnecting ACP client"),a.disconnect().catch(i=>{V.error("Failed to disconnect ACP client",{error:i instanceof Error?i.message:String(i)})})}}catch(a){const i=a instanceof Error?a.message:"Failed to initialize ACP client";o(i),V.error("Failed to initialize ACP client",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0});return}},[]),n?t.jsx("div",{className:"flex items-center justify-center h-screen bg-[var(--color-bg)]",children:t.jsxs("div",{className:"text-center p-8 max-w-md",children:[t.jsx("h1",{className:"text-2xl font-bold text-red-500 mb-4",children:"Initialization Error"}),t.jsx("p",{className:"text-[var(--color-text)] mb-4",children:n}),t.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Failed to initialize the ACP client. Check the console for details."})]})}):t.jsx(po,{client:s})}const $t=document.getElementById("root");if(!$t)throw new Error("Root element not found");Yt.createRoot($t).render(t.jsx(Zt.StrictMode,{children:t.jsx(mo,{})}));