@townco/gui-template 0.1.36 → 0.1.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{r as l,j as t,P as hs,e as xs,f as bs,M as ys,h as ws,b as vs}from"./react-BxIc-aOD.js";import{P as ke,a as Ns}from"./acp-sdk-CrD5QpoU.js";import{L as
|
|
1
|
+
import{r as l,j as t,P as hs,e as xs,f as bs,M as ys,h as ws,b as vs}from"./react-BxIc-aOD.js";import{P as ke,a as Ns}from"./acp-sdk-CrD5QpoU.js";import{L as $,M as E,N as A,O as w,P as ze,Q as z,R as M,S as L,T as F,U as Ss,W as ee,X as de,Y as js,Z as Cs,$ as ks,a0 as Ts,a1 as q,a2 as Is,a3 as Te}from"./vendor-CDPxlbZ6.js";import{S as te,a as _e,b as Le,P as Es,C as Fe,I as Oe,c as Be,d as $e,R as He,L as We,e as Ve,f as Rs,T as As,g as qe,h as Qe,i as Ge,j as Ms,k as Ke,l as Us,m as Ds,n as Ps,O as Je,o as zs,p as Xe,q as _s,r as Ye,D as Ze,s as et,t as tt,u as Ls,v as st,w as nt,x as Fs,y as ot,V as Os,z as rt,A as at,B as Bs,E as $s,F as it}from"./radix-BwF8w229.js";import{C as xe,S as Hs,P as Ws,M as Vs,A as qs,a as lt,b as be,F as Qs,c as Gs,d as Ks,E as Js,e as se,f as ct,g as ye,h as we,D as dt,L as ut,i as Ie,j as Xs,k as Ys,l as Zs,m as en,n as pt,X as tn,W as ft,o as sn,p as nn,q as on,r as rn,G as an,s as mt,t as ln}from"./icons-xaawVwTw.js";import{r as cn}from"./markdown-PIOGdvNw.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))o(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&o(c)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function o(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();var dn={};const re=typeof process<"u"&&process.versions?.node;let un,pn=0;const fn=new Set;function mn(s){for(const e of fn)e(s)}const Ee={trace:0,debug:1,info:2,warn:3,error:4,fatal:5};class gn{service;minLevel;logFilePath;logsDir;writeQueue=[];isWriting=!1;enableConsoleOutput;constructor(e,n="debug"){this.service=e,this.minLevel=n,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&dn?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(e){if(!(!this.logFilePath||!re)&&(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
2
|
`)}
|
|
3
|
-
`;try{await require("node:fs").promises.appendFile(this.logFilePath,o,"utf-8")}catch{}}this.isWriting=!1}}shouldLog(e){return Ee[e]>=Ee[this.minLevel]}log(e,n,o){if(!this.shouldLog(e))return;const i={id:`log_${++
|
|
4
|
-
`),o={sessionId:this.currentSessionId,prompt:[{type:"text",text:n}]},i=await this.sendRpcRequest("session/prompt",o);k.debug("Prompt sent",{promptResponse:i}),this.streamComplete=!0;const a=this.chunkResolvers.shift();a?a({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(){this.isReceivingMessages=!0;try{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}}finally{this.isReceivingMessages=!1}}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 i={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:n};k.debug("Sending RPC request",{method:e,params:n,request:i});const a={"Content-Type":"application/json",...this.options.headers},c=this.options.timeout??600*1e3,f=new AbortController,
|
|
5
|
-
`);c=r.pop()||"";let d={event:"message",data:""};for(const u of r)u.startsWith("event:")?d.event=u.substring(6).trim():u.startsWith("data:")?d.data=u.substring(5).trim():u===""&&(d.event==="message"&&d.data&&this.handleSSEMessage(d.data),d={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=Ns.safeParse(n);if(!o.success){k.error("Invalid ACP message from SSE",{issues:o.error.issues});return}const i=o.data;k.debug("Parsed ACP message",{method:"method"in i?i.method:"(no method)"}),"method"in i&&i.method==="session/update"&&(k.debug("Received session/update notification"),"params"in i&&i.params&&(k.debug("Calling handleSessionNotification",{params:i.params}),this.handleSessionNotification(i.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,i=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 a=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,c=o._meta&&typeof o._meta=="object"&&"prettyName"in o._meta?String(o._meta.prettyName):void 0,f=o._meta&&typeof o._meta=="object"&&"icon"in o._meta?String(o._meta.icon):void 0,p={id:o.toolCallId??"",title:o.title??"",prettyName:c,icon:f,kind:o.kind||"other",status:o.status||"pending",locations:o.locations,rawInput:o.rawInput,tokenUsage:o.tokenUsage,content:o.content?.map(d=>{if(typeof d!="object"||d===null)return{type:"text",text:""};const u=d;if(u.type==="content"&&typeof u.content=="object"&&u.content!==null){const h=u.content;if(h.type==="text")return{type:"content",content:{type:"text",text:typeof h.text=="string"?h.text:""}}}return u.type==="text"?{type:"text",text:typeof u.text=="string"?u.text:""}:u.type==="diff"?{type:"diff",path:typeof u.path=="string"?u.path:"",oldText:typeof u.oldText=="string"?u.oldText:"",newText:typeof u.newText=="string"?u.newText:"",line:typeof u.line=="number"?u.line:null}:u.type==="terminal"?{type:"terminal",terminalId:typeof u.terminalId=="string"?u.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now()},r={type:"tool_call",sessionId:i,status:"active",toolCall:p,messageId:a};this.notifySessionUpdate(r)}else if(o?.sessionUpdate==="tool_call_update"){const a=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,c={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 d=r.content;if(d.type==="text")return{type:"content",content:{type:"text",text:typeof d.text=="string"?d.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:i,status:"active",toolCallUpdate:c,messageId:a};k.debug("Notifying tool_call_update session update",{sessionUpdate:f}),this.notifySessionUpdate(f)}else if(o&&"sessionUpdate"in o&&o.sessionUpdate==="tool_output"){const a=o,c=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,f={id:a.toolCallId??"",rawOutput:a.rawOutput,content:a.content?.map(r=>{if(typeof r!="object"||r===null)return{type:"text",text:""};const d=r;if(d.type==="content"&&typeof d.content=="object"&&d.content!==null){const u=d.content;if(u.type==="text")return{type:"content",content:{type:"text",text:typeof u.text=="string"?u.text:""}}}return d.type==="text"?{type:"text",text:typeof d.text=="string"?d.text:""}:d.type==="diff"?{type:"diff",path:typeof d.path=="string"?d.path:"",oldText:typeof d.oldText=="string"?d.oldText:"",newText:typeof d.newText=="string"?d.newText:"",line:typeof d.line=="number"?d.line:null}:d.type==="terminal"?{type:"terminal",terminalId:typeof d.terminalId=="string"?d.terminalId:""}:{type:"text",text:""}})},p={type:"tool_call_update",sessionId:i,status:"active",toolCallUpdate:f,messageId:c};k.debug("Notifying tool_output as tool_call_update",{sessionUpdate:p}),this.notifySessionUpdate(p)}else if(o?.sessionUpdate==="agent_message_chunk"){const a=o._meta&&typeof o._meta=="object"&&"isReplay"in o._meta&&o._meta.isReplay===!0;if(this.isInReplayMode&&!a)return;const c={type:"generic",sessionId:i,status:"active"},f=o._meta&&typeof o._meta=="object"&&"tokenUsage"in o._meta?o._meta.tokenUsage:void 0,p=o.content;if(p&&typeof p=="object"){const r=p;let d=null;if(r.type==="text"&&typeof r.text=="string"&&(d={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:r.text},tokenUsage:f,isComplete:!1}),d&&!a){const u=this.chunkResolvers.shift();u?u(d):this.messageQueue.push(d)}if(d&&typeof r.text=="string"&&(a||!this.isReceivingMessages)){const u={type:"generic",sessionId:i,status:"active",message:{id:`msg_${Date.now()}_assistant`,role:"assistant",content:[{type:"text",text:r.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(u)}}a||this.notifySessionUpdate(c)}else if(o?.sessionUpdate==="user_message_chunk"){k.debug("Received user_message_chunk",{update:o});const a=o.content;if(a&&typeof a=="object"){const c=a;if(c.type==="text"&&typeof c.text=="string"){const f={type:"generic",sessionId:i,status:"active",message:{id:`msg_${Date.now()}_user`,role:"user",content:[{type:"text",text:c.text}],timestamp:new Date().toISOString()}};k.debug("Notifying session update for user message"),this.notifySessionUpdate(f)}}}else{const a={type:"generic",sessionId:i,status:"active"};this.notifySessionUpdate(a)}}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 hn{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 xn{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 he=$("acp-client","debug");class bn{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=>{he.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="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(n){const c=new Date().toISOString(),f={id:n,status:"connected",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:c}};return this.sessions.set(n,f),this.currentSessionId=n,n}const o=this.generateSessionId(),i=new Date().toISOString(),a={id:o,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:i}};return this.sessions.set(o,a),this.currentSessionId=o,this.updateSessionStatus(o,"connected"),o}async loadSession(e,n){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const o=new Date().toISOString(),i={id:e,status:"connecting",config:n?{...n,agentPath:n.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};return this.sessions.set(e,i),this.currentSessionId=e,await this.transport.loadSession(e),this.updateSessionStatus(e,"connected"),e}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 i=this.sessions.get(o);if(!i)throw new Error(`Session ${o} not found`);const a={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};i.messages.push(a),this.updateSessionStatus(o,"active"),await this.transport.send(a)}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 hn(this.config.options);case"http":return new gn(this.config.options);case"websocket":return new xn(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){he.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){he.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 G=$("acp-client-hook");function yn(s){const[e,n]=l.useState(null),[o,i]=l.useState(null),[a,c]=l.useState(null);return l.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("session");p&&(G.info("Session ID found in URL",{sessionId:p}),c(p));try{G.info("Initializing ACP client",{serverUrl:s.serverUrl});const r=new bn({type:"http",options:{baseUrl:s.serverUrl}});return n(r),G.info("ACP client initialized successfully"),()=>{G.debug("Disconnecting ACP client"),r.disconnect().catch(d=>{G.error("Failed to disconnect ACP client",{error:d instanceof Error?d.message:String(d)})})}}catch(r){const d=r instanceof Error?r.message:"Failed to initialize ACP client";i(d),G.error("Failed to initialize ACP client",{error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}},[s.serverUrl]),{client:e,error:o,sessionId:a}}const gt=H(["pending","in_progress","completed","failed"]),wn=H(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),ht=E({path:w(),line:A().nullable().optional()}),ve=E({inputTokens:A().optional(),outputTokens:A().optional(),totalTokens:A().optional()}),xt=ze("type",[E({type:z("content"),content:E({type:z("text"),text:w()})}),E({type:z("text"),text:w()}),E({type:z("diff"),path:w(),oldText:w(),newText:w(),line:A().nullable().optional()}),E({type:z("terminal"),terminalId:w()})]),bt=E({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),kind:wn,status:gt,contentPosition:A().optional(),locations:M(ht).optional(),rawInput:L(w(),F()).optional(),rawOutput:L(w(),F()).optional(),content:M(xt).optional(),error:w().optional(),startedAt:A().optional(),completedAt:A().optional(),tokenUsage:ve.optional()}),vn=E({id:w(),status:gt.optional(),locations:M(ht).optional(),rawOutput:L(w(),F()).optional(),content:M(xt).optional(),error:w().optional(),completedAt:A().optional(),tokenUsage:ve.optional()});function Re(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 K=$("chat-store","debug"),T=Ss(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 i=o.messages.find(r=>r.id===e);let a=o.totalBilled,c=o.currentContext,f=n;if(n.tokenUsage){const r=i?.tokenUsage;K.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:r});const d={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)};K.debug("updateMessage: merged tokenUsage",{merged:d}),f={...n,tokenUsage:d};const u=d.inputTokens-(r?.inputTokens??0),h=d.outputTokens-(r?.outputTokens??0),v=d.totalTokens-(r?.totalTokens??0);a={inputTokens:o.totalBilled.inputTokens+u,outputTokens:o.totalBilled.outputTokens+h,totalTokens:o.totalBilled.totalTokens+v},c={inputTokens:d.inputTokens,outputTokens:o.currentContext.outputTokens+h,totalTokens:d.totalTokens}}const p=o.messages.map(r=>r.id===e?{...r,...f}:r);if(n.tokenUsage&&f.tokenUsage){const r=i?.tokenUsage,d=f.tokenUsage,u=(d.inputTokens??0)-(r?.inputTokens??0),h=(d.outputTokens??0)-(r?.outputTokens??0),v=(d.totalTokens??0)-(r?.totalTokens??0),m=p.filter(y=>y.tokenUsage).map(y=>({id:y.id,role:y.role,tokens:y.tokenUsage})),x=p.reduce((y,N)=>({inputTokens:y.inputTokens+(N.tokenUsage?.inputTokens??0),outputTokens:y.outputTokens+(N.tokenUsage?.outputTokens??0),totalTokens:y.totalTokens+(N.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),b=x.inputTokens===a.inputTokens&&x.outputTokens===a.outputTokens&&x.totalTokens===a.totalTokens;K.debug("updateMessage: tokenUsage update",{messageId:e,updates:n.tokenUsage,existing:r,messageMax:d,delta:{inputDelta:u,outputDelta:h,totalDelta:v},totalBilled:a,currentContext:c,actualSum:x,billedCorrect:b?"✅":"❌",messageCount:p.length,messagesWithTokens:m.length,breakdown:m})}return{messages:p,totalBilled:a,currentContext:c}}),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(p=>p.role==="assistant");if(o===-1){K.debug("No assistant message found, creating one for tool call at position 0");const p={id:`msg_${Date.now()}_assistant`,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,toolCalls:[{...e,contentPosition:0}]};return{messages:[...n.messages,p]}}const i=[...n.messages],a=i[o];if(!a)return n;const c=a.content.length,f={...e,contentPosition:c};return i[o]={...a,toolCalls:[...a.toolCalls||[],f]},{messages:i}}),updateToolCallInCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(d=>d.role==="assistant");if(o===-1)return K.warn("No assistant message found to update tool call in"),n;const i=[...n.messages],a=i[o];if(!a)return n;const c=a.toolCalls||[],f=c.findIndex(d=>d.id===e.id);if(f===-1)return K.warn(`Tool call ${e.id} not found in message`),n;const p=c[f];if(!p)return n;const r=[...c];return r[f]=Re(p,e),i[o]={...a,toolCalls:r},{messages:i}}),updateToolCall:(e,n)=>s(o=>{const i=o.toolCalls[e]||[],a=i.findIndex(p=>p.id===n.id);if(a===-1)return o;const c=i[a];if(!c)return o;const f=[...i];return f[a]=Re(c,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,i)=>i!==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"],i=(n.indexOf(e.tokenDisplayMode)+1)%n.length,a=n[i];return a?{tokenDisplayMode:a}:e}),addLog:e=>s(n=>({logs:[...n.logs,e]})),clearLogs:()=>s({logs:[]}),setActiveTab:e=>s({activeTab:e})})),X=$("use-chat-messages","debug");function yt(s,e){const n=T(u=>u.messages),o=T(u=>u.isStreaming),i=T(u=>u.sessionId),a=T(u=>u.setIsStreaming),c=T(u=>u.setStreamingStartTime),f=T(u=>u.addMessage),p=T(u=>u.updateMessage),r=T(u=>u.setError),d=l.useCallback(async u=>{if(!s){X.error("No client available"),r("No client available");return}let h=i;if(!h){X.info("Creating new session before sending first message");const m=await e();if(!m){X.error("Failed to create session"),r("Failed to create session");return}h=m,X.info("Session created successfully",{sessionId:m})}const v=`msg_${Date.now()}_assistant`;try{const m=Date.now();a(!0),c(m);const x={id:`msg_${Date.now()}_user`,role:"user",content:u,timestamp:new Date().toISOString(),isStreaming:!1};f(x);const b={id:v,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:m};f(b);const y=s.receiveMessages();s.sendMessage(u,h).catch(C=>{const I=C instanceof Error?C.message:String(C);r(I),a(!1),c(null)});let N="",j=!1;for await(const C of y)if(C.tokenUsage&&X.debug("chunk.tokenUsage",{tokenUsage:C.tokenUsage}),C.isComplete){p(v,{content:N,isStreaming:!1,streamingStartTime:void 0,...C.tokenUsage?{tokenUsage:C.tokenUsage}:{}}),a(!1),c(null),j=!0;break}else C.contentDelta.type==="text"&&(N+=C.contentDelta.text,p(v,{content:N,...C.tokenUsage?{tokenUsage:C.tokenUsage}:{}}),await new Promise(I=>setTimeout(I,16)));j||(X.warn("Stream ended without isComplete flag"),p(v,{isStreaming:!1,streamingStartTime:void 0}),a(!1),c(null))}catch(m){const x=m instanceof Error?m.message:String(m);r(x),a(!1),c(null),p(v,{isStreaming:!1,streamingStartTime:void 0})}},[s,i,e,f,p,a,c,r]);return{messages:n,isStreaming:o,sendMessage:d}}const Nn=$("use-chat-input","debug");function Sn(s,e){const n=T(h=>h.input),o=T(h=>h.setInputValue),i=T(h=>h.setInputSubmitting),a=T(h=>h.addFileAttachment),c=T(h=>h.removeFileAttachment),{sendMessage:f}=yt(s,e),p=l.useCallback(h=>{o(h)},[o]),r=l.useCallback(async()=>{if(!n.value.trim()||n.isSubmitting)return;const h=n.value;o(""),i(!0);try{await f(h)}catch(v){Nn.error("Failed to send message",{error:v instanceof Error?v.message:String(v)})}finally{i(!1)}},[n,o,i,f]),d=l.useCallback(h=>{a(h)},[a]),u=l.useCallback(h=>{c(h)},[c]);return{value:n.value,isSubmitting:n.isSubmitting,attachedFiles:n.attachedFiles,onChange:p,onSubmit:r,onAttachFile:d,onRemoveFile:u}}const W=$("use-chat-session","debug");function jn(s,e){const n=T(m=>m.connectionStatus),o=T(m=>m.sessionId),i=T(m=>m.setConnectionStatus),a=T(m=>m.setSessionId),c=T(m=>m.setError),f=T(m=>m.clearMessages),p=T(m=>m.resetTokens),r=T(m=>m.addMessage);l.useEffect(()=>s?s.onSessionUpdate(x=>{if(x.message&&(W.debug("Session update with message",{message:x.message}),x.message.role!=="tool")){const b=x.message.content.map(j=>j.type==="text"?j.text:"").join(""),y=T.getState().messages,N=y[y.length-1];if(x.message.role==="assistant"&&N?.role==="assistant"&&N.content===""&&b)W.debug("Appending text to existing assistant message"),T.getState().updateMessage(N.id,{content:N.content+b});else{const j={id:x.message.id,role:x.message.role,content:b,timestamp:x.message.timestamp,isStreaming:!1};r(j)}}}):void 0,[s,r]);const d=l.useCallback(async()=>{if(!s){c("No client available");return}try{i("connecting"),c(null),await s.connect(),i("connected")}catch(m){W.error("Failed to connect",{error:m instanceof Error?m.message:String(m)});const x=m instanceof Error?m.message:String(m);c(x),i("error")}},[s,i,c]),u=l.useCallback(async m=>{if(!s){c("No client available");return}try{i("connecting"),c(null);const x=await s.loadSession(m);a(x),i("connected"),p(),W.info("Session loaded successfully",{sessionId:x})}catch(x){W.warn("Failed to load session, creating new one instead",{sessionId:m,error:x instanceof Error?x.message:String(x)});try{await d();const b=await s.startSession();if(a(b),f(),p(),typeof window<"u"){const y=new URL(window.location.href);y.searchParams.set("session",b),window.history.replaceState({},"",y.toString())}W.info("Created new session after failed load",{sessionId:b})}catch(b){const y=b instanceof Error?b.message:String(b);c(`Failed to load or create session: ${y}`),i("error")}}},[s,i,a,c,f,p,d]),h=l.useCallback(async()=>{if(!s)return c("No client available"),null;try{const m=await s.startSession();if(a(m),f(),p(),typeof window<"u"){const x=new URL(window.location.href);x.searchParams.set("session",m),window.history.pushState({},"",x.toString())}return m}catch(m){const x=m instanceof Error?m.message:String(m);return c(x),null}},[s,a,c,f,p]),v=l.useCallback(async()=>{if(s)try{await s.disconnect(),i("disconnected"),a(null)}catch(m){const x=m instanceof Error?m.message:String(m);c(x)}},[s,i,a,c]);return l.useEffect(()=>{!s||n!=="disconnected"||(e?(W.info("Loading initial session from URL",{sessionId:e}),u(e)):d())},[s,n,e,d,u]),{connectionStatus:n,sessionId:o,connect:d,loadSession:u,startSession:h,disconnect:v}}function Cn(s){const e=T(c=>c.toolCalls),n=T(c=>c.addToolCall),o=T(c=>c.updateToolCall),i=T(c=>c.addToolCallToCurrentMessage),a=T(c=>c.updateToolCallInCurrentMessage);return l.useEffect(()=>{if(!s)return;const c=s.onSessionUpdate(f=>{f.type==="tool_call"?(n(f.sessionId,f.toolCall),i(f.toolCall)):f.type==="tool_call_update"&&(o(f.sessionId,f.toolCallUpdate),a(f.toolCallUpdate))});return()=>{c()}},[s,n,o,i,a]),{toolCalls:e,getToolCallsForSession:c=>{const f=e[c];return f&&f.length>0?f:Object.values(e).flat()}}}const kn=E({id:w(),role:H(["user","assistant","system"]),content:w(),timestamp:ce(),isStreaming:ee().default(!1),streamingStartTime:A().optional(),metadata:L(w(),F()).optional(),toolCalls:M(bt).optional(),tokenUsage:ve.optional()}),Tn=E({value:w(),isSubmitting:ee(),attachedFiles:M(E({name:w(),path:w(),size:A(),mimeType:w()}))});E({sessionId:w().nullable(),isConnected:ee(),isStreaming:ee(),messages:M(kn),input:Tn,error:w().nullable()});H(["disconnected","connecting","connected","error"]);const In=E({name:w(),description:w().optional(),parameters:L(w(),F()).optional()}),En=E({name:w(),description:w(),parameters:L(w(),F()),required:M(w()).optional()}),Rn=E({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:M(In).optional(),tools:M(En).optional(),supportedFormats:M(w()).optional()}),An=H(["initializing","ready","busy","error","terminated"]);E({status:An,info:Rn.optional(),pid:A().optional(),error:w().optional(),uptime:A().optional()});const wt=H(["user","assistant","system","tool"]),Mn=H(["text","image","file","tool_call","tool_result"]),ne=E({type:Mn}),Un=ne.extend({type:z("text"),text:w()}),Dn=ne.extend({type:z("image"),url:w().url().optional(),data:w().optional(),mimeType:w().optional()}),Pn=ne.extend({type:z("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:A().optional()}),zn=ne.extend({type:z("tool_call"),id:w(),name:w(),arguments:L(w(),F())}),_n=ne.extend({type:z("tool_result"),callId:w(),result:F(),error:w().optional()}),vt=ze("type",[Un,Dn,Pn,zn,_n]),Nt=E({id:w(),role:wt,content:M(vt),timestamp:ce(),metadata:L(w(),F()).optional()});E({id:w(),role:wt,contentDelta:vt,isComplete:ee(),tokenUsage:E({inputTokens:A().optional(),outputTokens:A().optional(),totalTokens:A().optional()}).optional()});const St=H(["idle","connecting","connected","active","streaming","error","disconnected"]),Ln=E({agentPath:w(),agentArgs:M(w()).optional(),environment:L(w(),w()).optional(),workingDirectory:w().optional(),timeout:A().optional()}),Fn=E({agentName:w().optional(),agentVersion:w().optional(),capabilities:M(w()).optional(),startedAt:ce(),lastActivityAt:ce().optional()});E({id:w(),status:St,config:Ln,metadata:Fn.optional(),messages:M(Nt),error:w().optional()});const de=E({sessionId:w(),status:St.optional(),message:Nt.optional(),error:w().optional()}),On=de.extend({type:z("tool_call"),toolCall:bt,messageId:w().optional()}),Bn=de.extend({type:z("tool_call_update"),toolCallUpdate:vn,messageId:w().optional()}),Hn=de.extend({type:z("tool_output"),toolOutput:E({id:w(),content:M(js()).optional(),rawOutput:L(w(),F()).optional()}),messageId:w().optional()}),$n=de.extend({type:z("generic").optional()});Cs([On,Bn,Hn,$n]);const Wn=[{id:"folder-1",name:"Item 1",type:"folder",children:[{id:"file-1-1",name:"Item 2",type:"file",extension:"tsx"},{id:"file-1-2",name:"Item 3",type:"file",extension:"ts"},{id:"file-1-3",name:"Item 4",type:"file",extension:"json"},{id:"file-1-4",name:"Item 5",type:"file",extension:"md"}]},{id:"folder-2",name:"Description 1",type:"folder",children:[{id:"file-2-1",name:"Description 2",type:"file",extension:"tsx"},{id:"file-2-2",name:"Description 3",type:"file",extension:"ts"},{id:"file-2-3",name:"Description 4",type:"file",extension:"json"},{id:"file-2-4",name:"Description 5",type:"file",extension:"md"}]},{id:"folder-3",name:"financial-docs",type:"folder",children:[]}];class Vn{data;constructor(e=Wn){this.data=e}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(e){const n=i=>{for(const a of i){if(a.id===e)return a;if(a.children){const c=n(a.children);if(c)return c}}},o=n(this.data);return Promise.resolve(o?.children||[])}async getItemDetails(e){const n=i=>{for(const a of i){if(a.id===e)return a;if(a.children){const c=n(a.children);if(c)return c}}},o=n(this.data);if(!o)throw new Error(`Item with id ${e} not found`);return Promise.resolve(o)}}const qn=[{id:"1",title:"Boeing Scores Early Wins at Dubai Airshow",url:"https://www.reuters.com/business/aerospace-defense/boeing-scores-early-wins-dubai-airshow-2024-11-17",snippet:"DUBAI, Nov 17 (Reuters) - Boeing (BA.N), opens new tab took centre stage at day one of the Dubai Airshow on Monday, booking a $38 billion order from host carrier Emirates and clinching more deals with African carriers, while China displayed its C919 in the Middle East for the first time.",sourceName:"Reuters",favicon:"https://www.reuters.com/favicon.ico"},{id:"2",title:"Boeing's Sustainable Aviation Goals Take Flight",url:"https://www.forbes.com/boeing-sustainability",snippet:"SEATTLE, Nov 18 (Reuters) - Boeing is making headway towards its sustainability targets, unveiling plans for a new eco-friendly aircraft design aimed at reducing emissions by 50% by 2030.",sourceName:"Forbes"},{id:"3",title:"Boeing Faces Increased Competition in Global Aviation Market",url:"https://www.reuters.com/business/aerospace-defense/boeing-competition-2024-11-19",snippet:"CHICAGO, Nov 19 (Reuters) - As the global aviation industry rebounds post-pandemic, Boeing is grappling with intensified competition from rival manufacturers, particularly in the Asian market.",sourceName:"Reuters",favicon:"https://www.reuters.com/favicon.ico"},{id:"4",title:"Boeing's Starliner Successfully Completes Orbital Test Flight",url:"https://www.theverge.com/boeing-starliner",snippet:"NASA, Nov 20 (Reuters) - Boeing's CST-100 Starliner spacecraft achieves a significant milestone, successfully completing its orbital test flight, paving the way for future crewed missions to the International Space Station.",sourceName:"The Verge"}],Qn=[{id:"todo-1",text:"Review filesystem implementation",status:"completed"},{id:"todo-2",text:"Add overflow menu actions",status:"in_progress"},{id:"todo-3",text:"Connect to real filesystem API",status:"pending"},{id:"todo-4",text:"Implement drag and drop support",status:"pending"},{id:"todo-5",text:"Add file preview functionality",status:"pending"}];function g(...s){return ks(Ts(s))}const Gn=q("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-paragraph-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-hover",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive-hover",outline:"border border-input bg-background hover:bg-accent-hover hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover",ghost:"hover:bg-accent-hover 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"}}),J=l.forwardRef(({className:s,variant:e,size:n,asChild:o=!1,...i},a)=>{const c=o?te:"button";return t.jsx(c,{className:g(Gn({variant:e,size:n,className:s})),ref:a,...i})});J.displayName="Button";const Kn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));Kn.displayName="Card";const Xn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex flex-col space-y-1.5 p-6",s),...e}));Xn.displayName="CardHeader";const Jn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-2xl font-semibold leading-none tracking-tight",s),...e}));Jn.displayName="CardTitle";const Yn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-sm text-muted-foreground",s),...e}));Yn.displayName="CardDescription";const Zn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("p-6 pt-0",s),...e}));Zn.displayName="CardContent";const eo=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex items-center p-6 pt-0",s),...e}));eo.displayName="CardFooter";const jt=l.forwardRef(({title:s,description:e,guideUrl:n,guideText:o="Guide",suggestedPrompts:i=[],onPromptClick:a,onGuideClick:c,onOpenFiles:f,onPromptHover:p,onPromptLeave:r,className:d,...u},h)=>{const v=b=>{a?.(b)},m=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),c?.()},x=[];for(let b=0;b<i.length;b+=2)x.push(i.slice(b,b+2));return t.jsxs("div",{ref:h,className:g("flex flex-col items-start",d),...u,children:[t.jsx("h3",{className:"text-heading-4 text-text-primary mb-6",children:s}),t.jsx("p",{className:"text-subheading text-text-secondary max-w-prose mb-6",children:e}),f&&t.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors mb-6",children:[t.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:"View Files"}),t.jsx(xe,{className:"size-4 text-foreground shrink-0"})]}),(n||c)&&t.jsxs("button",{type:"button",onClick:m,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:o}),t.jsx(xe,{className:"size-4 text-foreground shrink-0"})]}),i.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:x.map(b=>t.jsx("div",{className:"flex gap-2.5 items-center",children:b.map(y=>t.jsx("button",{type:"button",onClick:()=>v(y),onMouseEnter:()=>p?.(y),onMouseLeave:()=>r?.(),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-paragraph font-normal leading-normal text-text-tertiary truncate",children:y})},y))},b.join("-")))})]})]})});jt.displayName="ChatEmptyState";const Ct=l.createContext(void 0),Ne=()=>{const s=l.useContext(Ct);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},kt=l.forwardRef(({defaultExpanded:s=!1,expanded:e,onExpandedChange:n,className:o,children:i,...a},c)=>{const[f,p]=l.useState(s),r=e??f,d=l.useCallback(m=>{p(m),n?.(m)},[n]),u=l.Children.toArray(i),h=u.find(m=>l.isValidElement(m)&&typeof m.type=="function"&&m.type.displayName==="ChatHeader.ExpandablePanel"),v=u.filter(m=>m!==h);return t.jsxs(Ct.Provider,{value:{isExpanded:r,setIsExpanded:d},children:[t.jsx("div",{ref:c,className:g("flex items-center justify-between px-6 py-4",o),...a,children:v}),h]})});kt.displayName="ChatHeader.Root";const to=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("h1",{ref:o,className:g("m-0 text-subheading font-semibold",s),...n,children:e}));to.displayName="ChatHeader.Title";const so=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center gap-3",s),...n,children:e}));so.displayName="ChatHeader.Actions";const no=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"}},oo=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},ro=l.forwardRef(({status:s,statusText:e,className:n,...o},i)=>{const a=e??oo(s),c=no(s);return t.jsxs("div",{ref:i,className:g("flex items-center gap-2",n),...o,children:[t.jsx("div",{className:g("h-2 w-2 rounded-full",c)}),t.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:a})]})});ro.displayName="ChatHeader.StatusIndicator";const ao=l.forwardRef(({icon:s,className:e,children:n,onClick:o,...i},a)=>{const{isExpanded:c,setIsExpanded:f}=Ne(),p=r=>{f(!c),o?.(r)};return t.jsxs("button",{ref:a,type:"button",onClick:p,className:g("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":c?"Collapse header":"Expand header",...i,children:[s&&t.jsx("div",{className:g("transition-transform duration-200",c&&"rotate-180"),children:s}),n]})});ao.displayName="ChatHeader.Toggle";const Tt=l.forwardRef(({className:s,children:e,...n},o)=>{const{isExpanded:i}=Ne();return i?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});Tt.displayName="ChatHeader.ExpandablePanel";const It=l.forwardRef(({commands:s=[],showCommandMenu:e,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:i,setMenuItemCount:a,triggerCounter:c,onChange:f,className:p,...r},d)=>{const u=l.useCallback((v,m)=>{const x=v.toLowerCase(),b=m.toLowerCase();if(!m)return 1;if(x.includes(b))return 1-b.length/x.length;let y=0;for(let N=0;N<x.length&&y<b.length;N++)x[N]===b[y]&&y++;return y===b.length?.5-y/x.length:0},[]),h=l.useMemo(()=>s.map(v=>({...v,score:Math.max(u(v.label,n),v.description?u(v.description,n):0)})).filter(v=>v.score>0).sort((v,m)=>m.score-v.score),[s,n,u]);return l.useEffect(()=>{a(h.length)},[h.length,a]),l.useEffect(()=>{i(0)},[i]),l.useEffect(()=>{c>0&&h[o]&&(h[o].onSelect(),f(""))},[c,h,o,f]),!e||h.length===0?null:t.jsxs("div",{ref:d,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-caption font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),t.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map((v,m)=>t.jsxs("button",{type:"button",onClick:()=>v.onSelect(),className:g("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",m===o&&"bg-muted"),children:[v.icon&&t.jsx("span",{className:"shrink-0 mt-0.5",children:v.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-medium",children:v.label}),v.description&&t.jsx("div",{className:"text-caption text-muted-foreground truncate",children:v.description})]})]},v.id))})]})});It.displayName="ChatInputCommandMenu";const Et=l.createContext(void 0),ue=()=>{const s=l.useContext(Et);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},Rt=l.forwardRef(({client:s,startSession:e,value:n,onChange:o,onSubmit:i,disabled:a=!1,isSubmitting:c,submitOnEnter:f=!0,className:p,children:r,...d},u)=>{const h=l.useRef(null),v=l.useCallback(async()=>Promise.resolve(null),[]),m=Sn(s??null,e??v),x=T(D=>D.isStreaming),b=s&&e,y=b?m.value:n||"",N=b?m.onChange:o||(()=>{}),j=b?m.onSubmit:i||(async()=>{}),C=b?m.isSubmitting||x:c||!1,[I,U]=l.useState(!1),[S,R]=l.useState(""),[P,Q]=l.useState(0),[B,ls]=l.useState(0),[cs,ds]=l.useState(0),us=l.useCallback(()=>{ds(D=>D+1)},[]),ps=async D=>{D.preventDefault(),y.trim()&&!C&&!a&&(await j(),setTimeout(()=>{h.current?.focus()},0))},fs=D=>{const O=D.target;!(O.tagName==="BUTTON"||O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.closest("button"))&&h.current&&h.current.focus()},ms=D=>{const O=D.target;!(O.tagName==="BUTTON"||O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.closest("button"))&&D.key===" "&&(D.preventDefault(),h.current&&h.current.focus())};return l.useEffect(()=>{const D=document.querySelector('textarea[name="chat-input"]');D&&h.current!==D&&(h.current=D)},[]),l.useEffect(()=>{!y&&h.current&&(h.current.style.height="auto",h.current.style.overflowY="hidden")},[y]),t.jsx(Et.Provider,{value:{value:y,onChange:N,onSubmit:j,disabled:a,isSubmitting:C,submitOnEnter:f,showCommandMenu:I,setShowCommandMenu:U,commandMenuQuery:S,setCommandMenuQuery:R,selectedMenuIndex:P,setSelectedMenuIndex:Q,menuItemCount:B,setMenuItemCount:ls,triggerMenuSelect:us,triggerCounter:cs},children:t.jsx("form",{ref:u,onSubmit:ps,onClick:fs,onKeyDown:ms,className:g("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...d,children:r})})});Rt.displayName="ChatInput.Root";const At=l.forwardRef(({asChild:s=!1,className:e,onKeyDown:n,children:o,...i},a)=>{const{value:c,onChange:f,onSubmit:p,disabled:r,isSubmitting:d,submitOnEnter:u,showCommandMenu:h,setShowCommandMenu:v,setCommandMenuQuery:m,setSelectedMenuIndex:x,menuItemCount:b,triggerMenuSelect:y}=ue(),N=l.useRef(null),U={ref:l.useCallback(S=>{N.current=S,typeof a=="function"?a(S):a&&(a.current=S)},[a]),name:"chat-input",value:c,onChange:S=>{const R=S.target.value;if(f(R),R.startsWith("/")&&!R.includes(`
|
|
6
|
-
`)){v(!0);const B=R.slice(1);m(B)}else v(!1),m("");const P=N.current;if(!P)return;P.style.height="auto";const Q=Math.min(P.scrollHeight,164);P.style.height=`${Q}px`,P.scrollHeight>164?P.style.overflowY="auto":P.style.overflowY="hidden"},onKeyDown:S=>{if(h&&b>0){if(S.key==="ArrowDown"){S.preventDefault(),x(R=>(R+1)%b);return}else if(S.key==="ArrowUp"){S.preventDefault(),x(R=>(R-1+b)%b);return}else if(S.key==="Enter"&&!S.shiftKey){S.preventDefault(),y();return}else if(S.key==="Escape"){S.preventDefault(),v(!1),m("");return}}u&&S.key==="Enter"&&!S.shiftKey&&(c.trim()&&!d&&!r?(S.preventDefault(),p()):(d||r)&&S.preventDefault()),n?.(S)},disabled:r,...i};return s&&l.isValidElement(o)?l.cloneElement(o,U):t.jsx("textarea",{...U,rows:1,className:g("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 max-h-[6lh] min-h-[44px]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-paragraph-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});At.displayName="ChatInput.Field";const Mt=l.forwardRef(({asChild:s=!1,className:e,disabled:n,children:o,...i},a)=>{const{value:c,disabled:f,isSubmitting:p}=ue(),r=n||f||p||!c.trim(),d=s?te:J;return t.jsx(d,{ref:a,type:"submit",disabled:r,variant:s?void 0:"default",size:"icon",className:g(!s&&"gap-1.5 rounded-full",e),...i,children:o})});Mt.displayName="ChatInput.Submit";const Ut=l.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}));Ut.displayName="ChatInput.Toolbar";const Dt=l.forwardRef(({asChild:s=!1,className:e,children:n,onClick:o,...i},a)=>{const{value:c,onChange:f,setShowCommandMenu:p,setCommandMenuQuery:r}=ue(),d=h=>{c.startsWith("/")||(f("/"),p(!0),r("")),o?.(h)},u=s?te:J;return t.jsx(u,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),onClick:d,...i,children:n||t.jsx($s,{className:"size-4"})})});Dt.displayName="ChatInput.Actions";const Pt=l.forwardRef(({asChild:s=!1,className:e,children:n,...o},i)=>{const a=s?te:J;return t.jsx(a,{ref:i,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(Ws,{className:"size-4"})})});Pt.displayName="ChatInput.Attachment";const zt=l.forwardRef(({asChild:s=!1,className:e,children:n,...o},i)=>{const a=s?te:J;return t.jsx(a,{ref:i,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(Vs,{className:"size-4"})})});zt.displayName="ChatInput.VoiceInput";const _t=l.forwardRef(({commands:s=[],className:e,onChange:n,...o},i)=>{const{showCommandMenu:a,commandMenuQuery:c,selectedMenuIndex:f,setSelectedMenuIndex:p,setMenuItemCount:r,triggerCounter:d,onChange:u}=ue();return t.jsx(It,{ref:i,commands:s,showCommandMenu:a,commandMenuQuery:c,selectedMenuIndex:f,setSelectedMenuIndex:p,setMenuItemCount:r,triggerCounter:d,onChange:u,className:e,...o})});_t.displayName="ChatInput.CommandMenu";const io=({className:s,...e})=>t.jsx(hs,{className:g("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...e}),Lt=({className:s,...e})=>t.jsx(xs,{className:g(s),...e}),lo=({withHandle:s,className:e,...n})=>t.jsx(bs,{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"})]})})}),co=({...s})=>t.jsx(Is,{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}),Ft=l.createContext(void 0),oe=()=>{const s=l.useContext(Ft);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},Ot=l.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:e="hidden",defaultActiveTab:n="todo",className:o,children:i,...a},c)=>{const[f,p]=l.useState(s),[r,d]=l.useState(e),[u,h]=l.useState(n);return t.jsx(Ft.Provider,{value:{sidebarOpen:f,setSidebarOpen:p,panelSize:r,setPanelSize:d,activeTab:u,setActiveTab:h},children:t.jsx("div",{ref:c,className:g("flex h-screen flex-row bg-background text-foreground",o),...a,children:t.jsx(io,{direction:"horizontal",className:"flex-1",children:i})})})});Ot.displayName="ChatLayout.Root";const uo=l.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}));uo.displayName="ChatLayout.Header";const Bt=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx(Lt,{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})}));Bt.displayName="ChatLayout.Main";const Ht=l.forwardRef(({showToaster:s=!0,className:e,children:n,...o},i)=>t.jsxs("div",{ref:i,className:g("relative flex flex-1 flex-col overflow-hidden",e),...o,children:[n,s&&t.jsx(co,{})]}));Ht.displayName="ChatLayout.Body";const $t=l.forwardRef(({className:s,children:e,onScrollChange:n,showScrollToBottom:o=!0,...i},a)=>{const[c,f]=l.useState(!1),p=l.useRef(null),r=l.useRef(!0),d=l.useRef(!1);l.useImperativeHandle(a,()=>p.current);const u=l.useCallback(()=>{const b=p.current;if(!b)return!1;const{scrollTop:y,scrollHeight:N,clientHeight:j}=b,I=N-y-j<100;return f(!I&&o),n?.(I),I},[n,o]),h=l.useCallback(()=>{if(d.current)return;const b=u();r.current=b},[u]),v=l.useCallback((b=!0)=>{const y=p.current;y&&(d.current=!0,r.current=!0,y.scrollTo({top:y.scrollHeight,behavior:b?"smooth":"auto"}),setTimeout(()=>{d.current=!1},b?300:0))},[]);l.useEffect(()=>{p.current&&(r.current&&!d.current&&requestAnimationFrame(()=>{v(!1)}),d.current||u())},[e,v,u]),l.useEffect(()=>{if(!d.current){const b=u();r.current=b}},[u]);const m=l.useCallback(()=>{d.current=!1;const b=p.current;if(!b)return;const{scrollTop:y,scrollHeight:N,clientHeight:j}=b;N-y-j>=100&&(r.current=!1)},[]),x=l.useCallback(b=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"].includes(b.key)&&(d.current=!1,requestAnimationFrame(()=>{const N=p.current;if(!N)return;const{scrollTop:j,scrollHeight:C,clientHeight:I}=N,U=C-j-I;r.current=U<100}))},[]);return t.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[t.jsx("div",{ref:p,className:g("h-full overflow-y-auto flex flex-col",s),onScroll:h,onWheel:m,onTouchStart:m,onKeyDown:x,tabIndex:0,...i,children:t.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:e})}),c&&t.jsx("button",{type:"button",onClick:()=>v(!0),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(qs,{className:"size-4"})})]})});$t.displayName="ChatLayout.Messages";const Wt=l.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})}));Wt.displayName="ChatLayout.Footer";const po=l.forwardRef(({className:s,children:e,...n},o)=>{const{sidebarOpen:i}=oe();return i?t.jsx("div",{ref:o,className:g("border-r border-border bg-card w-64 overflow-y-auto",s),...n,children:e}):null});po.displayName="ChatLayout.Sidebar";const Vt=l.forwardRef(({breakpoint:s="lg",className:e,children:n,...o},i)=>{const{panelSize:a}=oe(),[c,f]=l.useState(25);return l.useEffect(()=>{const p=()=>{const d=400/window.innerWidth*100;f(Math.max(d,25))};return p(),window.addEventListener("resize",p),()=>{window.removeEventListener("resize",p)}},[]),a==="hidden"?null:t.jsxs(t.Fragment,{children:[t.jsx(lo,{withHandle:!0,className:"group-hover:opacity-100 opacity-0 transition-opacity"}),t.jsx(Lt,{defaultSize:25,minSize:c,maxSize:35,className:"group",children:t.jsx("div",{ref:i,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})})]})});Vt.displayName="ChatLayout.Aside";const fo=Rs,mo=As,go=l.forwardRef(({className:s,inset:e,children:n,...o},i)=>t.jsxs(_e,{ref:i,className:g("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",s),...o,children:[n,t.jsx(xe,{className:"ml-auto h-4 w-4"})]}));go.displayName=_e.displayName;const ho=l.forwardRef(({className:s,...e},n)=>t.jsx(Le,{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}));ho.displayName=Le.displayName;const qt=l.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(Es,{children:t.jsx(Fe,{ref:o,sideOffset:e,className:g("z-50 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-popover p-0.5 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})}));qt.displayName=Fe.displayName;const ae=l.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(Oe,{ref:o,className:g("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-paragraph-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}));ae.displayName=Oe.displayName;const xo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Be,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-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(He,{children:t.jsx(lt,{className:"h-4 w-4"})})}),e]}));xo.displayName=Be.displayName;const bo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs($e,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-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(He,{children:t.jsx(be,{className:"h-2 w-2 fill-current"})})}),e]}));bo.displayName=$e.displayName;const yo=l.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(We,{ref:o,className:g("px-2 py-1.5 text-paragraph-sm font-semibold",e&&"pl-8",s),...n}));yo.displayName=We.displayName;const Qt=l.forwardRef(({className:s,...e},n)=>t.jsx(Ve,{ref:n,className:g("-mx-1 my-1 h-px bg-border",s),...e}));Qt.displayName=Ve.displayName;function Gt({item:s,level:e=0,onSelect:n,selectedId:o,isDropTarget:i=!1,onDownload:a,onRename:c,onDelete:f}){const[p,r]=l.useState(!0),d=o===s.id,u=()=>{s.type==="folder"&&r(!p)},h=()=>{n?.(s),s.type==="folder"&&u()},v=x=>{x.key==="Enter"||x.key===" "?(x.preventDefault(),h()):x.key==="ArrowRight"&&s.type==="folder"&&!p?(x.preventDefault(),r(!0)):x.key==="ArrowLeft"&&s.type==="folder"&&p&&(x.preventDefault(),r(!1))},m=()=>e===0?"p-2":e===1?"pl-8 pr-2 py-2":"pl-16 pr-2 py-2";return t.jsxs("div",{className:"flex flex-col w-full",children:[t.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":s.type==="folder"?p:void 0,className:g("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",m(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",d&&"bg-accent",i&&["bg-accent","border border-dashed border-border-dark"]),onClick:h,onKeyDown:v,children:[t.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:s.type==="folder"?p?t.jsx(Qs,{className:"size-4"}):t.jsx(Gs,{className:"size-4"}):t.jsx(Ks,{className:"size-4"})}),t.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:s.name}),t.jsxs(fo,{children:[t.jsx(mo,{asChild:!0,children:t.jsx("button",{className:g("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:x=>{x.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:t.jsx(Xs,{className:"size-4"})})}),t.jsxs(qt,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:x=>x.stopPropagation(),children:[a&&t.jsx(ae,{onClick:x=>{x.stopPropagation(),a(s)},children:"Download"}),c&&t.jsx(ae,{onClick:x=>{x.stopPropagation(),c(s)},children:"Rename"}),(a||c)&&f&&t.jsx(Qt,{}),f&&t.jsx(ae,{className:"text-destructive focus:text-destructive focus:bg-muted",onClick:x=>{x.stopPropagation(),f(s)},children:t.jsx("span",{className:"text-paragraph-sm",children:"Delete"})})]})]}),s.type==="folder"&&t.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-muted-foreground",children:t.jsx(se,{className:g("size-4 transition-transform",!p&&"-rotate-90")})})]}),s.type==="folder"&&p&&s.children&&t.jsx("div",{className:"flex flex-col",children:s.children.map(x=>t.jsx(Gt,{item:x,level:e+1,...n&&{onSelect:n},...o&&{selectedId:o},...a&&{onDownload:a},...c&&{onRename:c},...f&&{onDelete:f}},x.id))})]})}const wo=new Vn;function vo({className:s,provider:e=wo,onItemSelect:n,onDownload:o,onRename:i,onDelete:a}){const[c,f]=l.useState([]),[p,r]=l.useState(),[d,u]=l.useState(!0),[h,v]=l.useState();l.useEffect(()=>{(async()=>{try{u(!0);const b=await e.getRootItems();f(b),v(void 0)}catch(b){v(b instanceof Error?b.message:"Failed to load items")}finally{u(!1)}})()},[e]);const m=x=>{r(x.id),n?.(x)};return d?t.jsx("div",{className:g("",s),children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):h?t.jsx("div",{className:g("",s),children:t.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",h]})}):t.jsx("div",{className:g("flex flex-col",s),children:c.length===0?t.jsx("p",{className:"text-sm text-muted-foreground",children:"No items found"}):c.map(x=>t.jsx(Gt,{item:x,onSelect:m,...p&&{selectedId:p},...o&&{onDownload:o},...i&&{onRename:i},...a&&{onDelete:a}},x.id))})}const Kt=l.forwardRef(({source:s,isSelected:e,className:n,...o},i)=>t.jsxs("button",{ref:i,type:"button",className:g("group flex w-full text-left gap-2 items-start p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",e&&"bg-accent",n),onClick:()=>window.open(s.url,"_blank"),...o,children:[t.jsx("div",{className:"shrink-0 flex items-center h-5",children:t.jsx("div",{className:"relative rounded-[3px] size-4 overflow-hidden bg-muted",children:s.favicon?t.jsx("img",{alt:s.sourceName,className:"size-full object-cover",src:s.favicon}):t.jsx("div",{className:"size-full bg-muted"})})}),t.jsxs("div",{className:"flex flex-1 flex-col gap-1 min-w-0",children:[t.jsxs("div",{className:"text-paragraph-sm text-foreground",children:[t.jsx("span",{className:"font-medium",children:s.sourceName}),t.jsxs("span",{className:"text-muted-foreground",children:[" · ",s.title]})]}),t.jsx("p",{className:"text-paragraph-sm text-muted-foreground line-clamp-3",children:s.snippet})]})]}));Kt.displayName="SourceListItem";const Xt=l.forwardRef(({todo:s,className:e,...n},o)=>{const i=s.status==="completed";return t.jsxs("div",{ref:o,className:g("group flex items-center gap-2 p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",!1,e),role:"button",tabIndex:0,...n,children:[t.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:i?t.jsx(ct,{className:"size-4 text-muted-foreground"}):t.jsx(be,{className:"size-4 text-foreground"})}),t.jsx("p",{className:g("flex-1 text-foreground",i&&"line-through text-muted-foreground",s.status==="in_progress"&&"font-medium"),children:s.text})]})});Xt.displayName="TodoListItem";const Se=l.forwardRef(({client:s,todos:e,className:n,...o},i)=>{const a=e||[];return t.jsx("div",{ref:i,className:g("space-y-2 max-h-64 overflow-y-auto",n),...o,children:a.length===0?t.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"No tasks yet."}):a.map(c=>t.jsx(Xt,{todo:c},c.id))})});Se.displayName="TodoList";const pe=l.forwardRef(({todos:s,className:e,...n},o)=>{const i=s&&s.length>0?s:Qn;return t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:t.jsx(Se,{todos:i})})});pe.displayName="TodoTabContent";const fe=l.forwardRef(({files:s=[],provider:e,onFileSelect:n,className:o,...i},a)=>{const c=l.useCallback(r=>{console.log("Download:",r.name)},[]),f=l.useCallback(r=>{console.log("Rename:",r.name)},[]),p=l.useCallback(r=>{console.log("Delete:",r.name)},[]);return t.jsx("div",{ref:a,className:g("h-full",o),...i,children:t.jsx(vo,{...e&&{provider:e},onItemSelect:r=>{r.type==="file"&&n&&n(r.path||r.name)},onDownload:c,onRename:f,onDelete:p,className:"h-full"})})});fe.displayName="FilesTabContent";const me=l.forwardRef(({sources:s,className:e,...n},o)=>{const i=s&&s.length>0?s:qn;return t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:i.map(a=>t.jsx(Kt,{source:a},a.id))})});me.displayName="SourcesTabContent";const No=l.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-subheading",children:"Database"}),t.jsxs("div",{className:"text-paragraph-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-caption overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));No.displayName="DatabaseTabContent";const je=Ms,Y=l.forwardRef(({className:s,...e},n)=>t.jsx(qe,{ref:n,className:g("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...e}));Y.displayName=qe.displayName;const Z=l.forwardRef(({className:s,...e},n)=>t.jsx(Qe,{ref:n,className:g("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-paragraph-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}));Z.displayName=Qe.displayName;const _=l.forwardRef(({className:s,...e},n)=>t.jsx(Ge,{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}));_.displayName=Ge.displayName;const So=l.forwardRef(({client:s,todos:e,variant:n="animated",showIcons:o=!1,visibleTabs:i=["todo","files","database"],className:a,...c},f)=>{const p=e||[],[r,d]=l.useState(i[0]||"todo"),u=l.useRef(null),h=l.useRef(null);l.useEffect(()=>{const b=setTimeout(()=>{const y=u.current;if(r&&y){const N=h.current;if(N){const j=y.getBoundingClientRect(),C=N.getBoundingClientRect(),I=C.left-j.left,U=C.width,S=I/j.width*100,R=100-(I+U)/j.width*100;y.style.clipPath=`inset(0 ${R.toFixed(2)}% 0 ${S.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(b)},[r]);const m=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:ye},{id:"files",label:"Files",icon:we},{id:"database",label:"Database",icon:dt},{id:"sources",label:"Sources",icon:ut}].filter(x=>i.includes(x.id));return t.jsx("div",{ref:f,className:g("select-none",a),...c,children:t.jsxs(je,{value:r,onValueChange:d,className:"w-full",children:[n==="pills"?t.jsx(Y,{className:g("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:m.map(x=>{const b=x.icon;return t.jsxs(Z,{value:x.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&b&&t.jsx(b,{className:"size-4"}),x.label]},x.id)})}):t.jsxs("div",{className:"relative mb-4 border-border",children:[t.jsx(Y,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:m.map(x=>t.jsx(Z,{value:x.id,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:x.label},x.id))}),t.jsx("div",{ref:u,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(Y,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:m.map(x=>t.jsx(Z,{value:x.id,ref:r===x.id?h:null,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:x.label},x.id))})})]}),t.jsx(_,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?t.jsx(pe,{todos:p}):t.jsx(Se,{todos:p})}),t.jsx(_,{value:"files",className:n==="pills"?"mt-0":"",children:t.jsx(fe,{})}),t.jsx(_,{value:"database",className:n==="pills"?"mt-0":"",children:t.jsx("div",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})}),t.jsx(_,{value:"sources",className:n==="pills"?"mt-0":"",children:t.jsx(me,{})})]})})});So.displayName="ChatSecondaryPanel";const jo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex h-full flex-col",s),...n,children:e}));jo.displayName="ChatSidebar.Root";const Co=l.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}));Co.displayName="ChatSidebar.Header";const ko=l.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}));ko.displayName="ChatSidebar.Content";const To=l.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}));To.displayName="ChatSidebar.Footer";const Io=l.forwardRef(({children:s,className:e,...n},o)=>{const[i,a]=l.useState(s),[c,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 d=setTimeout(()=>{a(s),p.current=s,requestAnimationFrame(()=>{f(!1)})},150);return()=>{clearTimeout(d)}},[s]),t.jsx("span",{ref:o,className:g("text-sm text-foreground opacity-60 transition-opacity duration-300",c?"opacity-0":"opacity-60",e),...n,children:i})});Io.displayName="ChatStatus";const ie=128e3,Ae={"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:ie};function Eo(s){if(!s)return ie;if(s in Ae)return Ae[s]??ie;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:ie}function Jt(s,e){const n=Eo(e);return s/n*100}function Ro(s,e,n=1){return`${Jt(s,e).toFixed(n)}%`}const V=$("gui");function Ao({children:s}){const{setPanelSize:e,setActiveTab:n}=oe(),o=()=>{e("small"),n("files")};return t.jsx(t.Fragment,{children:s({openFiles:o})})}function Mo(){const{activeTab:s,setActiveTab:e}=oe();return t.jsxs(je,{value:s,onValueChange:n=>e(n),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(Ce,{showIcons:!0,visibleTabs:["todo","files","sources"],variant:"compact"})}),t.jsx(_,{value:"todo",className:"flex-1 p-4 mt-0",children:t.jsx(pe,{})}),t.jsx(_,{value:"files",className:"flex-1 p-4 mt-0",children:t.jsx(fe,{})}),t.jsx(_,{value:"sources",className:"flex-1 p-4 mt-0",children:t.jsx(me,{})})]})}function Uo({agentName:s,showHeader:e}){const{isExpanded:n,setIsExpanded:o}=Ne();return t.jsxs("div",{className:"flex lg:hidden items-center gap-2 flex-1",children:[e&&t.jsx("div",{className:"flex items-center gap-2 flex-1",children:t.jsx("h1",{className:"text-heading-4 text-foreground",children:s})}),!e&&t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle menu",onClick:()=>o(!n),children:t.jsx(pt,{className:g("size-4 text-muted-foreground transition-transform duration-200",n?"":"rotate-180")})})]})}function Do({agentName:s,todos:e,sources:n,showHeader:o}){const{panelSize:i,setPanelSize:a}=oe();return t.jsxs(kt,{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:[o&&t.jsx("div",{className:"flex items-center gap-2 flex-1",children:t.jsx("h1",{className:"text-heading-4 text-foreground",children:s})}),!o&&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(i==="hidden"?"small":"hidden")},children:t.jsx(en,{className:"size-4 text-muted-foreground"})})]}),t.jsx(Uo,{agentName:s,showHeader:o}),t.jsx(Tt,{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(je,{defaultValue:"todo",className:"w-full",children:[t.jsx(Ce,{showIcons:!0,visibleTabs:["todo","files","sources"],variant:"default"}),t.jsx(_,{value:"todo",className:"mt-4",children:t.jsx(pe,{todos:e})}),t.jsx(_,{value:"files",className:"mt-4",children:t.jsx(fe,{})}),t.jsx(_,{value:"sources",className:"mt-4",children:t.jsx(me,{sources:n})})]})})]})}function Po({client:s,initialSessionId:e,error:n}){const{connectionStatus:o,connect:i,sessionId:a,startSession:c}=jn(s,e),{messages:f,sendMessage:p}=yt(s,c);Cn(s);const r=T(S=>S.error),d=T(S=>S.currentModel),[u,h]=l.useState("Agent"),[v,m]=l.useState(typeof window<"u"?window.innerWidth>=1024:!0),[x,b]=l.useState("Type a message or / for commands...");l.useEffect(()=>{V.debug("Connection status changed",{status:o}),o==="error"&&r&&V.error("Connection error occurred",{error:r})},[o,r]),l.useEffect(()=>{if(s&&a){const S=s.getCurrentSession();S?.metadata?.agentName&&h(S.metadata.agentName)}},[s,a]),l.useEffect(()=>{const S=window.matchMedia("(min-width: 1024px)"),R=P=>{m(P.matches)};return m(S.matches),S.addEventListener("change",R),()=>{S.removeEventListener("change",R)}},[]);const y=S=>{b(S)},N=()=>{b("Type a message or / for commands...")};if(n)return t.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:t.jsxs("div",{className:"text-center p-8 max-w-md",children:[t.jsx("h1",{className:"text-2xl font-bold text-destructive mb-4",children:"Initialization Error"}),t.jsx("p",{className:"text-foreground mb-4",children:n}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})});const j=[],C=[{id:"1",title:"Boeing Scores Early Wins at Dubai Airshow",sourceName:"Reuters",url:"https://www.reuters.com/markets/companies/BA.N",snippet:"DUBAI, Nov 17 (Reuters) - Boeing (BA.N), opens new tab took centre stage at day one of the Dubai Airshow on Monday, booking a $38 billion order from host carrier Emirates and clinching more deals with African carriers, while China displayed its C919 in the Middle East for the first time.",favicon:"https://www.google.com/s2/favicons?domain=reuters.com&sz=32"},{id:"2",title:"Boeing's Sustainable Aviation Goals Take Flight",sourceName:"Forbes",url:"https://www.forbes.com",snippet:"SEATTLE, Nov 18 (Reuters) - Boeing is making headway towards its sustainability targets, unveiling plans for a new eco-friendly aircraft design aimed at reducing emissions by 50% by 2030.",favicon:"https://www.google.com/s2/favicons?domain=forbes.com&sz=32"},{id:"3",title:"Boeing Faces Increased Competition in Global Aviation Market",sourceName:"Reuters",url:"https://www.reuters.com",snippet:"CHICAGO, Nov 19 (Reuters) - As the global aviation industry rebounds post-pandemic, Boeing is grappling with intensified competition from rival manufacturers, particularly in the Asian market.",favicon:"https://www.google.com/s2/favicons?domain=reuters.com&sz=32"},{id:"4",title:"Boeing's Starliner Successfully Completes Orbital Test Flight",sourceName:"The Verge",url:"https://www.theverge.com",snippet:"NASA, Nov 20 (Reuters) - Boeing's CST-100 Starliner spacecraft achieves a significant milestone, successfully completing its orbital test flight, paving the way for future crewed missions to the International Space Station.",favicon:"https://www.google.com/s2/favicons?domain=theverge.com&sz=32"}],I=f.slice().reverse().find(S=>S.role==="assistant"&&S.tokenUsage)?.tokenUsage,U=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:t.jsx(Ie,{className:"h-4 w-4"}),category:"model",onSelect:()=>{V.info("User selected Sonnet 4.5 model")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:t.jsx(Ie,{className:"h-4 w-4"}),category:"model",onSelect:()=>{V.info("User selected Opus model")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:t.jsx(Js,{className:"h-4 w-4"}),category:"action",onSelect:()=>{V.info("User opened settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:t.jsx(Ys,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{V.info("User enabled code mode")}}];return t.jsxs(Ot,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[t.jsxs(Bt,{children:[t.jsx(Do,{agentName:u,todos:j,sources:C,showHeader:f.length>0}),o==="error"&&r&&t.jsx("div",{className:"border-b border-destructive/20 bg-destructive/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-paragraph-sm font-semibold text-destructive",children:"Connection Error"}),t.jsx("p",{className:"whitespace-pre-line text-paragraph-sm text-foreground",children:r})]}),t.jsx("button",{type:"button",onClick:i,className:"rounded-lg bg-destructive px-4 py-2 text-paragraph-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive-hover",children:"Retry"})]})}),t.jsxs(Ht,{children:[t.jsx($t,{children:f.length===0?t.jsx(Ao,{children:({openFiles:S})=>t.jsx("div",{className:"flex flex-1 items-center px-4",children:t.jsx(jt,{title:u,description:"This agent can help you with your tasks. Start a conversation by typing a message below.",suggestedPrompts:["Search the web for the latest news on top tech company earnings, produce a summary for each company, and then a macro trend analysis of the tech industry. Use your todo list","Explain how this works","Create a new feature","Review my changes"],onPromptClick:R=>{p(R),b("Type a message or / for commands..."),V.info("Prompt clicked",{prompt:R})},onPromptHover:y,onPromptLeave:N,onOpenFiles:S})})}):t.jsx("div",{className:"flex flex-col px-4",children:f.map((S,R)=>{const P=R===0,Q=P?null:f[R-1];let B="mt-2";return P?B="mt-2":S.role==="user"?B=(Q?.role==="user","mt-4"):S.role==="assistant"&&(B=Q?.role==="assistant"?"mt-2":"mt-6"),t.jsx(ts,{message:S,className:B,isLastMessage:R===f.length-1,children:t.jsx(ns,{message:S,thinkingDisplayStyle:"collapsible"})},S.id)})})}),t.jsx(Wt,{children:t.jsxs(Rt,{client:s,startSession:c,children:[t.jsx(_t,{commands:U}),t.jsx(At,{placeholder:x,autoFocus:!0}),t.jsxs(Ut,{children:[t.jsxs("div",{className:"flex items-baseline gap-1",children:[t.jsx(Dt,{}),t.jsx(Pt,{}),I&&t.jsx(Zt,{percentage:Jt(I.totalTokens??0,d??void 0),tokens:I.totalTokens??0,formattedPercentage:Ro(I.totalTokens??0,d??void 0)})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(zt,{}),t.jsx(Mt,{children:t.jsx(Zs,{className:"size-4"})})]})]})]})})]})]}),v&&t.jsx(Vt,{breakpoint:"lg",children:t.jsx(Mo,{})})]})}const zo=Us,_o=Ds,Lo=Ps,Yt=l.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(Ke,{ref:o,sideOffset:e,className:g("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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}));Yt.displayName=Ke.displayName;const Zt=l.forwardRef(({percentage:s,tokens:e,formattedPercentage:n,className:o,...i},a)=>{const c=Math.min(100,Math.max(0,s)),f=16,p=2,r=(f-p)/2,d=f/2,u=2*Math.PI*r,h=u-c/100*u;return t.jsx(zo,{children:t.jsxs(_o,{children:[t.jsx(Lo,{asChild:!0,children:t.jsx(J,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full cursor-default",o),...i,children:t.jsxs("svg",{width:f,height:f,viewBox:`0 0 ${f} ${f}`,className:"transform -rotate-90",children:[t.jsx("circle",{cx:d,cy:d,r,stroke:"currentColor",strokeWidth:p,fill:"transparent",className:"opacity-20"}),t.jsx("circle",{cx:d,cy:d,r,stroke:"currentColor",strokeWidth:p,fill:"transparent",strokeDasharray:u,strokeDashoffset:h,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),t.jsx(Yt,{side:"top",align:"center",children:t.jsxs("p",{children:["Context: ",n," (",e.toLocaleString()," tokens)"]})})]})})});Zt.displayName="ContextUsageButton";const Fo=l.forwardRef(({autoScroll:s=!0,isStreaming:e=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:i=!0,scrollButton:a,className:c,children:f,...p},r)=>{const d=l.useRef(null),[u,h]=l.useState(!0),[v,m]=l.useState(!1),x=l.useRef(0);l.useImperativeHandle(r,()=>{if(!d.current)throw new Error("Container ref not initialized");return d.current});const b=l.useCallback(()=>{const N=d.current;if(!N)return;const{scrollTop:j,scrollHeight:C,clientHeight:I}=N,S=C-j-I<o;h(S),m(!S&&i),x.current=j},[o,i]),y=l.useCallback((N=n)=>{const j=d.current;j&&j.scrollTo({top:j.scrollHeight,behavior:N})},[n]);return l.useEffect(()=>{!s||!d.current||(e&&u?y("auto"):!e&&u&&y())},[s,e,u,y]),l.useEffect(()=>{const N=d.current;if(!N)return;const j=()=>{b()};return N.addEventListener("scroll",j,{passive:!0}),b(),()=>{N.removeEventListener("scroll",j)}},[b]),l.useEffect(()=>{const N=d.current;if(!N)return;const j=new ResizeObserver(()=>{u&&s&&y("auto")});return j.observe(N),()=>{j.disconnect()}},[u,s,y]),t.jsxs("div",{className:"relative flex-1",children:[t.jsx("div",{ref:d,className:g("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",c),...p,children:t.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:f})}),v&&t.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:a||t.jsxs("button",{type:"button",onClick:()=>y(),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"]})})]})});Fo.displayName="Conversation";const Oo=zs,es=l.forwardRef(({className:s,...e},n)=>t.jsx(Xe,{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}));es.displayName=Xe.displayName;const Bo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Oo,{children:[t.jsx(es,{}),t.jsxs(Je,{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(_s,{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(tn,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Bo.displayName=Je.displayName;const Ho=l.forwardRef(({className:s,...e},n)=>t.jsx(Ye,{ref:n,className:g("text-subheading font-semibold leading-none tracking-tight",s),...e}));Ho.displayName=Ye.displayName;const $o=l.forwardRef(({className:s,...e},n)=>t.jsx(Ze,{ref:n,className:g("text-paragraph-sm text-muted-foreground",s),...e}));$o.displayName=Ze.displayName;const Wo=q("flex h-10 w-full rounded-md border bg-input-background px-3 py-2 text-paragraph-sm ring-offset-background file:border-0 file:bg-transparent file:text-paragraph-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"}}),Vo=l.forwardRef(({className:s,type:e,variant:n,...o},i)=>t.jsx("input",{type:e,className:g(Wo({variant:n,className:s})),ref:i,...o}));Vo.displayName="Input";const qo=l.forwardRef(({className:s,...e},n)=>t.jsx(et,{ref:n,className:g("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...e}));qo.displayName=et.displayName;const Qo=q("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"}}),ts=l.forwardRef(({message:s,role:e,layout:n,className:o,children:i,messageId:a,autoScroll:c,isLastMessage:f=!1,...p},r)=>{const d=s?s.role:e||"assistant",u=s?s.id:a,h=l.useRef(null),[v,m]=l.useState(void 0);return l.useImperativeHandle(r,()=>h.current),l.useEffect(()=>{if(!f||d!=="assistant"){m(void 0);return}const x=()=>{const y=h.current;if(!y)return;let N=y.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;if(!N)return;const j=y.previousElementSibling;if(!j||j.getAttribute("aria-label")!=="user message"){m(void 0);return}const C=N.clientHeight,I=j.offsetHeight,S=Math.max(0,C-I-32);m(S)};x();const b=new ResizeObserver(x);if(h.current){b.observe(h.current);let y=h.current.parentElement;for(;y&&!y.classList.contains("overflow-y-auto");)y=y.parentElement;y&&b.observe(y)}return()=>b.disconnect()},[f,d]),l.useEffect(()=>{if((c!==void 0?c:d==="user")&&h.current){const b=setTimeout(()=>{h.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(b)}},[d,c]),t.jsx("article",{ref:h,"aria-label":`${d} message`,"data-message-id":u,className:g(Qo({role:d,layout:n}),o),style:{minHeight:v!==void 0?`${v}px`:void 0},...p,children:i})});ts.displayName="Message";const Me=q("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"}}),Go=q("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),ss=l.forwardRef(({content:s,isStreaming:e=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:i=!1,autoCollapse:a=!0,autoCollapseDelay:c=2e3,label:f="Thinking",variant:p,className:r},d)=>{const[u,h]=l.useState(n==="inline"?!0:o),[v,m]=l.useState(!1);return l.useEffect(()=>{if(a&&!e&&s&&n==="collapsible"){const x=setTimeout(()=>{m(!0),h(!1)},c);return()=>clearTimeout(x)}},[e,s,a,c,n]),l.useEffect(()=>{i&&e&&n==="collapsible"&&!v&&h(!0)},[i,e,n,v]),!s&&!e?null:n==="inline"?t.jsxs("div",{ref:d,className:g(Me({variant:p}),"p-3",r),children:[t.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[t.jsx("span",{className:"text-caption 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-paragraph-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:d,className:g("mb-3",r),children:[t.jsxs("button",{type:"button",onClick:()=>{h(!u),m(!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":u,"aria-label":`${u?"Collapse":"Expand"} reasoning`,children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx("span",{className:"text-caption 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"}),!u&&s&&t.jsxs("span",{className:"text-caption text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),t.jsx(se,{className:Go({expanded:u}),"aria-hidden":"true"})]}),u&&t.jsx("div",{className:g(Me({variant:p}),"mt-2 p-3 animate-fadeIn"),children:t.jsxs("div",{className:"text-paragraph-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:"..."})]})})]})});ss.displayName="Reasoning";const le=l.forwardRef(({content:s,isStreaming:e=!1,showEmpty:n=!0,emptyMessage:o="",className:i,...a},c)=>{if(!s&&e&&n)return t.jsx("div",{ref:c,className:g("opacity-70 italic text-paragraph-sm",i),...a,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,...d})=>d.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",...d}):t.jsx("input",{...d}),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-code text-foreground shadow-sm",...r}):t.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code 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-heading-3 mt-6 mb-4 text-foreground border-b border-border pb-2",...r}),h2:({node:p,...r})=>t.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...r}),h3:({node:p,...r})=>t.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...r}),h4:({node:p,...r})=>t.jsx("h4",{className:"text-paragraph-sm font-semibold mt-3 mb-2 text-foreground",...r}),ul:({node:p,...r})=>{const d=p?.children?.some(u=>typeof u=="object"&&u!==null&&"type"in u&&u.type==="element"&&"tagName"in u&&u.tagName==="li"&&"children"in u&&Array.isArray(u.children)&&u.children.some(h=>typeof h=="object"&&h!==null&&"type"in h&&h.type==="element"&&"tagName"in h&&h.tagName==="input"&&"properties"in h&&typeof h.properties=="object"&&h.properties!==null&&"type"in h.properties&&h.properties.type==="checkbox"));return t.jsx("ul",{className:g("my-2 space-y-1 text-foreground",d?"list-none space-y-2":"list-disc list-outside pl-4"),...r})},ol:({node:p,...r})=>t.jsx("ol",{className:"list-decimal list-outside pl-4 my-2 space-y-1 text-foreground",...r}),li:({node:p,...r})=>{const d=p?.children?.some(u=>typeof u=="object"&&u!==null&&"type"in u&&u.type==="element"&&"tagName"in u&&u.tagName==="input"&&"properties"in u&&typeof u.properties=="object"&&u.properties!==null&&"type"in u.properties&&u.properties.type==="checkbox");return t.jsx("li",{className:g(d?"flex items-start gap-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:"mb-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.jsx("div",{ref:c,className:g("markdown-content prose prose-sm max-w-none dark:prose-invert",i),...a,children:t.jsx(ys,{remarkPlugins:[cn],components:f,children:s})})});le.displayName="Response";const Ue={Globe:an,Link:rn,Cloud:on,CheckSquare:ye,Search:nn,FileText:we,Edit:sn,Wrench:ft};function De({toolCall:s}){const[e,n]=l.useState(!1),o=s.icon&&Ue[s.icon]?Ue[s.icon]:ft,i=s.prettyName||s.title;return t.jsxs("div",{className:"flex flex-col my-4",children:[t.jsx("button",{type:"button",className:"flex items-center gap-2 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>n(!e),"aria-expanded":e,children:t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-zinc-500",children:[t.jsx("div",{className:"text-zinc-500",children:t.jsx(o,{className:"h-3 w-3"})}),t.jsx("span",{className:"text-paragraph-sm text-zinc-500",children:i}),t.jsx(se,{className:`h-3 w-3 text-zinc-400 transition-transform duration-200 ${e?"rotate-180":""}`})]})}),e&&t.jsxs("div",{className:"mt-2 text-sm border border-zinc-200 rounded-lg bg-zinc-50 overflow-hidden w-full",children:[s.locations&&s.locations.length>0&&t.jsxs("div",{className:"p-3 border-b border-zinc-200",children:[t.jsx("div",{className:"text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-1.5 font-sans",children:"Files"}),t.jsx("ul",{className:"space-y-1",children:s.locations.map(a=>t.jsxs("li",{className:"font-mono text-[11px] text-zinc-700 bg-zinc-200/50 px-1.5 py-0.5 rounded w-fit",children:[a.path,a.line!==null&&a.line!==void 0&&`:${a.line}`]},`${a.path}:${a.line??""}`))})]}),s.rawInput&&Object.keys(s.rawInput).length>0&&t.jsxs("div",{className:"p-3 border-b border-zinc-200",children:[t.jsx("div",{className:"text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-1.5 font-sans",children:"Input"}),t.jsx("div",{className:"text-[11px] font-mono text-zinc-700",children:t.jsx(Te,{value:s.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit"}})})]}),s.content&&s.content.length>0||s.error?t.jsxs("div",{className:"p-3 border-b border-zinc-200 last:border-0",children:[t.jsx("div",{className:"text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-1.5 font-sans",children:"Output"}),t.jsxs("div",{className:"space-y-2 text-[11px] text-zinc-700",children:[s.content?.map((a,c)=>{const f=()=>a.type==="diff"&&"path"in a?`diff-${a.path}-${c}`:a.type==="terminal"&&"terminalId"in a?`terminal-${a.terminalId}`:a.type==="text"&&"text"in a?`text-${a.text.substring(0,20)}-${c}`:a.type==="content"&&"content"in a?`content-${a.content.text?.substring(0,20)}-${c}`:`block-${c}`,p=(r,d)=>{try{const u=JSON.parse(r);if(typeof u=="object"&&u!==null)return t.jsx("div",{className:"text-[11px]",children:t.jsx(Te,{value:u,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit"}})},d)}catch{}return t.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-zinc-700 overflow-x-auto",children:r},d)};if(a.type==="content"&&"content"in a){const r=a.content;if(r.type==="text"&&r.text)return p(r.text,f())}return a.type==="text"&&"text"in a?p(a.text,f()):a.type==="diff"&&"path"in a&&"oldText"in a&&"newText"in a?t.jsxs("div",{className:"border border-zinc-200 rounded bg-white",children:[t.jsxs("div",{className:"bg-zinc-50 px-2 py-1 text-[10px] font-mono text-zinc-500 border-b border-zinc-200",children:[a.path,"line"in a&&a.line!==null&&a.line!==void 0&&`:${a.line}`]}),t.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[t.jsxs("div",{className:"text-red-600",children:["- ",a.oldText]}),t.jsxs("div",{className:"text-green-600",children:["+ ",a.newText]})]})]},f()):a.type==="terminal"&&"terminalId"in a?t.jsxs("div",{className:"bg-zinc-900 text-zinc-100 p-2 rounded text-[11px] font-mono",children:["Terminal: ",a.terminalId]},f()):null}),s.error&&t.jsxs("div",{className:"text-red-600 font-mono text-[11px] mt-2",children:["Error: ",s.error]})]})]}):null,(s.tokenUsage||s.startedAt)&&t.jsxs("div",{className:"p-2 bg-zinc-100/50 border-t border-zinc-200 flex flex-wrap gap-4 text-[10px] text-zinc-500 font-sans",children:[s.tokenUsage&&t.jsxs("div",{className:"flex gap-3",children:[s.tokenUsage.inputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Input:"}),s.tokenUsage.inputTokens.toLocaleString()]}),s.tokenUsage.outputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Output:"}),s.tokenUsage.outputTokens.toLocaleString()]}),s.tokenUsage.totalTokens!==void 0&&t.jsxs("div",{children:[t.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Total:"}),s.tokenUsage.totalTokens.toLocaleString()]})]}),s.startedAt&&t.jsxs("div",{className:"flex gap-3 ml-auto",children:[t.jsxs("span",{children:["Started: ",new Date(s.startedAt).toLocaleTimeString()]}),s.completedAt&&t.jsxs("span",{children:["Completed:"," ",new Date(s.completedAt).toLocaleTimeString()," (",Math.round((s.completedAt-s.startedAt)/1e3),"s)"]})]})]})]})]})}const re=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],Pe=["...","·..",".·.","..·",".·.","·.."];function Ko({startTime:s}){const[e,n]=l.useState(0),[o,i]=l.useState(()=>re[Math.floor(Math.random()*re.length)]),[a,c]=l.useState(0);l.useEffect(()=>{const r=setInterval(()=>{const u=Date.now()-s;n(u)},100);return()=>clearInterval(r)},[s]),l.useEffect(()=>{const r=setInterval(()=>{const d=Math.floor(Math.random()*re.length);i(re[d])},1500);return()=>clearInterval(r)},[]),l.useEffect(()=>{const r=setInterval(()=>{c(d=>(d+1)%Pe.length)},100);return()=>clearInterval(r)},[]);const f=(e/1e3).toFixed(1),p=Pe[a];return t.jsxs("span",{className:"text-muted-foreground text-paragraph-sm",children:[o,p," ",f,"s"]})}const Xo=q("w-full rounded-2xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-secondary text-foreground px-4 py-4 text-paragraph",assistant:"text-foreground text-paragraph-sm",system:"bg-card border border-border text-foreground opacity-80 text-caption px-4 py-3"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),ns=l.forwardRef(({role:s,variant:e,isStreaming:n,message:o,thinkingDisplayStyle:i="collapsible",className:a,children:c,...f},p)=>{const r=T(m=>m.streamingStartTime);T(m=>m.currentModel);const d=o&&!c,u=d?o.role:s||"assistant",h=d?o.isStreaming:n;let v=c;if(d){const m=o.metadata?.thinking,x=!!m,b=o.isStreaming&&!o.content&&o.role==="assistant";v=t.jsxs(t.Fragment,{children:[o.role==="assistant"&&x&&t.jsx(ss,{content:m,isStreaming:o.isStreaming,mode:i,autoCollapse:!0}),b&&r&&t.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[t.jsx(mt,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx(Ko,{startTime:r})]}),o.role==="assistant"?(()=>{const y=(o.toolCalls||[]).slice().sort((C,I)=>(C.contentPosition??1/0)-(I.contentPosition??1/0));if(y.length===0||!y.some(C=>C.contentPosition!==void 0))return t.jsxs(t.Fragment,{children:[y.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mb-1",children:y.map(C=>t.jsx(De,{toolCall:C},C.id))}),t.jsx(le,{content:o.content,isStreaming:o.isStreaming,showEmpty:!1})]});const N=[];let j=0;if(y.forEach(C=>{const I=C.contentPosition??o.content.length;if(I>j){const U=o.content.slice(j,I);U&&N.push(t.jsx(le,{content:U,isStreaming:!1,showEmpty:!1},`text-before-${C.id}`))}N.push(t.jsx("div",{children:t.jsx(De,{toolCall:C})},`tool-${C.id}`)),j=I}),j<o.content.length){const C=o.content.slice(j);C&&N.push(t.jsx(le,{content:C,isStreaming:o.isStreaming,showEmpty:!1},"text-end"))}return t.jsx(t.Fragment,{children:N})})():t.jsx("div",{className:"whitespace-pre-wrap",children:o.content})]})}return t.jsx("div",{ref:p,className:g(Xo({role:u,variant:e}),h&&"animate-pulse-subtle",a),...f,children:v})});ns.displayName="MessageContent";const Ce=l.forwardRef(({showIcons:s=!0,visibleTabs:e=["todo","files"],variant:n="default",className:o,...i},a)=>{const f=[{id:"todo",label:"To-do",icon:ye},{id:"files",label:"Files",icon:we},{id:"database",label:"Database",icon:dt},{id:"sources",label:"Sources",icon:ut}].filter(r=>e.includes(r.id)),p=n==="compact"?"gap-[4px]":"gap-3";return t.jsx(Y,{ref:a,className:g("w-full justify-start bg-transparent p-0 h-auto",p,o),...i,children:f.map(r=>{const d=r.icon;return t.jsxs(Z,{value:r.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[s&&d&&t.jsx(d,{className:"size-4"}),r.label]},r.id)})})});Ce.displayName="PanelTabsHeader";const Jo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(tt,{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-paragraph-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(Ls,{asChild:!0,children:t.jsx(ln,{className:"h-4 w-4 opacity-50"})})]}));Jo.displayName=tt.displayName;const os=l.forwardRef(({className:s,...e},n)=>t.jsx(st,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(pt,{className:"h-4 w-4"})}));os.displayName=st.displayName;const rs=l.forwardRef(({className:s,...e},n)=>t.jsx(nt,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(se,{className:"h-4 w-4"})}));rs.displayName=nt.displayName;const Yo=l.forwardRef(({className:s,children:e,position:n="popper",...o},i)=>t.jsx(Fs,{children:t.jsxs(ot,{ref:i,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(os,{}),t.jsx(Os,{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(rs,{})]})}));Yo.displayName=ot.displayName;const Zo=l.forwardRef(({className:s,...e},n)=>t.jsx(rt,{ref:n,className:g("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",s),...e}));Zo.displayName=rt.displayName;const er=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(at,{ref:o,className:g("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-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(Bs,{children:t.jsx(lt,{className:"h-4 w-4"})})}),t.jsx(Hs,{children:e})]}));er.displayName=at.displayName;const tr=l.forwardRef(({className:s,...e},n)=>t.jsx(it,{ref:n,className:g("-mx-1 my-1 h-px bg-muted",s),...e}));tr.displayName=it.displayName;const as=l.forwardRef(({task:s,collapsible:e=!0,defaultExpanded:n=!1,onTaskClick:o,className:i,...a},c)=>{const[f,p]=l.useState(n),r=!!(s.details||s.files&&s.files.length>0),d={pending:be,in_progress:mt,completed:ct}[s.status],u=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},h=()=>{r&&e&&p(!f),o?.(s)};return t.jsxs("div",{ref:c,className:g("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",i),...a,children:[t.jsxs("button",{type:"button",onClick:h,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(d,{className:g("w-4 h-4 shrink-0",u(),s.status==="in_progress"&&"animate-spin")}),t.jsx("span",{className:g("flex-1 text-paragraph-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(se,{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-paragraph-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-caption font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),t.jsx("div",{className:"space-y-1",children:s.files.map(v=>t.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:v},v))})]})]})]})});as.displayName="Task";const sr=l.forwardRef(({tasks:s,collapsible:e=!0,onTaskClick:n,emptyMessage:o="No tasks yet.",className:i,...a},c)=>t.jsx("div",{ref:c,className:g("space-y-2 max-h-96 overflow-y-auto",i),...a,children:s.length===0?t.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:o}):s.map(f=>t.jsx(as,{task:f,collapsible:e,...n?{onTaskClick:n}:{}},f.id))}));sr.displayName="TaskList";const nr=q("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-paragraph-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"}}),or=l.forwardRef(({className:s,autoResize:e=!1,maxHeight:n=200,variant:o,...i},a)=>{const c=l.useRef(null),f=l.useCallback(r=>{c.current=r,typeof a=="function"?a(r):a&&(a.current=r)},[a]),p=l.useCallback(()=>{const r=c.current;if(!r||!e)return;r.style.height="auto";const d=Math.min(r.scrollHeight,n);r.style.height=`${d}px`,r.scrollHeight>n?r.style.overflowY="auto":r.style.overflowY="hidden"},[e,n]);return l.useEffect(()=>{p()},[p]),t.jsx("textarea",{className:g(nr({variant:o}),e&&"overflow-y-hidden",s),ref:f,...i})});or.displayName="Textarea";function rr(){return"http://localhost:3100"}const ar={agentServerUrl:rr()};function ir(){const{client:s,error:e,sessionId:n}=yn({serverUrl:ar.agentServerUrl});return t.jsx(Po,{client:s,initialSessionId:n,error:e})}const is=document.getElementById("root");if(!is)throw new Error("Root element not found");ws.createRoot(is).render(t.jsx(vs.StrictMode,{children:t.jsx(ir,{})}));
|
|
3
|
+
`;try{await require("node:fs").promises.appendFile(this.logFilePath,o,"utf-8")}catch{}}this.isWriting=!1}}shouldLog(e){return Ee[e]>=Ee[this.minLevel]}log(e,n,o){if(!this.shouldLog(e))return;const i={id:`log_${++pn}`,timestamp:new Date().toISOString(),level:e,service:this.service,message:n,...o&&{metadata:o}};if(mn(i),re&&this.logFilePath,re&&this.logFilePath){const a={timestamp:i.timestamp,level:i.level,service:i.service,message:i.message,...i.metadata&&{metadata:i.metadata}};this.writeToFile(JSON.stringify(a)).catch(()=>{})}if(re&&this.enableConsoleOutput){const a=i.timestamp,c=i.level.toUpperCase().padEnd(5),f=`[${this.service}]`,u=i.metadata?` ${JSON.stringify(i.metadata)}`:"";console.log(`${a} ${c} ${f} ${i.message}${u}`)}}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 H(s,e="debug"){return new gn(s,e)}const k=H("http-transport");class hn{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;isReceivingMessages=!1;isInReplayMode=!1;constructor(e){this.options={...e,baseUrl:e.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const e={protocolVersion:ke,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",e);k.info("ACP connection initialized",{initResponse:n});const o={cwd:"/",mcpServers:[]},i=await this.sendRpcRequest("session/new",o);this.currentSessionId=i.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 loadSession(e){this.connected&&(k.warn("Transport already connected, disconnecting first",{sessionId:e}),await this.disconnect());try{this.abortController=new AbortController;const n={protocolVersion:ke,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};k.info("Loading session - initializing connection",{sessionId:e});const o=await this.sendRpcRequest("initialize",n);if(!o.agentCapabilities?.loadSession)throw k.error("Agent does not support loading sessions",{capabilities:o.agentCapabilities}),new Error("Agent does not support loading sessions");k.info("ACP connection initialized, loading session",{sessionId:e,capabilities:o.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=e,await this.connectSSE();const i={sessionId:e,cwd:"/",mcpServers:[]};k.info("Sending session/load request",{loadRequest:i});const a=await this.sendRpcRequest("session/load",i);k.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:a}),this.connected=!0,this.reconnectAttempts=0}catch(n){this.connected=!1;const o=n instanceof Error?n:new Error(String(n));throw k.error("Failed to load session",{sessionId:e,error:o.message,stack:o.stack}),this.notifyError(o),o}}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");this.isInReplayMode&&(k.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const n=e.content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
4
|
+
`),o={sessionId:this.currentSessionId,prompt:[{type:"text",text:n}]},i=await this.sendRpcRequest("session/prompt",o);k.debug("Prompt sent",{promptResponse:i}),this.streamComplete=!0;const a=this.chunkResolvers.shift();a?a({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(){this.isReceivingMessages=!0;try{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}}finally{this.isReceivingMessages=!1}}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 i={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:n};k.debug("Sending RPC request",{method:e,params:n,request:i});const a={"Content-Type":"application/json",...this.options.headers},c=this.options.timeout??600*1e3,f=new AbortController,u=setTimeout(()=>f.abort(),c);try{const r=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:a,body:JSON.stringify(i),signal:f.signal});if(clearTimeout(u),!r.ok){const p=await r.text();throw new Error(`HTTP ${r.status}: ${p}`)}const d=await r.json();if(d.error)throw new Error(`ACP error: ${d.error.message||JSON.stringify(d.error)}`);return d.result||d}catch(r){throw clearTimeout(u),r instanceof Error&&r.name==="AbortError"?new Error(`Request timeout after ${c}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 i=o.body.getReader(),a=new TextDecoder;let c="";(async()=>{try{for(;;){const{done:f,value:u}=await i.read();if(f){k.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}c+=a.decode(u,{stream:!0});const r=c.split(`
|
|
5
|
+
`);c=r.pop()||"";let d={event:"message",data:""};for(const p of r)p.startsWith("event:")?d.event=p.substring(6).trim():p.startsWith("data:")?d.data=p.substring(5).trim():p===""&&(d.event==="message"&&d.data&&this.handleSSEMessage(d.data),d={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=Ns.safeParse(n);if(!o.success){k.error("Invalid ACP message from SSE",{issues:o.error.issues});return}const i=o.data;k.debug("Parsed ACP message",{method:"method"in i?i.method:"(no method)"}),"method"in i&&i.method==="session/update"&&(k.debug("Received session/update notification"),"params"in i&&i.params&&(k.debug("Calling handleSessionNotification",{params:i.params}),this.handleSessionNotification(i.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,i=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 a=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,c=o._meta&&typeof o._meta=="object"&&"prettyName"in o._meta?String(o._meta.prettyName):void 0,f=o._meta&&typeof o._meta=="object"&&"icon"in o._meta?String(o._meta.icon):void 0,u={id:o.toolCallId??"",title:o.title??"",prettyName:c,icon:f,kind:o.kind||"other",status:o.status||"pending",locations:o.locations,rawInput:o.rawInput,tokenUsage:o.tokenUsage,content:o.content?.map(d=>{if(typeof d!="object"||d===null)return{type:"text",text:""};const p=d;if(p.type==="content"&&typeof p.content=="object"&&p.content!==null){const h=p.content;if(h.type==="text")return{type:"content",content:{type:"text",text:typeof h.text=="string"?h.text:""}}}return p.type==="text"?{type:"text",text:typeof p.text=="string"?p.text:""}:p.type==="diff"?{type:"diff",path:typeof p.path=="string"?p.path:"",oldText:typeof p.oldText=="string"?p.oldText:"",newText:typeof p.newText=="string"?p.newText:"",line:typeof p.line=="number"?p.line:null}:p.type==="terminal"?{type:"terminal",terminalId:typeof p.terminalId=="string"?p.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now()},r={type:"tool_call",sessionId:i,status:"active",toolCall:u,messageId:a};this.notifySessionUpdate(r)}else if(o?.sessionUpdate==="tool_call_update"){const a=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,c={id:o.toolCallId??"",status:o.status,locations:o.locations,rawOutput:o.rawOutput,tokenUsage:o.tokenUsage,content:o.content?.map(u=>{if(typeof u!="object"||u===null)return{type:"text",text:""};const r=u;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const d=r.content;if(d.type==="text")return{type:"content",content:{type:"text",text:typeof d.text=="string"?d.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:i,status:"active",toolCallUpdate:c,messageId:a};k.debug("Notifying tool_call_update session update",{sessionUpdate:f}),this.notifySessionUpdate(f)}else if(o&&"sessionUpdate"in o&&o.sessionUpdate==="tool_output"){const a=o,c=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,f={id:a.toolCallId??"",rawOutput:a.rawOutput,content:a.content?.map(r=>{if(typeof r!="object"||r===null)return{type:"text",text:""};const d=r;if(d.type==="content"&&typeof d.content=="object"&&d.content!==null){const p=d.content;if(p.type==="text")return{type:"content",content:{type:"text",text:typeof p.text=="string"?p.text:""}}}return d.type==="text"?{type:"text",text:typeof d.text=="string"?d.text:""}:d.type==="diff"?{type:"diff",path:typeof d.path=="string"?d.path:"",oldText:typeof d.oldText=="string"?d.oldText:"",newText:typeof d.newText=="string"?d.newText:"",line:typeof d.line=="number"?d.line:null}:d.type==="terminal"?{type:"terminal",terminalId:typeof d.terminalId=="string"?d.terminalId:""}:{type:"text",text:""}})},u={type:"tool_call_update",sessionId:i,status:"active",toolCallUpdate:f,messageId:c};k.debug("Notifying tool_output as tool_call_update",{sessionUpdate:u}),this.notifySessionUpdate(u)}else if(o?.sessionUpdate==="agent_message_chunk"){const a=o._meta&&typeof o._meta=="object"&&"isReplay"in o._meta&&o._meta.isReplay===!0;if(this.isInReplayMode&&!a)return;const c={type:"generic",sessionId:i,status:"active"},f=o._meta&&typeof o._meta=="object"&&"tokenUsage"in o._meta?o._meta.tokenUsage:void 0,u=o.content;if(u&&typeof u=="object"){const r=u;let d=null;if(r.type==="text"&&typeof r.text=="string"&&(d={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:r.text},tokenUsage:f,isComplete:!1}),d&&!a){const p=this.chunkResolvers.shift();p?p(d):this.messageQueue.push(d)}if(d&&typeof r.text=="string"&&(a||!this.isReceivingMessages)){const p={type:"generic",sessionId:i,status:"active",message:{id:`msg_${Date.now()}_assistant`,role:"assistant",content:[{type:"text",text:r.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(p)}}a||this.notifySessionUpdate(c)}else if(o?.sessionUpdate==="user_message_chunk"){k.debug("Received user_message_chunk",{update:o});const a=o.content;if(a&&typeof a=="object"){const c=a;if(c.type==="text"&&typeof c.text=="string"){const f={type:"generic",sessionId:i,status:"active",message:{id:`msg_${Date.now()}_user`,role:"user",content:[{type:"text",text:c.text}],timestamp:new Date().toISOString()}};k.debug("Notifying session update for user message"),this.notifySessionUpdate(f)}}}else{const a={type:"generic",sessionId:i,status:"active"};this.notifySessionUpdate(a)}}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 xn{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 bn{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 he=H("acp-client","debug");class yn{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=>{he.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="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(n){const c=new Date().toISOString(),f={id:n,status:"connected",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:c}};return this.sessions.set(n,f),this.currentSessionId=n,n}const o=this.generateSessionId(),i=new Date().toISOString(),a={id:o,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:i}};return this.sessions.set(o,a),this.currentSessionId=o,this.updateSessionStatus(o,"connected"),o}async loadSession(e,n){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const o=new Date().toISOString(),i={id:e,status:"connecting",config:n?{...n,agentPath:n.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};return this.sessions.set(e,i),this.currentSessionId=e,await this.transport.loadSession(e),this.updateSessionStatus(e,"connected"),e}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 i=this.sessions.get(o);if(!i)throw new Error(`Session ${o} not found`);const a={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};i.messages.push(a),this.updateSessionStatus(o,"active"),await this.transport.send(a)}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 xn(this.config.options);case"http":return new hn(this.config.options);case"websocket":return new bn(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){he.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){he.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 G=H("acp-client-hook");function wn(s){const[e,n]=l.useState(null),[o,i]=l.useState(null),[a,c]=l.useState(null);return l.useEffect(()=>{const u=new URLSearchParams(window.location.search).get("session");u&&(G.info("Session ID found in URL",{sessionId:u}),c(u));try{G.info("Initializing ACP client",{serverUrl:s.serverUrl});const r=new yn({type:"http",options:{baseUrl:s.serverUrl}});return n(r),G.info("ACP client initialized successfully"),()=>{G.debug("Disconnecting ACP client"),r.disconnect().catch(d=>{G.error("Failed to disconnect ACP client",{error:d instanceof Error?d.message:String(d)})})}}catch(r){const d=r instanceof Error?r.message:"Failed to initialize ACP client";i(d),G.error("Failed to initialize ACP client",{error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}},[s.serverUrl]),{client:e,error:o,sessionId:a}}const gt=$(["pending","in_progress","completed","failed"]),vn=$(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),ht=E({path:w(),line:A().nullable().optional()}),ve=E({inputTokens:A().optional(),outputTokens:A().optional(),totalTokens:A().optional()}),xt=ze("type",[E({type:z("content"),content:E({type:z("text"),text:w()})}),E({type:z("text"),text:w()}),E({type:z("diff"),path:w(),oldText:w(),newText:w(),line:A().nullable().optional()}),E({type:z("terminal"),terminalId:w()})]),bt=E({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),kind:vn,status:gt,contentPosition:A().optional(),locations:M(ht).optional(),rawInput:L(w(),F()).optional(),rawOutput:L(w(),F()).optional(),content:M(xt).optional(),error:w().optional(),startedAt:A().optional(),completedAt:A().optional(),tokenUsage:ve.optional()}),Nn=E({id:w(),status:gt.optional(),locations:M(ht).optional(),rawOutput:L(w(),F()).optional(),content:M(xt).optional(),error:w().optional(),completedAt:A().optional(),tokenUsage:ve.optional()});function Re(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 K=H("chat-store","debug"),T=Ss(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 i=o.messages.find(r=>r.id===e);let a=o.totalBilled,c=o.currentContext,f=n;if(n.tokenUsage){const r=i?.tokenUsage;K.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:r});const d={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)};K.debug("updateMessage: merged tokenUsage",{merged:d}),f={...n,tokenUsage:d};const p=d.inputTokens-(r?.inputTokens??0),h=d.outputTokens-(r?.outputTokens??0),v=d.totalTokens-(r?.totalTokens??0);a={inputTokens:o.totalBilled.inputTokens+p,outputTokens:o.totalBilled.outputTokens+h,totalTokens:o.totalBilled.totalTokens+v},c={inputTokens:d.inputTokens,outputTokens:o.currentContext.outputTokens+h,totalTokens:d.totalTokens}}const u=o.messages.map(r=>r.id===e?{...r,...f}:r);if(n.tokenUsage&&f.tokenUsage){const r=i?.tokenUsage,d=f.tokenUsage,p=(d.inputTokens??0)-(r?.inputTokens??0),h=(d.outputTokens??0)-(r?.outputTokens??0),v=(d.totalTokens??0)-(r?.totalTokens??0),m=u.filter(y=>y.tokenUsage).map(y=>({id:y.id,role:y.role,tokens:y.tokenUsage})),x=u.reduce((y,N)=>({inputTokens:y.inputTokens+(N.tokenUsage?.inputTokens??0),outputTokens:y.outputTokens+(N.tokenUsage?.outputTokens??0),totalTokens:y.totalTokens+(N.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),b=x.inputTokens===a.inputTokens&&x.outputTokens===a.outputTokens&&x.totalTokens===a.totalTokens;K.debug("updateMessage: tokenUsage update",{messageId:e,updates:n.tokenUsage,existing:r,messageMax:d,delta:{inputDelta:p,outputDelta:h,totalDelta:v},totalBilled:a,currentContext:c,actualSum:x,billedCorrect:b?"✅":"❌",messageCount:u.length,messagesWithTokens:m.length,breakdown:m})}return{messages:u,totalBilled:a,currentContext:c}}),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){K.debug("No assistant message found, creating one for tool call at position 0");const u={id:`msg_${Date.now()}_assistant`,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,toolCalls:[{...e,contentPosition:0}]};return{messages:[...n.messages,u]}}const i=[...n.messages],a=i[o];if(!a)return n;const c=a.content.length,f={...e,contentPosition:c};return i[o]={...a,toolCalls:[...a.toolCalls||[],f]},{messages:i}}),updateToolCallInCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(d=>d.role==="assistant");if(o===-1)return K.warn("No assistant message found to update tool call in"),n;const i=[...n.messages],a=i[o];if(!a)return n;const c=a.toolCalls||[],f=c.findIndex(d=>d.id===e.id);if(f===-1)return K.warn(`Tool call ${e.id} not found in message`),n;const u=c[f];if(!u)return n;const r=[...c];return r[f]=Re(u,e),i[o]={...a,toolCalls:r},{messages:i}}),updateToolCall:(e,n)=>s(o=>{const i=o.toolCalls[e]||[],a=i.findIndex(u=>u.id===n.id);if(a===-1)return o;const c=i[a];if(!c)return o;const f=[...i];return f[a]=Re(c,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,i)=>i!==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"],i=(n.indexOf(e.tokenDisplayMode)+1)%n.length,a=n[i];return a?{tokenDisplayMode:a}:e}),addLog:e=>s(n=>({logs:[...n.logs,e]})),clearLogs:()=>s({logs:[]}),setActiveTab:e=>s({activeTab:e})})),J=H("use-chat-messages","debug");function yt(s,e){const n=T(p=>p.messages),o=T(p=>p.isStreaming),i=T(p=>p.sessionId),a=T(p=>p.setIsStreaming),c=T(p=>p.setStreamingStartTime),f=T(p=>p.addMessage),u=T(p=>p.updateMessage),r=T(p=>p.setError),d=l.useCallback(async p=>{if(!s){J.error("No client available"),r("No client available");return}let h=i;if(!h){J.info("Creating new session before sending first message");const m=await e();if(!m){J.error("Failed to create session"),r("Failed to create session");return}h=m,J.info("Session created successfully",{sessionId:m})}const v=`msg_${Date.now()}_assistant`;try{const m=Date.now();a(!0),c(m);const x={id:`msg_${Date.now()}_user`,role:"user",content:p,timestamp:new Date().toISOString(),isStreaming:!1};f(x);const b={id:v,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:m};f(b);const y=s.receiveMessages();s.sendMessage(p,h).catch(C=>{const I=C instanceof Error?C.message:String(C);r(I),a(!1),c(null)});let N="",j=!1;for await(const C of y)if(C.tokenUsage&&J.debug("chunk.tokenUsage",{tokenUsage:C.tokenUsage}),C.isComplete){u(v,{content:N,isStreaming:!1,streamingStartTime:void 0,...C.tokenUsage?{tokenUsage:C.tokenUsage}:{}}),a(!1),c(null),j=!0;break}else C.contentDelta.type==="text"&&(N+=C.contentDelta.text,u(v,{content:N,...C.tokenUsage?{tokenUsage:C.tokenUsage}:{}}),await new Promise(I=>setTimeout(I,16)));j||(J.warn("Stream ended without isComplete flag"),u(v,{isStreaming:!1,streamingStartTime:void 0}),a(!1),c(null))}catch(m){const x=m instanceof Error?m.message:String(m);r(x),a(!1),c(null),u(v,{isStreaming:!1,streamingStartTime:void 0})}},[s,i,e,f,u,a,c,r]);return{messages:n,isStreaming:o,sendMessage:d}}const Sn=H("use-chat-input","debug");function jn(s,e){const n=T(h=>h.input),o=T(h=>h.setInputValue),i=T(h=>h.setInputSubmitting),a=T(h=>h.addFileAttachment),c=T(h=>h.removeFileAttachment),{sendMessage:f}=yt(s,e),u=l.useCallback(h=>{o(h)},[o]),r=l.useCallback(async()=>{if(!n.value.trim()||n.isSubmitting)return;const h=n.value;o(""),i(!0);try{await f(h)}catch(v){Sn.error("Failed to send message",{error:v instanceof Error?v.message:String(v)})}finally{i(!1)}},[n,o,i,f]),d=l.useCallback(h=>{a(h)},[a]),p=l.useCallback(h=>{c(h)},[c]);return{value:n.value,isSubmitting:n.isSubmitting,attachedFiles:n.attachedFiles,onChange:u,onSubmit:r,onAttachFile:d,onRemoveFile:p}}const W=H("use-chat-session","debug");function Cn(s,e){const n=T(m=>m.connectionStatus),o=T(m=>m.sessionId),i=T(m=>m.setConnectionStatus),a=T(m=>m.setSessionId),c=T(m=>m.setError),f=T(m=>m.clearMessages),u=T(m=>m.resetTokens),r=T(m=>m.addMessage);l.useEffect(()=>s?s.onSessionUpdate(x=>{if(x.message&&(W.debug("Session update with message",{message:x.message}),x.message.role!=="tool")){const b=x.message.content.map(j=>j.type==="text"?j.text:"").join(""),y=T.getState().messages,N=y[y.length-1];if(x.message.role==="assistant"&&N?.role==="assistant"&&N.content===""&&b)W.debug("Appending text to existing assistant message"),T.getState().updateMessage(N.id,{content:N.content+b});else{const j={id:x.message.id,role:x.message.role,content:b,timestamp:x.message.timestamp,isStreaming:!1};r(j)}}}):void 0,[s,r]);const d=l.useCallback(async()=>{if(!s){c("No client available");return}try{i("connecting"),c(null),await s.connect(),i("connected")}catch(m){W.error("Failed to connect",{error:m instanceof Error?m.message:String(m)});const x=m instanceof Error?m.message:String(m);c(x),i("error")}},[s,i,c]),p=l.useCallback(async m=>{if(!s){c("No client available");return}try{i("connecting"),c(null);const x=await s.loadSession(m);a(x),i("connected"),u(),W.info("Session loaded successfully",{sessionId:x})}catch(x){W.warn("Failed to load session, creating new one instead",{sessionId:m,error:x instanceof Error?x.message:String(x)});try{await d();const b=await s.startSession();if(a(b),f(),u(),typeof window<"u"){const y=new URL(window.location.href);y.searchParams.set("session",b),window.history.replaceState({},"",y.toString())}W.info("Created new session after failed load",{sessionId:b})}catch(b){const y=b instanceof Error?b.message:String(b);c(`Failed to load or create session: ${y}`),i("error")}}},[s,i,a,c,f,u,d]),h=l.useCallback(async()=>{if(!s)return c("No client available"),null;try{const m=await s.startSession();if(a(m),f(),u(),typeof window<"u"){const x=new URL(window.location.href);x.searchParams.set("session",m),window.history.pushState({},"",x.toString())}return m}catch(m){const x=m instanceof Error?m.message:String(m);return c(x),null}},[s,a,c,f,u]),v=l.useCallback(async()=>{if(s)try{await s.disconnect(),i("disconnected"),a(null)}catch(m){const x=m instanceof Error?m.message:String(m);c(x)}},[s,i,a,c]);return l.useEffect(()=>{!s||n!=="disconnected"||(e?(W.info("Loading initial session from URL",{sessionId:e}),p(e)):d())},[s,n,e,d,p]),{connectionStatus:n,sessionId:o,connect:d,loadSession:p,startSession:h,disconnect:v}}function kn(s){const e=T(c=>c.toolCalls),n=T(c=>c.addToolCall),o=T(c=>c.updateToolCall),i=T(c=>c.addToolCallToCurrentMessage),a=T(c=>c.updateToolCallInCurrentMessage);return l.useEffect(()=>{if(!s)return;const c=s.onSessionUpdate(f=>{f.type==="tool_call"?(n(f.sessionId,f.toolCall),i(f.toolCall)):f.type==="tool_call_update"&&(o(f.sessionId,f.toolCallUpdate),a(f.toolCallUpdate))});return()=>{c()}},[s,n,o,i,a]),{toolCalls:e,getToolCallsForSession:c=>{const f=e[c];return f&&f.length>0?f:Object.values(e).flat()}}}const Tn=E({id:w(),role:$(["user","assistant","system"]),content:w(),timestamp:de(),isStreaming:ee().default(!1),streamingStartTime:A().optional(),metadata:L(w(),F()).optional(),toolCalls:M(bt).optional(),tokenUsage:ve.optional()}),In=E({value:w(),isSubmitting:ee(),attachedFiles:M(E({name:w(),path:w(),size:A(),mimeType:w()}))});E({sessionId:w().nullable(),isConnected:ee(),isStreaming:ee(),messages:M(Tn),input:In,error:w().nullable()});$(["disconnected","connecting","connected","error"]);const En=E({name:w(),description:w().optional(),parameters:L(w(),F()).optional()}),Rn=E({name:w(),description:w(),parameters:L(w(),F()),required:M(w()).optional()}),An=E({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:M(En).optional(),tools:M(Rn).optional(),supportedFormats:M(w()).optional()}),Mn=$(["initializing","ready","busy","error","terminated"]);E({status:Mn,info:An.optional(),pid:A().optional(),error:w().optional(),uptime:A().optional()});const wt=$(["user","assistant","system","tool"]),Un=$(["text","image","file","tool_call","tool_result"]),ne=E({type:Un}),Dn=ne.extend({type:z("text"),text:w()}),Pn=ne.extend({type:z("image"),url:w().url().optional(),data:w().optional(),mimeType:w().optional()}),zn=ne.extend({type:z("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:A().optional()}),_n=ne.extend({type:z("tool_call"),id:w(),name:w(),arguments:L(w(),F())}),Ln=ne.extend({type:z("tool_result"),callId:w(),result:F(),error:w().optional()}),vt=ze("type",[Dn,Pn,zn,_n,Ln]),Nt=E({id:w(),role:wt,content:M(vt),timestamp:de(),metadata:L(w(),F()).optional()});E({id:w(),role:wt,contentDelta:vt,isComplete:ee(),tokenUsage:E({inputTokens:A().optional(),outputTokens:A().optional(),totalTokens:A().optional()}).optional()});const St=$(["idle","connecting","connected","active","streaming","error","disconnected"]),Fn=E({agentPath:w(),agentArgs:M(w()).optional(),environment:L(w(),w()).optional(),workingDirectory:w().optional(),timeout:A().optional()}),On=E({agentName:w().optional(),agentVersion:w().optional(),capabilities:M(w()).optional(),startedAt:de(),lastActivityAt:de().optional()});E({id:w(),status:St,config:Fn,metadata:On.optional(),messages:M(Nt),error:w().optional()});const ue=E({sessionId:w(),status:St.optional(),message:Nt.optional(),error:w().optional()}),Bn=ue.extend({type:z("tool_call"),toolCall:bt,messageId:w().optional()}),$n=ue.extend({type:z("tool_call_update"),toolCallUpdate:Nn,messageId:w().optional()}),Hn=ue.extend({type:z("tool_output"),toolOutput:E({id:w(),content:M(js()).optional(),rawOutput:L(w(),F()).optional()}),messageId:w().optional()}),Wn=ue.extend({type:z("generic").optional()});Cs([Bn,$n,Hn,Wn]);const Vn=[{id:"folder-1",name:"Item 1",type:"folder",children:[{id:"file-1-1",name:"Item 2",type:"file",extension:"tsx"},{id:"file-1-2",name:"Item 3",type:"file",extension:"ts"},{id:"file-1-3",name:"Item 4",type:"file",extension:"json"},{id:"file-1-4",name:"Item 5",type:"file",extension:"md"}]},{id:"folder-2",name:"Description 1",type:"folder",children:[{id:"file-2-1",name:"Description 2",type:"file",extension:"tsx"},{id:"file-2-2",name:"Description 3",type:"file",extension:"ts"},{id:"file-2-3",name:"Description 4",type:"file",extension:"json"},{id:"file-2-4",name:"Description 5",type:"file",extension:"md"}]},{id:"folder-3",name:"financial-docs",type:"folder",children:[]}];class qn{data;constructor(e=Vn){this.data=e}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(e){const n=i=>{for(const a of i){if(a.id===e)return a;if(a.children){const c=n(a.children);if(c)return c}}},o=n(this.data);return Promise.resolve(o?.children||[])}async getItemDetails(e){const n=i=>{for(const a of i){if(a.id===e)return a;if(a.children){const c=n(a.children);if(c)return c}}},o=n(this.data);if(!o)throw new Error(`Item with id ${e} not found`);return Promise.resolve(o)}}const Qn=[{id:"1",title:"Boeing Scores Early Wins at Dubai Airshow",url:"https://www.reuters.com/business/aerospace-defense/boeing-scores-early-wins-dubai-airshow-2024-11-17",snippet:"DUBAI, Nov 17 (Reuters) - Boeing (BA.N), opens new tab took centre stage at day one of the Dubai Airshow on Monday, booking a $38 billion order from host carrier Emirates and clinching more deals with African carriers, while China displayed its C919 in the Middle East for the first time.",sourceName:"Reuters",favicon:"https://www.reuters.com/favicon.ico"},{id:"2",title:"Boeing's Sustainable Aviation Goals Take Flight",url:"https://www.forbes.com/boeing-sustainability",snippet:"SEATTLE, Nov 18 (Reuters) - Boeing is making headway towards its sustainability targets, unveiling plans for a new eco-friendly aircraft design aimed at reducing emissions by 50% by 2030.",sourceName:"Forbes"},{id:"3",title:"Boeing Faces Increased Competition in Global Aviation Market",url:"https://www.reuters.com/business/aerospace-defense/boeing-competition-2024-11-19",snippet:"CHICAGO, Nov 19 (Reuters) - As the global aviation industry rebounds post-pandemic, Boeing is grappling with intensified competition from rival manufacturers, particularly in the Asian market.",sourceName:"Reuters",favicon:"https://www.reuters.com/favicon.ico"},{id:"4",title:"Boeing's Starliner Successfully Completes Orbital Test Flight",url:"https://www.theverge.com/boeing-starliner",snippet:"NASA, Nov 20 (Reuters) - Boeing's CST-100 Starliner spacecraft achieves a significant milestone, successfully completing its orbital test flight, paving the way for future crewed missions to the International Space Station.",sourceName:"The Verge"}],Gn=[{id:"todo-1",text:"Review filesystem implementation",status:"completed"},{id:"todo-2",text:"Add overflow menu actions",status:"in_progress"},{id:"todo-3",text:"Connect to real filesystem API",status:"pending"},{id:"todo-4",text:"Implement drag and drop support",status:"pending"},{id:"todo-5",text:"Add file preview functionality",status:"pending"}];function g(...s){return ks(Ts(s))}const Kn=q("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-paragraph-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-hover",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive-hover",outline:"border border-input bg-background hover:bg-accent-hover hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover",ghost:"hover:bg-accent-hover 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"}}),X=l.forwardRef(({className:s,variant:e,size:n,asChild:o=!1,...i},a)=>{const c=o?te:"button";return t.jsx(c,{className:g(Kn({variant:e,size:n,className:s})),ref:a,...i})});X.displayName="Button";const Jn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));Jn.displayName="Card";const Xn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex flex-col space-y-1.5 p-6",s),...e}));Xn.displayName="CardHeader";const Yn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-2xl font-semibold leading-none tracking-tight",s),...e}));Yn.displayName="CardTitle";const Zn=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-sm text-muted-foreground",s),...e}));Zn.displayName="CardDescription";const eo=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("p-6 pt-0",s),...e}));eo.displayName="CardContent";const to=l.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex items-center p-6 pt-0",s),...e}));to.displayName="CardFooter";const jt=l.forwardRef(({title:s,description:e,guideUrl:n,guideText:o="Guide",suggestedPrompts:i=[],onPromptClick:a,onGuideClick:c,onOpenFiles:f,onPromptHover:u,onPromptLeave:r,className:d,...p},h)=>{const v=b=>{a?.(b)},m=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),c?.()},x=[];for(let b=0;b<i.length;b+=2)x.push(i.slice(b,b+2));return t.jsxs("div",{ref:h,className:g("flex flex-col items-start",d),...p,children:[t.jsx("h3",{className:"text-heading-4 text-text-primary mb-6",children:s}),t.jsx("p",{className:"text-subheading text-text-secondary max-w-prose mb-6",children:e}),f&&t.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors mb-6",children:[t.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:"View Files"}),t.jsx(xe,{className:"size-4 text-foreground shrink-0"})]}),(n||c)&&t.jsxs("button",{type:"button",onClick:m,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:o}),t.jsx(xe,{className:"size-4 text-foreground shrink-0"})]}),i.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:x.map(b=>t.jsx("div",{className:"flex gap-2.5 items-center",children:b.map(y=>t.jsx("button",{type:"button",onClick:()=>v(y),onMouseEnter:()=>u?.(y),onMouseLeave:()=>r?.(),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-paragraph font-normal leading-normal text-text-tertiary truncate",children:y})},y))},b.join("-")))})]})]})});jt.displayName="ChatEmptyState";const Ct=l.createContext(void 0),Ne=()=>{const s=l.useContext(Ct);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},kt=l.forwardRef(({defaultExpanded:s=!1,expanded:e,onExpandedChange:n,className:o,children:i,...a},c)=>{const[f,u]=l.useState(s),r=e??f,d=l.useCallback(m=>{u(m),n?.(m)},[n]),p=l.Children.toArray(i),h=p.find(m=>l.isValidElement(m)&&typeof m.type=="function"&&m.type.displayName==="ChatHeader.ExpandablePanel"),v=p.filter(m=>m!==h);return t.jsxs(Ct.Provider,{value:{isExpanded:r,setIsExpanded:d},children:[t.jsx("div",{ref:c,className:g("flex items-center justify-between px-6 py-4",o),...a,children:v}),h]})});kt.displayName="ChatHeader.Root";const so=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("h1",{ref:o,className:g("m-0 text-subheading font-semibold",s),...n,children:e}));so.displayName="ChatHeader.Title";const no=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center gap-3",s),...n,children:e}));no.displayName="ChatHeader.Actions";const oo=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"}},ro=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},ao=l.forwardRef(({status:s,statusText:e,className:n,...o},i)=>{const a=e??ro(s),c=oo(s);return t.jsxs("div",{ref:i,className:g("flex items-center gap-2",n),...o,children:[t.jsx("div",{className:g("h-2 w-2 rounded-full",c)}),t.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:a})]})});ao.displayName="ChatHeader.StatusIndicator";const io=l.forwardRef(({icon:s,className:e,children:n,onClick:o,...i},a)=>{const{isExpanded:c,setIsExpanded:f}=Ne(),u=r=>{f(!c),o?.(r)};return t.jsxs("button",{ref:a,type:"button",onClick:u,className:g("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":c?"Collapse header":"Expand header",...i,children:[s&&t.jsx("div",{className:g("transition-transform duration-200",c&&"rotate-180"),children:s}),n]})});io.displayName="ChatHeader.Toggle";const Tt=l.forwardRef(({className:s,children:e,...n},o)=>{const{isExpanded:i}=Ne();return i?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});Tt.displayName="ChatHeader.ExpandablePanel";const It=l.forwardRef(({commands:s=[],showCommandMenu:e,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:i,setMenuItemCount:a,triggerCounter:c,onChange:f,className:u,...r},d)=>{const p=l.useCallback((v,m)=>{const x=v.toLowerCase(),b=m.toLowerCase();if(!m)return 1;if(x.includes(b))return 1-b.length/x.length;let y=0;for(let N=0;N<x.length&&y<b.length;N++)x[N]===b[y]&&y++;return y===b.length?.5-y/x.length:0},[]),h=l.useMemo(()=>s.map(v=>({...v,score:Math.max(p(v.label,n),v.description?p(v.description,n):0)})).filter(v=>v.score>0).sort((v,m)=>m.score-v.score),[s,n,p]);return l.useEffect(()=>{a(h.length)},[h.length,a]),l.useEffect(()=>{i(0)},[i]),l.useEffect(()=>{c>0&&h[o]&&(h[o].onSelect(),f(""))},[c,h,o,f]),!e||h.length===0?null:t.jsxs("div",{ref:d,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",u),...r,children:[t.jsx("div",{className:"text-caption font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),t.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map((v,m)=>t.jsxs("button",{type:"button",onClick:()=>v.onSelect(),className:g("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",m===o&&"bg-muted"),children:[v.icon&&t.jsx("span",{className:"shrink-0 mt-0.5",children:v.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-medium",children:v.label}),v.description&&t.jsx("div",{className:"text-caption text-muted-foreground truncate",children:v.description})]})]},v.id))})]})});It.displayName="ChatInputCommandMenu";const Et=l.createContext(void 0),pe=()=>{const s=l.useContext(Et);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},Rt=l.forwardRef(({client:s,startSession:e,value:n,onChange:o,onSubmit:i,disabled:a=!1,isSubmitting:c,submitOnEnter:f=!0,className:u,children:r,...d},p)=>{const h=l.useRef(null),v=l.useCallback(async()=>Promise.resolve(null),[]),m=jn(s??null,e??v),x=T(D=>D.isStreaming),b=s&&e,y=b?m.value:n||"",N=b?m.onChange:o||(()=>{}),j=b?m.onSubmit:i||(async()=>{}),C=b?m.isSubmitting||x:c||!1,[I,U]=l.useState(!1),[S,R]=l.useState(""),[P,Q]=l.useState(0),[B,ls]=l.useState(0),[cs,ds]=l.useState(0),us=l.useCallback(()=>{ds(D=>D+1)},[]),ps=async D=>{D.preventDefault(),y.trim()&&!C&&!a&&(await j(),setTimeout(()=>{h.current?.focus()},0))},fs=D=>{const O=D.target;!(O.tagName==="BUTTON"||O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.closest("button"))&&h.current&&h.current.focus()},ms=D=>{const O=D.target;!(O.tagName==="BUTTON"||O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.closest("button"))&&D.key===" "&&(D.preventDefault(),h.current&&h.current.focus())};return l.useEffect(()=>{const D=document.querySelector('textarea[name="chat-input"]');D&&h.current!==D&&(h.current=D)},[]),l.useEffect(()=>{!y&&h.current&&(h.current.style.height="auto",h.current.style.overflowY="hidden")},[y]),t.jsx(Et.Provider,{value:{value:y,onChange:N,onSubmit:j,disabled:a,isSubmitting:C,submitOnEnter:f,showCommandMenu:I,setShowCommandMenu:U,commandMenuQuery:S,setCommandMenuQuery:R,selectedMenuIndex:P,setSelectedMenuIndex:Q,menuItemCount:B,setMenuItemCount:ls,triggerMenuSelect:us,triggerCounter:cs},children:t.jsx("form",{ref:p,onSubmit:ps,onClick:fs,onKeyDown:ms,className:g("relative w-full divide-y rounded-xl border bg-background shadow-md",u),...d,children:r})})});Rt.displayName="ChatInput.Root";const At=l.forwardRef(({asChild:s=!1,className:e,onKeyDown:n,children:o,...i},a)=>{const{value:c,onChange:f,onSubmit:u,disabled:r,isSubmitting:d,submitOnEnter:p,showCommandMenu:h,setShowCommandMenu:v,setCommandMenuQuery:m,setSelectedMenuIndex:x,menuItemCount:b,triggerMenuSelect:y}=pe(),N=l.useRef(null),U={ref:l.useCallback(S=>{N.current=S,typeof a=="function"?a(S):a&&(a.current=S)},[a]),name:"chat-input",value:c,onChange:S=>{const R=S.target.value;if(f(R),R.startsWith("/")&&!R.includes(`
|
|
6
|
+
`)){v(!0);const B=R.slice(1);m(B)}else v(!1),m("");const P=N.current;if(!P)return;P.style.height="auto";const Q=Math.min(P.scrollHeight,164);P.style.height=`${Q}px`,P.scrollHeight>164?P.style.overflowY="auto":P.style.overflowY="hidden"},onKeyDown:S=>{if(h&&b>0){if(S.key==="ArrowDown"){S.preventDefault(),x(R=>(R+1)%b);return}else if(S.key==="ArrowUp"){S.preventDefault(),x(R=>(R-1+b)%b);return}else if(S.key==="Enter"&&!S.shiftKey){S.preventDefault(),y();return}else if(S.key==="Escape"){S.preventDefault(),v(!1),m("");return}}p&&S.key==="Enter"&&!S.shiftKey&&(c.trim()&&!d&&!r?(S.preventDefault(),u()):(d||r)&&S.preventDefault()),n?.(S)},disabled:r,...i};return s&&l.isValidElement(o)?l.cloneElement(o,U):t.jsx("textarea",{...U,rows:1,className:g("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 max-h-[6lh] min-h-[44px]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-paragraph-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});At.displayName="ChatInput.Field";const Mt=l.forwardRef(({asChild:s=!1,className:e,disabled:n,children:o,...i},a)=>{const{value:c,disabled:f,isSubmitting:u}=pe(),r=n||f||u||!c.trim(),d=s?te:X;return t.jsx(d,{ref:a,type:"submit",disabled:r,variant:s?void 0:"default",size:"icon",className:g(!s&&"gap-1.5 rounded-full",e),...i,children:o})});Mt.displayName="ChatInput.Submit";const Ut=l.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}));Ut.displayName="ChatInput.Toolbar";const Dt=l.forwardRef(({asChild:s=!1,className:e,children:n,onClick:o,...i},a)=>{const{value:c,onChange:f,setShowCommandMenu:u,setCommandMenuQuery:r}=pe(),d=h=>{c.startsWith("/")||(f("/"),u(!0),r("")),o?.(h)},p=s?te:X;return t.jsx(p,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),onClick:d,...i,children:n||t.jsx(Hs,{className:"size-4"})})});Dt.displayName="ChatInput.Actions";const Pt=l.forwardRef(({asChild:s=!1,className:e,children:n,...o},i)=>{const a=s?te:X;return t.jsx(a,{ref:i,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(Ws,{className:"size-4"})})});Pt.displayName="ChatInput.Attachment";const zt=l.forwardRef(({asChild:s=!1,className:e,children:n,...o},i)=>{const a=s?te:X;return t.jsx(a,{ref:i,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(Vs,{className:"size-4"})})});zt.displayName="ChatInput.VoiceInput";const _t=l.forwardRef(({commands:s=[],className:e,onChange:n,...o},i)=>{const{showCommandMenu:a,commandMenuQuery:c,selectedMenuIndex:f,setSelectedMenuIndex:u,setMenuItemCount:r,triggerCounter:d,onChange:p}=pe();return t.jsx(It,{ref:i,commands:s,showCommandMenu:a,commandMenuQuery:c,selectedMenuIndex:f,setSelectedMenuIndex:u,setMenuItemCount:r,triggerCounter:d,onChange:p,className:e,...o})});_t.displayName="ChatInput.CommandMenu";const lo=({className:s,...e})=>t.jsx(hs,{className:g("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...e}),Lt=({className:s,...e})=>t.jsx(xs,{className:g(s),...e}),co=({withHandle:s,className:e,...n})=>t.jsx(bs,{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"})]})})}),uo=({...s})=>t.jsx(Is,{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}),Ft=l.createContext(void 0),oe=()=>{const s=l.useContext(Ft);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},Ot=l.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:e="hidden",defaultActiveTab:n="todo",className:o,children:i,...a},c)=>{const[f,u]=l.useState(s),[r,d]=l.useState(e),[p,h]=l.useState(n);return t.jsx(Ft.Provider,{value:{sidebarOpen:f,setSidebarOpen:u,panelSize:r,setPanelSize:d,activeTab:p,setActiveTab:h},children:t.jsx("div",{ref:c,className:g("flex h-screen flex-row bg-background text-foreground",o),...a,children:t.jsx(lo,{direction:"horizontal",className:"flex-1",children:i})})})});Ot.displayName="ChatLayout.Root";const po=l.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}));po.displayName="ChatLayout.Header";const Bt=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx(Lt,{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})}));Bt.displayName="ChatLayout.Main";const $t=l.forwardRef(({showToaster:s=!0,className:e,children:n,...o},i)=>t.jsxs("div",{ref:i,className:g("relative flex flex-1 flex-col overflow-hidden",e),...o,children:[n,s&&t.jsx(uo,{})]}));$t.displayName="ChatLayout.Body";const Ht=l.forwardRef(({className:s,children:e,onScrollChange:n,showScrollToBottom:o=!0,...i},a)=>{const[c,f]=l.useState(!1),u=l.useRef(null),r=l.useRef(!0),d=l.useRef(!1);l.useImperativeHandle(a,()=>u.current);const p=l.useCallback(()=>{const b=u.current;if(!b)return!1;const{scrollTop:y,scrollHeight:N,clientHeight:j}=b,I=N-y-j<100;return f(!I&&o),n?.(I),I},[n,o]),h=l.useCallback(()=>{if(d.current)return;const b=p();r.current=b},[p]),v=l.useCallback((b=!0)=>{const y=u.current;y&&(d.current=!0,r.current=!0,y.scrollTo({top:y.scrollHeight,behavior:b?"smooth":"auto"}),setTimeout(()=>{d.current=!1},b?300:0))},[]);l.useEffect(()=>{u.current&&(r.current&&!d.current&&requestAnimationFrame(()=>{v(!1)}),d.current||p())},[e,v,p]),l.useEffect(()=>{if(!d.current){const b=p();r.current=b}},[p]);const m=l.useCallback(()=>{d.current=!1;const b=u.current;if(!b)return;const{scrollTop:y,scrollHeight:N,clientHeight:j}=b;N-y-j>=100&&(r.current=!1)},[]),x=l.useCallback(b=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"].includes(b.key)&&(d.current=!1,requestAnimationFrame(()=>{const N=u.current;if(!N)return;const{scrollTop:j,scrollHeight:C,clientHeight:I}=N,U=C-j-I;r.current=U<100}))},[]);return t.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[t.jsx("div",{ref:u,className:g("h-full overflow-y-auto flex flex-col",s),onScroll:h,onWheel:m,onTouchStart:m,onKeyDown:x,tabIndex:0,...i,children:t.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:e})}),c&&t.jsx("button",{type:"button",onClick:()=>v(!0),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(qs,{className:"size-4"})})]})});Ht.displayName="ChatLayout.Messages";const Wt=l.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})}));Wt.displayName="ChatLayout.Footer";const fo=l.forwardRef(({className:s,children:e,...n},o)=>{const{sidebarOpen:i}=oe();return i?t.jsx("div",{ref:o,className:g("border-r border-border bg-card w-64 overflow-y-auto",s),...n,children:e}):null});fo.displayName="ChatLayout.Sidebar";const Vt=l.forwardRef(({breakpoint:s="lg",className:e,children:n,...o},i)=>{const{panelSize:a}=oe(),[c,f]=l.useState(25);return l.useEffect(()=>{const u=()=>{const d=400/window.innerWidth*100;f(Math.max(d,25))};return u(),window.addEventListener("resize",u),()=>{window.removeEventListener("resize",u)}},[]),a==="hidden"?null:t.jsxs(t.Fragment,{children:[t.jsx(co,{withHandle:!0,className:"group-hover:opacity-100 opacity-0 transition-opacity"}),t.jsx(Lt,{defaultSize:25,minSize:c,maxSize:35,className:"group",children:t.jsx("div",{ref:i,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})})]})});Vt.displayName="ChatLayout.Aside";const mo=Rs,go=As,ho=l.forwardRef(({className:s,inset:e,children:n,...o},i)=>t.jsxs(_e,{ref:i,className:g("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",s),...o,children:[n,t.jsx(xe,{className:"ml-auto h-4 w-4"})]}));ho.displayName=_e.displayName;const xo=l.forwardRef(({className:s,...e},n)=>t.jsx(Le,{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}));xo.displayName=Le.displayName;const qt=l.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(Es,{children:t.jsx(Fe,{ref:o,sideOffset:e,className:g("z-50 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-popover p-0.5 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})}));qt.displayName=Fe.displayName;const ie=l.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(Oe,{ref:o,className:g("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-paragraph-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}));ie.displayName=Oe.displayName;const bo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Be,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-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(lt,{className:"h-4 w-4"})})}),e]}));bo.displayName=Be.displayName;const yo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(He,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-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(be,{className:"h-2 w-2 fill-current"})})}),e]}));yo.displayName=He.displayName;const wo=l.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(We,{ref:o,className:g("px-2 py-1.5 text-paragraph-sm font-semibold",e&&"pl-8",s),...n}));wo.displayName=We.displayName;const Qt=l.forwardRef(({className:s,...e},n)=>t.jsx(Ve,{ref:n,className:g("-mx-1 my-1 h-px bg-border",s),...e}));Qt.displayName=Ve.displayName;function Gt({item:s,level:e=0,onSelect:n,selectedId:o,isDropTarget:i=!1,onDownload:a,onRename:c,onDelete:f}){const[u,r]=l.useState(!0),d=o===s.id,p=()=>{s.type==="folder"&&r(!u)},h=()=>{n?.(s),s.type==="folder"&&p()},v=x=>{x.key==="Enter"||x.key===" "?(x.preventDefault(),h()):x.key==="ArrowRight"&&s.type==="folder"&&!u?(x.preventDefault(),r(!0)):x.key==="ArrowLeft"&&s.type==="folder"&&u&&(x.preventDefault(),r(!1))},m=()=>e===0?"p-2":e===1?"pl-8 pr-2 py-2":"pl-16 pr-2 py-2";return t.jsxs("div",{className:"flex flex-col w-full",children:[t.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":s.type==="folder"?u:void 0,className:g("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",m(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",d&&"bg-accent",i&&["bg-accent","border border-dashed border-border-dark"]),onClick:h,onKeyDown:v,children:[t.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:s.type==="folder"?u?t.jsx(Qs,{className:"size-4"}):t.jsx(Gs,{className:"size-4"}):t.jsx(Ks,{className:"size-4"})}),t.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:s.name}),t.jsxs(mo,{children:[t.jsx(go,{asChild:!0,children:t.jsx("button",{className:g("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:x=>{x.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:t.jsx(Js,{className:"size-4"})})}),t.jsxs(qt,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:x=>x.stopPropagation(),children:[a&&t.jsx(ie,{onClick:x=>{x.stopPropagation(),a(s)},children:"Download"}),c&&t.jsx(ie,{onClick:x=>{x.stopPropagation(),c(s)},children:"Rename"}),(a||c)&&f&&t.jsx(Qt,{}),f&&t.jsx(ie,{className:"text-destructive focus:text-destructive focus:bg-muted",onClick:x=>{x.stopPropagation(),f(s)},children:t.jsx("span",{className:"text-paragraph-sm",children:"Delete"})})]})]}),s.type==="folder"&&t.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-muted-foreground",children:t.jsx(se,{className:g("size-4 transition-transform",!u&&"-rotate-90")})})]}),s.type==="folder"&&u&&s.children&&t.jsx("div",{className:"flex flex-col",children:s.children.map(x=>t.jsx(Gt,{item:x,level:e+1,...n&&{onSelect:n},...o&&{selectedId:o},...a&&{onDownload:a},...c&&{onRename:c},...f&&{onDelete:f}},x.id))})]})}const vo=new qn;function No({className:s,provider:e=vo,onItemSelect:n,onDownload:o,onRename:i,onDelete:a}){const[c,f]=l.useState([]),[u,r]=l.useState(),[d,p]=l.useState(!0),[h,v]=l.useState();l.useEffect(()=>{(async()=>{try{p(!0);const b=await e.getRootItems();f(b),v(void 0)}catch(b){v(b instanceof Error?b.message:"Failed to load items")}finally{p(!1)}})()},[e]);const m=x=>{r(x.id),n?.(x)};return d?t.jsx("div",{className:g("",s),children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):h?t.jsx("div",{className:g("",s),children:t.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",h]})}):t.jsx("div",{className:g("flex flex-col",s),children:c.length===0?t.jsx("p",{className:"text-sm text-muted-foreground",children:"No items found"}):c.map(x=>t.jsx(Gt,{item:x,onSelect:m,...u&&{selectedId:u},...o&&{onDownload:o},...i&&{onRename:i},...a&&{onDelete:a}},x.id))})}const Kt=l.forwardRef(({source:s,isSelected:e,className:n,...o},i)=>t.jsxs("button",{ref:i,type:"button",className:g("group flex w-full text-left gap-2 items-start p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",e&&"bg-accent",n),onClick:()=>window.open(s.url,"_blank"),...o,children:[t.jsx("div",{className:"shrink-0 flex items-center h-5",children:t.jsx("div",{className:"relative rounded-[3px] size-4 overflow-hidden bg-muted",children:s.favicon?t.jsx("img",{alt:s.sourceName,className:"size-full object-cover",src:s.favicon}):t.jsx("div",{className:"size-full bg-muted"})})}),t.jsxs("div",{className:"flex flex-1 flex-col gap-1 min-w-0",children:[t.jsxs("div",{className:"text-paragraph-sm text-foreground",children:[t.jsx("span",{className:"font-medium",children:s.sourceName}),t.jsxs("span",{className:"text-muted-foreground",children:[" · ",s.title]})]}),t.jsx("p",{className:"text-paragraph-sm text-muted-foreground line-clamp-3",children:s.snippet})]})]}));Kt.displayName="SourceListItem";const Jt=l.forwardRef(({todo:s,className:e,...n},o)=>{const i=s.status==="completed";return t.jsxs("div",{ref:o,className:g("group flex items-center gap-2 p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",!1,e),role:"button",tabIndex:0,...n,children:[t.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:i?t.jsx(ct,{className:"size-4 text-muted-foreground"}):t.jsx(be,{className:"size-4 text-foreground"})}),t.jsx("p",{className:g("flex-1 text-foreground",i&&"line-through text-muted-foreground",s.status==="in_progress"&&"font-medium"),children:s.text})]})});Jt.displayName="TodoListItem";const Se=l.forwardRef(({client:s,todos:e,className:n,...o},i)=>{const a=e||[];return t.jsx("div",{ref:i,className:g("space-y-2 max-h-64 overflow-y-auto",n),...o,children:a.length===0?t.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"No tasks yet."}):a.map(c=>t.jsx(Jt,{todo:c},c.id))})});Se.displayName="TodoList";const fe=l.forwardRef(({todos:s,className:e,...n},o)=>{const i=s&&s.length>0?s:Gn;return t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:t.jsx(Se,{todos:i})})});fe.displayName="TodoTabContent";const me=l.forwardRef(({files:s=[],provider:e,onFileSelect:n,className:o,...i},a)=>{const c=l.useCallback(r=>{console.log("Download:",r.name)},[]),f=l.useCallback(r=>{console.log("Rename:",r.name)},[]),u=l.useCallback(r=>{console.log("Delete:",r.name)},[]);return t.jsx("div",{ref:a,className:g("h-full",o),...i,children:t.jsx(No,{...e&&{provider:e},onItemSelect:r=>{r.type==="file"&&n&&n(r.path||r.name)},onDownload:c,onRename:f,onDelete:u,className:"h-full"})})});me.displayName="FilesTabContent";const ge=l.forwardRef(({sources:s,className:e,...n},o)=>{const i=s&&s.length>0?s:Qn;return t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:i.map(a=>t.jsx(Kt,{source:a},a.id))})});ge.displayName="SourcesTabContent";const So=l.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-subheading",children:"Database"}),t.jsxs("div",{className:"text-paragraph-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-caption overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));So.displayName="DatabaseTabContent";const je=Ms,Y=l.forwardRef(({className:s,...e},n)=>t.jsx(qe,{ref:n,className:g("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...e}));Y.displayName=qe.displayName;const Z=l.forwardRef(({className:s,...e},n)=>t.jsx(Qe,{ref:n,className:g("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-paragraph-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}));Z.displayName=Qe.displayName;const _=l.forwardRef(({className:s,...e},n)=>t.jsx(Ge,{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}));_.displayName=Ge.displayName;const jo=l.forwardRef(({client:s,todos:e,variant:n="animated",showIcons:o=!1,visibleTabs:i=["todo","files","database"],className:a,...c},f)=>{const u=e||[],[r,d]=l.useState(i[0]||"todo"),p=l.useRef(null),h=l.useRef(null);l.useEffect(()=>{const b=setTimeout(()=>{const y=p.current;if(r&&y){const N=h.current;if(N){const j=y.getBoundingClientRect(),C=N.getBoundingClientRect(),I=C.left-j.left,U=C.width,S=I/j.width*100,R=100-(I+U)/j.width*100;y.style.clipPath=`inset(0 ${R.toFixed(2)}% 0 ${S.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(b)},[r]);const m=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:ye},{id:"files",label:"Files",icon:we},{id:"database",label:"Database",icon:dt},{id:"sources",label:"Sources",icon:ut}].filter(x=>i.includes(x.id));return t.jsx("div",{ref:f,className:g("select-none",a),...c,children:t.jsxs(je,{value:r,onValueChange:d,className:"w-full",children:[n==="pills"?t.jsx(Y,{className:g("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:m.map(x=>{const b=x.icon;return t.jsxs(Z,{value:x.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&b&&t.jsx(b,{className:"size-4"}),x.label]},x.id)})}):t.jsxs("div",{className:"relative mb-4 border-border",children:[t.jsx(Y,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:m.map(x=>t.jsx(Z,{value:x.id,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:x.label},x.id))}),t.jsx("div",{ref:p,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(Y,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:m.map(x=>t.jsx(Z,{value:x.id,ref:r===x.id?h:null,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:x.label},x.id))})})]}),t.jsx(_,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?t.jsx(fe,{todos:u}):t.jsx(Se,{todos:u})}),t.jsx(_,{value:"files",className:n==="pills"?"mt-0":"",children:t.jsx(me,{})}),t.jsx(_,{value:"database",className:n==="pills"?"mt-0":"",children:t.jsx("div",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})}),t.jsx(_,{value:"sources",className:n==="pills"?"mt-0":"",children:t.jsx(ge,{})})]})})});jo.displayName="ChatSecondaryPanel";const Co=l.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex h-full flex-col",s),...n,children:e}));Co.displayName="ChatSidebar.Root";const ko=l.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}));ko.displayName="ChatSidebar.Header";const To=l.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}));To.displayName="ChatSidebar.Content";const Io=l.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}));Io.displayName="ChatSidebar.Footer";const Eo=l.forwardRef(({children:s,className:e,...n},o)=>{const[i,a]=l.useState(s),[c,f]=l.useState(!1),u=l.useRef(s),r=l.useRef(!0);return l.useEffect(()=>{if(r.current){r.current=!1,u.current=s;return}if(u.current===s)return;f(!0);const d=setTimeout(()=>{a(s),u.current=s,requestAnimationFrame(()=>{f(!1)})},150);return()=>{clearTimeout(d)}},[s]),t.jsx("span",{ref:o,className:g("text-sm text-foreground opacity-60 transition-opacity duration-300",c?"opacity-0":"opacity-60",e),...n,children:i})});Eo.displayName="ChatStatus";const le=128e3,Ae={"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:le};function Ro(s){if(!s)return le;if(s in Ae)return Ae[s]??le;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:le}function Xt(s,e){const n=Ro(e);return s/n*100}function Ao(s,e,n=1){return`${Xt(s,e).toFixed(n)}%`}const V=H("gui");function Mo({children:s}){const{setPanelSize:e,setActiveTab:n}=oe(),o=()=>{e("small"),n("files")};return t.jsx(t.Fragment,{children:s({openFiles:o})})}function Uo(){const{activeTab:s,setActiveTab:e}=oe();return t.jsxs(je,{value:s,onValueChange:n=>e(n),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(Ce,{showIcons:!0,visibleTabs:["todo","files","sources"],variant:"compact"})}),t.jsx(_,{value:"todo",className:"flex-1 p-4 mt-0",children:t.jsx(fe,{})}),t.jsx(_,{value:"files",className:"flex-1 p-4 mt-0",children:t.jsx(me,{})}),t.jsx(_,{value:"sources",className:"flex-1 p-4 mt-0",children:t.jsx(ge,{})})]})}function Do({agentName:s,showHeader:e}){const{isExpanded:n,setIsExpanded:o}=Ne();return t.jsxs("div",{className:"flex lg:hidden items-center gap-2 flex-1",children:[e&&t.jsx("div",{className:"flex items-center gap-2 flex-1",children:t.jsx("h1",{className:"text-heading-4 text-foreground",children:s})}),!e&&t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle menu",onClick:()=>o(!n),children:t.jsx(pt,{className:g("size-4 text-muted-foreground transition-transform duration-200",n?"":"rotate-180")})})]})}function Po({agentName:s,todos:e,sources:n,showHeader:o}){const{panelSize:i,setPanelSize:a}=oe();return t.jsxs(kt,{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:[o&&t.jsx("div",{className:"flex items-center gap-2 flex-1",children:t.jsx("h1",{className:"text-heading-4 text-foreground",children:s})}),!o&&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(i==="hidden"?"small":"hidden")},children:t.jsx(en,{className:"size-4 text-muted-foreground"})})]}),t.jsx(Do,{agentName:s,showHeader:o}),t.jsx(Tt,{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(je,{defaultValue:"todo",className:"w-full",children:[t.jsx(Ce,{showIcons:!0,visibleTabs:["todo","files","sources"],variant:"default"}),t.jsx(_,{value:"todo",className:"mt-4",children:t.jsx(fe,{todos:e})}),t.jsx(_,{value:"files",className:"mt-4",children:t.jsx(me,{})}),t.jsx(_,{value:"sources",className:"mt-4",children:t.jsx(ge,{sources:n})})]})})]})}function zo({client:s,initialSessionId:e,error:n}){const{connectionStatus:o,connect:i,sessionId:a,startSession:c}=Cn(s,e),{messages:f,sendMessage:u}=yt(s,c);kn(s);const r=T(S=>S.error),d=T(S=>S.currentModel),[p,h]=l.useState("Agent"),[v,m]=l.useState(typeof window<"u"?window.innerWidth>=1024:!0),[x,b]=l.useState("Type a message or / for commands...");l.useEffect(()=>{V.debug("Connection status changed",{status:o}),o==="error"&&r&&V.error("Connection error occurred",{error:r})},[o,r]),l.useEffect(()=>{if(s&&a){const S=s.getCurrentSession();S?.metadata?.agentName&&h(S.metadata.agentName)}},[s,a]),l.useEffect(()=>{const S=window.matchMedia("(min-width: 1024px)"),R=P=>{m(P.matches)};return m(S.matches),S.addEventListener("change",R),()=>{S.removeEventListener("change",R)}},[]);const y=S=>{b(S)},N=()=>{b("Type a message or / for commands...")};if(n)return t.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:t.jsxs("div",{className:"text-center p-8 max-w-md",children:[t.jsx("h1",{className:"text-2xl font-bold text-destructive mb-4",children:"Initialization Error"}),t.jsx("p",{className:"text-foreground mb-4",children:n}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})});const j=[],C=[{id:"1",title:"Boeing Scores Early Wins at Dubai Airshow",sourceName:"Reuters",url:"https://www.reuters.com/markets/companies/BA.N",snippet:"DUBAI, Nov 17 (Reuters) - Boeing (BA.N), opens new tab took centre stage at day one of the Dubai Airshow on Monday, booking a $38 billion order from host carrier Emirates and clinching more deals with African carriers, while China displayed its C919 in the Middle East for the first time.",favicon:"https://www.google.com/s2/favicons?domain=reuters.com&sz=32"},{id:"2",title:"Boeing's Sustainable Aviation Goals Take Flight",sourceName:"Forbes",url:"https://www.forbes.com",snippet:"SEATTLE, Nov 18 (Reuters) - Boeing is making headway towards its sustainability targets, unveiling plans for a new eco-friendly aircraft design aimed at reducing emissions by 50% by 2030.",favicon:"https://www.google.com/s2/favicons?domain=forbes.com&sz=32"},{id:"3",title:"Boeing Faces Increased Competition in Global Aviation Market",sourceName:"Reuters",url:"https://www.reuters.com",snippet:"CHICAGO, Nov 19 (Reuters) - As the global aviation industry rebounds post-pandemic, Boeing is grappling with intensified competition from rival manufacturers, particularly in the Asian market.",favicon:"https://www.google.com/s2/favicons?domain=reuters.com&sz=32"},{id:"4",title:"Boeing's Starliner Successfully Completes Orbital Test Flight",sourceName:"The Verge",url:"https://www.theverge.com",snippet:"NASA, Nov 20 (Reuters) - Boeing's CST-100 Starliner spacecraft achieves a significant milestone, successfully completing its orbital test flight, paving the way for future crewed missions to the International Space Station.",favicon:"https://www.google.com/s2/favicons?domain=theverge.com&sz=32"}],I=f.slice().reverse().find(S=>S.role==="assistant"&&S.tokenUsage)?.tokenUsage,U=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:t.jsx(Ie,{className:"h-4 w-4"}),category:"model",onSelect:()=>{V.info("User selected Sonnet 4.5 model")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:t.jsx(Ie,{className:"h-4 w-4"}),category:"model",onSelect:()=>{V.info("User selected Opus model")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:t.jsx(Xs,{className:"h-4 w-4"}),category:"action",onSelect:()=>{V.info("User opened settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:t.jsx(Ys,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{V.info("User enabled code mode")}}];return t.jsxs(Ot,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[t.jsxs(Bt,{children:[t.jsx(Po,{agentName:p,todos:j,sources:C,showHeader:f.length>0}),o==="error"&&r&&t.jsx("div",{className:"border-b border-destructive/20 bg-destructive/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-paragraph-sm font-semibold text-destructive",children:"Connection Error"}),t.jsx("p",{className:"whitespace-pre-line text-paragraph-sm text-foreground",children:r})]}),t.jsx("button",{type:"button",onClick:i,className:"rounded-lg bg-destructive px-4 py-2 text-paragraph-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive-hover",children:"Retry"})]})}),t.jsxs($t,{children:[t.jsx(Ht,{children:f.length===0?t.jsx(Mo,{children:({openFiles:S})=>t.jsx("div",{className:"flex flex-1 items-center px-4",children:t.jsx(jt,{title:p,description:"This agent can help you with your tasks. Start a conversation by typing a message below.",suggestedPrompts:["Search the web for the latest news on top tech company earnings, produce a summary for each company, and then a macro trend analysis of the tech industry. Use your todo list","Explain how this works","Create a new feature","Review my changes"],onPromptClick:R=>{u(R),b("Type a message or / for commands..."),V.info("Prompt clicked",{prompt:R})},onPromptHover:y,onPromptLeave:N,onOpenFiles:S})})}):t.jsx("div",{className:"flex flex-col px-4",children:f.map((S,R)=>{const P=R===0,Q=P?null:f[R-1];let B="mt-2";return P?B="mt-2":S.role==="user"?B=(Q?.role==="user","mt-4"):S.role==="assistant"&&(B=Q?.role==="assistant"?"mt-2":"mt-6"),t.jsx(ts,{message:S,className:B,isLastMessage:R===f.length-1,children:t.jsx(ns,{message:S,thinkingDisplayStyle:"collapsible"})},S.id)})})}),t.jsx(Wt,{children:t.jsxs(Rt,{client:s,startSession:c,children:[t.jsx(_t,{commands:U}),t.jsx(At,{placeholder:x,autoFocus:!0}),t.jsxs(Ut,{children:[t.jsxs("div",{className:"flex items-baseline gap-1",children:[t.jsx(Dt,{}),t.jsx(Pt,{}),I&&t.jsx(Zt,{percentage:Xt(I.totalTokens??0,d??void 0),tokens:I.totalTokens??0,formattedPercentage:Ao(I.totalTokens??0,d??void 0)})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(zt,{}),t.jsx(Mt,{children:t.jsx(Zs,{className:"size-4"})})]})]})]})})]})]}),v&&t.jsx(Vt,{breakpoint:"lg",children:t.jsx(Uo,{})})]})}const _o=Us,Lo=Ds,Fo=Ps,Yt=l.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(Ke,{ref:o,sideOffset:e,className:g("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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}));Yt.displayName=Ke.displayName;const Zt=l.forwardRef(({percentage:s,tokens:e,formattedPercentage:n,className:o,...i},a)=>{const c=Math.min(100,Math.max(0,s)),f=16,u=2,r=(f-u)/2,d=f/2,p=2*Math.PI*r,h=p-c/100*p;return t.jsx(_o,{children:t.jsxs(Lo,{children:[t.jsx(Fo,{asChild:!0,children:t.jsx(X,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full cursor-default",o),...i,children:t.jsxs("svg",{width:f,height:f,viewBox:`0 0 ${f} ${f}`,className:"transform -rotate-90",children:[t.jsx("circle",{cx:d,cy:d,r,stroke:"currentColor",strokeWidth:u,fill:"transparent",className:"opacity-20"}),t.jsx("circle",{cx:d,cy:d,r,stroke:"currentColor",strokeWidth:u,fill:"transparent",strokeDasharray:p,strokeDashoffset:h,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),t.jsx(Yt,{side:"top",align:"center",children:t.jsxs("p",{children:["Context: ",n," (",e.toLocaleString()," tokens)"]})})]})})});Zt.displayName="ContextUsageButton";const Oo=l.forwardRef(({autoScroll:s=!0,isStreaming:e=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:i=!0,scrollButton:a,className:c,children:f,...u},r)=>{const d=l.useRef(null),[p,h]=l.useState(!0),[v,m]=l.useState(!1),x=l.useRef(0);l.useImperativeHandle(r,()=>{if(!d.current)throw new Error("Container ref not initialized");return d.current});const b=l.useCallback(()=>{const N=d.current;if(!N)return;const{scrollTop:j,scrollHeight:C,clientHeight:I}=N,S=C-j-I<o;h(S),m(!S&&i),x.current=j},[o,i]),y=l.useCallback((N=n)=>{const j=d.current;j&&j.scrollTo({top:j.scrollHeight,behavior:N})},[n]);return l.useEffect(()=>{!s||!d.current||(e&&p?y("auto"):!e&&p&&y())},[s,e,p,y]),l.useEffect(()=>{const N=d.current;if(!N)return;const j=()=>{b()};return N.addEventListener("scroll",j,{passive:!0}),b(),()=>{N.removeEventListener("scroll",j)}},[b]),l.useEffect(()=>{const N=d.current;if(!N)return;const j=new ResizeObserver(()=>{p&&s&&y("auto")});return j.observe(N),()=>{j.disconnect()}},[p,s,y]),t.jsxs("div",{className:"relative flex-1",children:[t.jsx("div",{ref:d,className:g("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",c),...u,children:t.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:f})}),v&&t.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:a||t.jsxs("button",{type:"button",onClick:()=>y(),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"]})})]})});Oo.displayName="Conversation";const Bo=zs,es=l.forwardRef(({className:s,...e},n)=>t.jsx(Je,{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}));es.displayName=Je.displayName;const $o=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Bo,{children:[t.jsx(es,{}),t.jsxs(Xe,{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(_s,{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(tn,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));$o.displayName=Xe.displayName;const Ho=l.forwardRef(({className:s,...e},n)=>t.jsx(Ye,{ref:n,className:g("text-subheading font-semibold leading-none tracking-tight",s),...e}));Ho.displayName=Ye.displayName;const Wo=l.forwardRef(({className:s,...e},n)=>t.jsx(Ze,{ref:n,className:g("text-paragraph-sm text-muted-foreground",s),...e}));Wo.displayName=Ze.displayName;const Vo=q("flex h-10 w-full rounded-md border bg-input-background px-3 py-2 text-paragraph-sm ring-offset-background file:border-0 file:bg-transparent file:text-paragraph-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"}}),qo=l.forwardRef(({className:s,type:e,variant:n,...o},i)=>t.jsx("input",{type:e,className:g(Vo({variant:n,className:s})),ref:i,...o}));qo.displayName="Input";const Qo=l.forwardRef(({className:s,...e},n)=>t.jsx(et,{ref:n,className:g("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...e}));Qo.displayName=et.displayName;const Go=q("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"}}),ts=l.forwardRef(({message:s,role:e,layout:n,className:o,children:i,messageId:a,autoScroll:c,isLastMessage:f=!1,...u},r)=>{const d=s?s.role:e||"assistant",p=s?s.id:a,h=l.useRef(null),[v,m]=l.useState(void 0);return l.useImperativeHandle(r,()=>h.current),l.useEffect(()=>{if(!f||d!=="assistant"){m(void 0);return}const x=()=>{const y=h.current;if(!y)return;let N=y.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;if(!N)return;const j=y.previousElementSibling;if(!j||j.getAttribute("aria-label")!=="user message"){m(void 0);return}const C=N.clientHeight,I=j.offsetHeight,S=Math.max(0,C-I-32);m(S)};x();const b=new ResizeObserver(x);if(h.current){b.observe(h.current);let y=h.current.parentElement;for(;y&&!y.classList.contains("overflow-y-auto");)y=y.parentElement;y&&b.observe(y)}return()=>b.disconnect()},[f,d]),l.useEffect(()=>{if((c!==void 0?c:d==="user")&&h.current){const b=setTimeout(()=>{h.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(b)}},[d,c]),t.jsx("article",{ref:h,"aria-label":`${d} message`,"data-message-id":p,className:g(Go({role:d,layout:n}),o),style:{minHeight:v!==void 0?`${v}px`:void 0},...u,children:i})});ts.displayName="Message";const Me=q("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"}}),Ko=q("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),ss=l.forwardRef(({content:s,isStreaming:e=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:i=!1,autoCollapse:a=!0,autoCollapseDelay:c=2e3,label:f="Thinking",variant:u,className:r},d)=>{const[p,h]=l.useState(n==="inline"?!0:o),[v,m]=l.useState(!1);return l.useEffect(()=>{if(a&&!e&&s&&n==="collapsible"){const x=setTimeout(()=>{m(!0),h(!1)},c);return()=>clearTimeout(x)}},[e,s,a,c,n]),l.useEffect(()=>{i&&e&&n==="collapsible"&&!v&&h(!0)},[i,e,n,v]),!s&&!e?null:n==="inline"?t.jsxs("div",{ref:d,className:g(Me({variant:u}),"p-3",r),children:[t.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[t.jsx("span",{className:"text-caption 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-paragraph-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:d,className:g("mb-3",r),children:[t.jsxs("button",{type:"button",onClick:()=>{h(!p),m(!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":p,"aria-label":`${p?"Collapse":"Expand"} reasoning`,children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx("span",{className:"text-caption 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"}),!p&&s&&t.jsxs("span",{className:"text-caption text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),t.jsx(se,{className:Ko({expanded:p}),"aria-hidden":"true"})]}),p&&t.jsx("div",{className:g(Me({variant:u}),"mt-2 p-3 animate-fadeIn"),children:t.jsxs("div",{className:"text-paragraph-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:"..."})]})})]})});ss.displayName="Reasoning";const ce=l.forwardRef(({content:s,isStreaming:e=!1,showEmpty:n=!0,emptyMessage:o="",className:i,...a},c)=>{if(!s&&e&&n)return t.jsx("div",{ref:c,className:g("opacity-70 italic text-paragraph-sm",i),...a,children:o});if(!s)return null;const f={table:({node:u,...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:u,...r})=>t.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:u,...r})=>t.jsx("tbody",{...r}),tr:({node:u,...r})=>t.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:u,...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:u,...r})=>t.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:u,checked:r,...d})=>d.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",...d}):t.jsx("input",{...d}),code:({node:u,...r})=>r.className?.includes("language-")?t.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-code text-foreground shadow-sm",...r}):t.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code text-foreground",...r}),pre:({node:u,...r})=>t.jsx("pre",{className:"my-4 rounded-lg",...r}),h1:({node:u,...r})=>t.jsx("h1",{className:"text-heading-3 mt-6 mb-4 text-foreground border-b border-border pb-2",...r}),h2:({node:u,...r})=>t.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...r}),h3:({node:u,...r})=>t.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...r}),h4:({node:u,...r})=>t.jsx("h4",{className:"text-paragraph-sm font-semibold mt-3 mb-2 text-foreground",...r}),ul:({node:u,...r})=>{const d=u?.children?.some(p=>typeof p=="object"&&p!==null&&"type"in p&&p.type==="element"&&"tagName"in p&&p.tagName==="li"&&"children"in p&&Array.isArray(p.children)&&p.children.some(h=>typeof h=="object"&&h!==null&&"type"in h&&h.type==="element"&&"tagName"in h&&h.tagName==="input"&&"properties"in h&&typeof h.properties=="object"&&h.properties!==null&&"type"in h.properties&&h.properties.type==="checkbox"));return t.jsx("ul",{className:g("my-2 space-y-1 text-foreground",d?"list-none space-y-2":"list-disc list-outside pl-4"),...r})},ol:({node:u,...r})=>t.jsx("ol",{className:"list-decimal list-outside pl-4 my-2 space-y-1 text-foreground",...r}),li:({node:u,...r})=>{const d=u?.children?.some(p=>typeof p=="object"&&p!==null&&"type"in p&&p.type==="element"&&"tagName"in p&&p.tagName==="input"&&"properties"in p&&typeof p.properties=="object"&&p.properties!==null&&"type"in p.properties&&p.properties.type==="checkbox");return t.jsx("li",{className:g(d?"flex items-start gap-2":""),...r})},a:({node:u,...r})=>t.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:u,...r})=>t.jsx("p",{className:"mb-2 text-foreground leading-relaxed",...r}),blockquote:({node:u,...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:u,...r})=>t.jsx("hr",{className:"my-6 border-t border-border opacity-50",...r})};return t.jsx("div",{ref:c,className:g("markdown-content prose prose-sm max-w-none dark:prose-invert",i),...a,children:t.jsx(ys,{remarkPlugins:[cn],components:f,children:s})})});ce.displayName="Response";const Ue={Globe:an,Link:rn,Cloud:on,CheckSquare:ye,Search:nn,FileText:we,Edit:sn,Wrench:ft};function De({toolCall:s}){const[e,n]=l.useState(!1),o=s.icon&&Ue[s.icon]?Ue[s.icon]:ft,i=s.prettyName||s.title;return t.jsxs("div",{className:"flex flex-col my-4",children:[t.jsx("button",{type:"button",className:"flex items-center gap-2 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>n(!e),"aria-expanded":e,children:t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-zinc-500",children:[t.jsx("div",{className:"text-zinc-500",children:t.jsx(o,{className:"h-3 w-3"})}),t.jsx("span",{className:"text-paragraph-sm text-zinc-500",children:i}),t.jsx(se,{className:`h-3 w-3 text-zinc-400 transition-transform duration-200 ${e?"rotate-180":""}`})]})}),e&&t.jsxs("div",{className:"mt-2 text-sm border border-zinc-200 rounded-lg bg-zinc-50 overflow-hidden w-full",children:[s.locations&&s.locations.length>0&&t.jsxs("div",{className:"p-3 border-b border-zinc-200",children:[t.jsx("div",{className:"text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-1.5 font-sans",children:"Files"}),t.jsx("ul",{className:"space-y-1",children:s.locations.map(a=>t.jsxs("li",{className:"font-mono text-[11px] text-zinc-700 bg-zinc-200/50 px-1.5 py-0.5 rounded w-fit",children:[a.path,a.line!==null&&a.line!==void 0&&`:${a.line}`]},`${a.path}:${a.line??""}`))})]}),s.rawInput&&Object.keys(s.rawInput).length>0&&t.jsxs("div",{className:"p-3 border-b border-zinc-200",children:[t.jsx("div",{className:"text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-1.5 font-sans",children:"Input"}),t.jsx("div",{className:"text-[11px] font-mono text-zinc-700",children:t.jsx(Te,{value:s.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit"}})})]}),s.content&&s.content.length>0||s.error?t.jsxs("div",{className:"p-3 border-b border-zinc-200 last:border-0",children:[t.jsx("div",{className:"text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-1.5 font-sans",children:"Output"}),t.jsxs("div",{className:"space-y-2 text-[11px] text-zinc-700",children:[s.content?.map((a,c)=>{const f=()=>a.type==="diff"&&"path"in a?`diff-${a.path}-${c}`:a.type==="terminal"&&"terminalId"in a?`terminal-${a.terminalId}`:a.type==="text"&&"text"in a?`text-${a.text.substring(0,20)}-${c}`:a.type==="content"&&"content"in a?`content-${a.content.text?.substring(0,20)}-${c}`:`block-${c}`,u=(r,d)=>{try{const p=JSON.parse(r);if(typeof p=="object"&&p!==null)return t.jsx("div",{className:"text-[11px]",children:t.jsx(Te,{value:p,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit"}})},d)}catch{}return t.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-zinc-700 overflow-x-auto",children:r},d)};if(a.type==="content"&&"content"in a){const r=a.content;if(r.type==="text"&&r.text)return u(r.text,f())}return a.type==="text"&&"text"in a?u(a.text,f()):a.type==="diff"&&"path"in a&&"oldText"in a&&"newText"in a?t.jsxs("div",{className:"border border-zinc-200 rounded bg-white",children:[t.jsxs("div",{className:"bg-zinc-50 px-2 py-1 text-[10px] font-mono text-zinc-500 border-b border-zinc-200",children:[a.path,"line"in a&&a.line!==null&&a.line!==void 0&&`:${a.line}`]}),t.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[t.jsxs("div",{className:"text-red-600",children:["- ",a.oldText]}),t.jsxs("div",{className:"text-green-600",children:["+ ",a.newText]})]})]},f()):a.type==="terminal"&&"terminalId"in a?t.jsxs("div",{className:"bg-zinc-900 text-zinc-100 p-2 rounded text-[11px] font-mono",children:["Terminal: ",a.terminalId]},f()):null}),s.error&&t.jsxs("div",{className:"text-red-600 font-mono text-[11px] mt-2",children:["Error: ",s.error]})]})]}):null,(s.tokenUsage||s.startedAt)&&t.jsxs("div",{className:"p-2 bg-zinc-100/50 border-t border-zinc-200 flex flex-wrap gap-4 text-[10px] text-zinc-500 font-sans",children:[s.tokenUsage&&t.jsxs("div",{className:"flex gap-3",children:[s.tokenUsage.inputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Input:"}),s.tokenUsage.inputTokens.toLocaleString()]}),s.tokenUsage.outputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Output:"}),s.tokenUsage.outputTokens.toLocaleString()]}),s.tokenUsage.totalTokens!==void 0&&t.jsxs("div",{children:[t.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Total:"}),s.tokenUsage.totalTokens.toLocaleString()]})]}),s.startedAt&&t.jsxs("div",{className:"flex gap-3 ml-auto",children:[t.jsxs("span",{children:["Started: ",new Date(s.startedAt).toLocaleTimeString()]}),s.completedAt&&t.jsxs("span",{children:["Completed:"," ",new Date(s.completedAt).toLocaleTimeString()," (",Math.round((s.completedAt-s.startedAt)/1e3),"s)"]})]})]})]})]})}const ae=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],Pe=["...","·..",".·.","..·",".·.","·.."];function Jo({startTime:s}){const[e,n]=l.useState(0),[o,i]=l.useState(()=>ae[Math.floor(Math.random()*ae.length)]),[a,c]=l.useState(0);l.useEffect(()=>{const r=setInterval(()=>{const p=Date.now()-s;n(p)},100);return()=>clearInterval(r)},[s]),l.useEffect(()=>{const r=setInterval(()=>{const d=Math.floor(Math.random()*ae.length);i(ae[d])},1500);return()=>clearInterval(r)},[]),l.useEffect(()=>{const r=setInterval(()=>{c(d=>(d+1)%Pe.length)},100);return()=>clearInterval(r)},[]);const f=(e/1e3).toFixed(1),u=Pe[a];return t.jsxs("span",{className:"text-muted-foreground text-paragraph-sm",children:[o,u," ",f,"s"]})}const Xo=q("w-full rounded-2xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-secondary text-foreground px-4 py-4 text-paragraph",assistant:"text-foreground text-paragraph-sm",system:"bg-card border border-border text-foreground opacity-80 text-caption px-4 py-3"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),ns=l.forwardRef(({role:s,variant:e,isStreaming:n,message:o,thinkingDisplayStyle:i="collapsible",className:a,children:c,...f},u)=>{const r=T(m=>m.streamingStartTime);T(m=>m.currentModel);const d=o&&!c,p=d?o.role:s||"assistant",h=d?o.isStreaming:n;let v=c;if(d){const m=o.metadata?.thinking,x=!!m,b=o.isStreaming&&!o.content&&o.role==="assistant";v=t.jsxs(t.Fragment,{children:[o.role==="assistant"&&x&&t.jsx(ss,{content:m,isStreaming:o.isStreaming,mode:i,autoCollapse:!0}),b&&r&&t.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[t.jsx(mt,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx(Jo,{startTime:r})]}),o.role==="assistant"?(()=>{const y=(o.toolCalls||[]).slice().sort((C,I)=>(C.contentPosition??1/0)-(I.contentPosition??1/0));if(y.length===0||!y.some(C=>C.contentPosition!==void 0))return t.jsxs(t.Fragment,{children:[y.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mb-1",children:y.map(C=>t.jsx(De,{toolCall:C},C.id))}),t.jsx(ce,{content:o.content,isStreaming:o.isStreaming,showEmpty:!1})]});const N=[];let j=0;if(y.forEach(C=>{const I=C.contentPosition??o.content.length;if(I>j){const U=o.content.slice(j,I);U&&N.push(t.jsx(ce,{content:U,isStreaming:!1,showEmpty:!1},`text-before-${C.id}`))}N.push(t.jsx("div",{children:t.jsx(De,{toolCall:C})},`tool-${C.id}`)),j=I}),j<o.content.length){const C=o.content.slice(j);C&&N.push(t.jsx(ce,{content:C,isStreaming:o.isStreaming,showEmpty:!1},"text-end"))}return t.jsx(t.Fragment,{children:N})})():t.jsx("div",{className:"whitespace-pre-wrap",children:o.content})]})}return t.jsx("div",{ref:u,className:g(Xo({role:p,variant:e}),h&&"animate-pulse-subtle",a),...f,children:v})});ns.displayName="MessageContent";const Ce=l.forwardRef(({showIcons:s=!0,visibleTabs:e=["todo","files"],variant:n="default",className:o,...i},a)=>{const f=[{id:"todo",label:"To-do",icon:ye},{id:"files",label:"Files",icon:we},{id:"database",label:"Database",icon:dt},{id:"sources",label:"Sources",icon:ut}].filter(r=>e.includes(r.id)),u=n==="compact"?"gap-[4px]":"gap-3";return t.jsx(Y,{ref:a,className:g("w-full justify-start bg-transparent p-0 h-auto",u,o),...i,children:f.map(r=>{const d=r.icon;return t.jsxs(Z,{value:r.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[s&&d&&t.jsx(d,{className:"size-4"}),r.label]},r.id)})})});Ce.displayName="PanelTabsHeader";const Yo=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(tt,{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-paragraph-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(Ls,{asChild:!0,children:t.jsx(ln,{className:"h-4 w-4 opacity-50"})})]}));Yo.displayName=tt.displayName;const os=l.forwardRef(({className:s,...e},n)=>t.jsx(st,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(pt,{className:"h-4 w-4"})}));os.displayName=st.displayName;const rs=l.forwardRef(({className:s,...e},n)=>t.jsx(nt,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(se,{className:"h-4 w-4"})}));rs.displayName=nt.displayName;const Zo=l.forwardRef(({className:s,children:e,position:n="popper",...o},i)=>t.jsx(Fs,{children:t.jsxs(ot,{ref:i,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(os,{}),t.jsx(Os,{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(rs,{})]})}));Zo.displayName=ot.displayName;const er=l.forwardRef(({className:s,...e},n)=>t.jsx(rt,{ref:n,className:g("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",s),...e}));er.displayName=rt.displayName;const tr=l.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(at,{ref:o,className:g("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-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(Bs,{children:t.jsx(lt,{className:"h-4 w-4"})})}),t.jsx($s,{children:e})]}));tr.displayName=at.displayName;const sr=l.forwardRef(({className:s,...e},n)=>t.jsx(it,{ref:n,className:g("-mx-1 my-1 h-px bg-muted",s),...e}));sr.displayName=it.displayName;const as=l.forwardRef(({task:s,collapsible:e=!0,defaultExpanded:n=!1,onTaskClick:o,className:i,...a},c)=>{const[f,u]=l.useState(n),r=!!(s.details||s.files&&s.files.length>0),d={pending:be,in_progress:mt,completed:ct}[s.status],p=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},h=()=>{r&&e&&u(!f),o?.(s)};return t.jsxs("div",{ref:c,className:g("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",i),...a,children:[t.jsxs("button",{type:"button",onClick:h,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(d,{className:g("w-4 h-4 shrink-0",p(),s.status==="in_progress"&&"animate-spin")}),t.jsx("span",{className:g("flex-1 text-paragraph-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(se,{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-paragraph-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-caption font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),t.jsx("div",{className:"space-y-1",children:s.files.map(v=>t.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:v},v))})]})]})]})});as.displayName="Task";const nr=l.forwardRef(({tasks:s,collapsible:e=!0,onTaskClick:n,emptyMessage:o="No tasks yet.",className:i,...a},c)=>t.jsx("div",{ref:c,className:g("space-y-2 max-h-96 overflow-y-auto",i),...a,children:s.length===0?t.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:o}):s.map(f=>t.jsx(as,{task:f,collapsible:e,...n?{onTaskClick:n}:{}},f.id))}));nr.displayName="TaskList";const or=q("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-paragraph-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"}}),rr=l.forwardRef(({className:s,autoResize:e=!1,maxHeight:n=200,variant:o,...i},a)=>{const c=l.useRef(null),f=l.useCallback(r=>{c.current=r,typeof a=="function"?a(r):a&&(a.current=r)},[a]),u=l.useCallback(()=>{const r=c.current;if(!r||!e)return;r.style.height="auto";const d=Math.min(r.scrollHeight,n);r.style.height=`${d}px`,r.scrollHeight>n?r.style.overflowY="auto":r.style.overflowY="hidden"},[e,n]);return l.useEffect(()=>{u()},[u]),t.jsx("textarea",{className:g(or({variant:o}),e&&"overflow-y-hidden",s),ref:f,...i})});rr.displayName="Textarea";function ar(){return"http://localhost:3100"}const ir={agentServerUrl:ar()};function lr(){const{client:s,error:e,sessionId:n}=wn({serverUrl:ir.agentServerUrl});return t.jsx(zo,{client:s,initialSessionId:n,error:e})}const is=document.getElementById("root");if(!is)throw new Error("Root element not found");ws.createRoot(is).render(t.jsx(vs.StrictMode,{children:t.jsx(lr,{})}));
|