@townco/gui-template 0.1.74 → 0.1.75

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,9 +0,0 @@
1
- import{r as l,j as e,M as Da,b as pt,h as Pa}from"./react-CDboZAE4.js";import{S as ve,L as Ua,M as Pt,N as ne,O as D,P as A,Q as w,R as Me,T as W,U as q,W as xe,X as se,Y as ae,Z as La,$ as Fe,a0 as ft,a1 as Oa,a2 as za,a3 as $a,a4 as ue,a5 as Fa,a6 as Y,a7 as Ba,a8 as Ie,a9 as Ha,aa as Gt,ab as Ut}from"./vendor-DXWxTThl.js";import{P as Lt,a as Wa}from"./acp-sdk-D41ZZ6b1.js";import{S as ce,a as Qt,b as Yt,P as Va,C as Xt,I as Jt,c as Zt,d as es,R as ts,L as ss,e as as,f as qa,T as Ka,O as We,g as ns,h as Ve,i as os,j as qe,D as Ke,k as Ga,l as rs,m as Qa,n as Ya,o as Xa,p as is,q as ls,r as cs,s as Ja,t as ds,u as us,v as Za,w as ps,x as ms,y as en,z as fs,V as tn,A as gs,B as hs,E as sn,F as an,G as xs}from"./radix-CUzxVG1O.js";import{c as _e,d as bs,e as Ge,f as gt,P as nn,E as on,g as rn,S as ln,h as cn,i as dn,A as un,F as pn,j as mn,k as fn,l as gn,m as me,n as Qe,o as Ye,p as ht,q as ys,r as vs,B as Ot,s as hn,t as xn,u as ws,v as js,w as xt,x as Ns,T as bn,y as rt,z as zt,G as $t,H as bt,I as yn,W as vn,J as wn,K as jn,N as Nn,O as Sn,Q as kn,U as Cn,V as Tn,Y as In,_ as _n,$ as Rn}from"./icons-D_apzdqV.js";import{r as En}from"./markdown-DB_sQ8pp.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const r of i.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&a(r)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Mn={};const Ue=typeof process<"u"&&process.versions?.node;let An,Dn=0;const Pn=new Set;function Un(t){for(const s of Pn)s(t)}const Ft={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},Ln={trace:ve.TRACE,debug:ve.DEBUG,info:ve.INFO,warn:ve.WARN,error:ve.ERROR,fatal:ve.FATAL};class On{service;minLevel;logFilePath;logsDir;writeQueue=[];isWriting=!1;enableConsoleOutput;constructor(s,n="debug"){this.service=s,this.minLevel=n,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&Mn?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){if(!(!this.logFilePath||!Ue)&&(this.writeQueue.push(s),!this.isWriting)){for(this.isWriting=!0;this.writeQueue.length>0;){const a=`${this.writeQueue.splice(0,this.writeQueue.length).join(`
2
- `)}
3
- `;try{await require("node:fs").promises.appendFile(this.logFilePath,a,"utf-8")}catch{}}this.isWriting=!1}}shouldLog(s){return Ft[s]>=Ft[this.minLevel]}log(s,n,a){if(!this.shouldLog(s))return;const o={id:`log_${++Dn}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:n,...a&&{metadata:a}};if(Un(o),Ue&&this.logFilePath,Ue&&this.logFilePath){const u={timestamp:o.timestamp,level:o.level,service:o.service,message:o.message,...o.metadata&&{metadata:o.metadata}};this.writeToFile(JSON.stringify(u)).catch(()=>{})}if(Ue&&this.enableConsoleOutput){const u=o.timestamp,p=o.level.toUpperCase().padEnd(5),d=`[${this.service}]`,c=o.metadata?` ${JSON.stringify(o.metadata)}`:"";console.log(`${u} ${p} ${d} ${o.message}${c}`)}const i=Ua.getLogger(this.service),r=Pt.trace.getSpan(Pt.context.active());i.emit({severityNumber:Ln[s],severityText:s.toUpperCase(),body:n,attributes:{service:this.service,...a&&Object.fromEntries(Object.entries(a).map(([u,p])=>[`log.${u}`,typeof p=="object"?JSON.stringify(p):p])),...r&&{trace_id:r.spanContext().traceId,span_id:r.spanContext().spanId}}})}trace(s,n){this.log("trace",s,n)}debug(s,n){this.log("debug",s,n)}info(s,n){this.log("info",s,n)}warn(s,n){this.log("warn",s,n)}error(s,n){this.log("error",s,n)}fatal(s,n){this.log("fatal",s,n)}}function de(t,s="debug"){return new On(t,s)}const z=de("http-transport");class zn{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;agentInfo;constructor(s){this.options={...s,baseUrl:s.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const s={protocolVersion:Lt,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",s);if(n.agentInfo){const i=n._meta,r=i&&typeof i=="object",u=r&&"agentDescription"in i?String(i.agentDescription):void 0,p=r&&"suggestedPrompts"in i&&Array.isArray(i.suggestedPrompts)?i.suggestedPrompts:void 0,d=r&&"tools"in i&&Array.isArray(i.tools)?i.tools:void 0,c=r&&"mcps"in i&&Array.isArray(i.mcps)?i.mcps:void 0,g=r&&"subagents"in i&&Array.isArray(i.subagents)?i.subagents:void 0,m=r&&"initialMessage"in i&&i.initialMessage&&typeof i.initialMessage=="object"?i.initialMessage:void 0,x=r&&"uiConfig"in i&&i.uiConfig&&typeof i.uiConfig=="object"?i.uiConfig:void 0;this.agentInfo={name:n.agentInfo.name,...n.agentInfo.title?{displayName:n.agentInfo.title}:{},version:n.agentInfo.version,...u?{description:u}:{},...p?{suggestedPrompts:p}:{},...m?{initialMessage:m}:{},...x?{uiConfig:x}:{},...d?{tools:d}:{},...c?{mcps:c}:{},...g?{subagents:g}:{}}}z.info("ACP connection initialized",{initResponse:n});const a={cwd:"/",mcpServers:[]},o=await this.sendRpcRequest("session/new",a);this.currentSessionId=o.sessionId,z.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(s){this.connected=!1;const n=s instanceof Error?s:new Error(String(s));throw this.notifyError(n),n}}async loadSession(s){this.connected&&(z.warn("Transport already connected, disconnecting first",{sessionId:s}),await this.disconnect());try{this.abortController=new AbortController;const n={protocolVersion:Lt,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};z.info("Loading session - initializing connection",{sessionId:s});const a=await this.sendRpcRequest("initialize",n);if(a.agentInfo){const r=a._meta,u=r&&typeof r=="object",p=u&&"agentDescription"in r?String(r.agentDescription):void 0,d=u&&"suggestedPrompts"in r&&Array.isArray(r.suggestedPrompts)?r.suggestedPrompts:void 0,c=u&&"tools"in r&&Array.isArray(r.tools)?r.tools:void 0,g=u&&"mcps"in r&&Array.isArray(r.mcps)?r.mcps:void 0,m=u&&"subagents"in r&&Array.isArray(r.subagents)?r.subagents:void 0,x=u&&"initialMessage"in r&&r.initialMessage&&typeof r.initialMessage=="object"?r.initialMessage:void 0,h=u&&"uiConfig"in r&&r.uiConfig&&typeof r.uiConfig=="object"?r.uiConfig:void 0;this.agentInfo={name:a.agentInfo.name,...a.agentInfo.title?{displayName:a.agentInfo.title}:{},version:a.agentInfo.version,...p?{description:p}:{},...d?{suggestedPrompts:d}:{},...x?{initialMessage:x}:{},...h?{uiConfig:h}:{},...c?{tools:c}:{},...g?{mcps:g}:{},...m?{subagents:m}:{}}}if(!a.agentCapabilities?.loadSession)throw z.error("Agent does not support loading sessions",{capabilities:a.agentCapabilities}),new Error("Agent does not support loading sessions");z.info("ACP connection initialized, loading session",{sessionId:s,capabilities:a.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=s,await this.connectSSE();const o={sessionId:s,cwd:"/",mcpServers:[]};z.info("Sending session/load request",{loadRequest:o});const i=await this.sendRpcRequest("session/load",o);z.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:i}),this.connected=!0,this.reconnectAttempts=0}catch(n){this.connected=!1;const a=n instanceof Error?n:new Error(String(n));throw z.error("Failed to load session",{sessionId:s,error:a.message,stack:a.stack}),this.notifyError(a),a}}async listSessions(){try{const s={method:"GET"};this.options.headers&&(s.headers=this.options.headers);const n=await fetch(`${this.options.baseUrl}/sessions`,s);if(!n.ok)throw new Error(`HTTP ${n.status}: ${await n.text()}`);return(await n.json()).sessions||[]}catch(s){return z.error("Failed to list sessions",{error:s}),[]}}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(s){const n=s instanceof Error?s:new Error(String(s));throw this.notifyError(n),n}}async send(s){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");this.isInReplayMode&&(z.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const n=s.content.map(r=>r.type==="text"?{type:"text",text:r.text}:r.type==="image"?"source"in r&&r.source?{type:"image",data:r.source.data,mimeType:r.source.media_type}:"data"in r&&"mimeType"in r?{type:"image",data:r.data,mimeType:r.mimeType}:r:r),a={sessionId:this.currentSessionId,prompt:n},o=await this.sendRpcRequest("session/prompt",a);z.debug("Prompt sent",{promptResponse:o}),this.streamComplete=!0;const i=this.chunkResolvers.shift();i?i({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(n){this.streamComplete=!0;const a=n instanceof Error?n:new Error(String(n));throw this.notifyError(a),a}}async*receive(){this.isReceivingMessages=!0;try{for(;!this.streamComplete;)if(this.messageQueue.length>0){const s=this.messageQueue.shift();if(s&&(yield s,s.type==="content"&&s.isComplete))return}else{const s=await new Promise(n=>{this.chunkResolvers.push(n)});if(s.type==="content"&&s.isComplete){yield s;return}else yield s}for(;this.messageQueue.length>0;){const s=this.messageQueue.shift();s&&(yield s)}yield{type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}finally{this.isReceivingMessages=!1}}isConnected(){return this.connected}onSessionUpdate(s){return this.sessionUpdateCallbacks.add(s),()=>{this.sessionUpdateCallbacks.delete(s)}}onError(s){return this.errorCallbacks.add(s),()=>{this.errorCallbacks.delete(s)}}getAgentInfo(){return this.agentInfo||{}}async sendRpcRequest(s,n){const o={jsonrpc:"2.0",id:this.generateRequestId(),method:s,params:n};z.debug("Sending RPC request",{method:s,params:n,request:o});const i={"Content-Type":"application/json",...this.options.headers},r=this.options.timeout??600*1e3,u=new AbortController,p=setTimeout(()=>u.abort(),r);try{const d=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(o),signal:u.signal});if(clearTimeout(p),!d.ok){const g=await d.text();throw new Error(`HTTP ${d.status}: ${g}`)}const c=await d.json();if(c.error)throw new Error(`ACP error: ${c.error.message||JSON.stringify(c.error)}`);return c.result||c}catch(d){throw clearTimeout(p),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${r}ms`):d}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const s=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const a=await fetch(s,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!a.ok)throw new Error(`SSE connection failed: HTTP ${a.status}`);if(!a.body)throw new Error("Response body is null");z.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const o=a.body.getReader(),i=new TextDecoder;let r="";(async()=>{try{for(;;){const{done:u,value:p}=await o.read();if(u){z.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}r+=i.decode(p,{stream:!0});const d=r.split(`
4
- `);r=d.pop()||"";let c={event:"message",data:""};for(const g of d)g.startsWith("event:")?c.event=g.substring(6).trim():g.startsWith("data:")?c.data=g.substring(5).trim():g===""&&(c.event==="message"&&c.data&&this.handleSSEMessage(c.data),c={event:"message",data:""})}}catch(u){if(u instanceof Error&&u.name==="AbortError"){z.debug("SSE stream aborted");return}z.error("Error reading SSE stream",{error:u}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(a){throw z.error("SSE connection error",{error:a}),a}}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 s=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);z.debug("SSE reconnecting",{delay:s,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(n=>setTimeout(n,s));try{await this.connectSSE(),z.info("SSE reconnected successfully"),this.reconnecting=!1}catch(n){z.error("SSE reconnection failed",{error:n}),this.reconnecting=!1}}handleSSEMessage(s){try{const n=JSON.parse(s);z.debug("Received SSE message",{message:n});const a=Wa.safeParse(n);if(!a.success){z.error("Invalid ACP message from SSE",{issues:a.error.issues});return}const o=a.data;z.debug("Parsed ACP message",{method:"method"in o?o.method:"(no method)"}),"method"in o&&o.method==="session/update"&&(z.debug("Received session/update notification"),"params"in o&&o.params&&(z.debug("Calling handleSessionNotification",{params:o.params}),this.handleSessionNotification(o.params)))}catch(n){z.error("Error parsing SSE message",{error:n}),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(s){z.debug("handleSessionNotification called",{params:s});const a=s.update,o=this.currentSessionId||s.sessionId;if(z.debug("Update session type",{sessionUpdate:a?.sessionUpdate}),a?.sessionUpdate==="tool_call"){z.debug("Tool call notification",{tokenUsage:a.tokenUsage});const i=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,r=a._meta&&typeof a._meta=="object"&&"prettyName"in a._meta&&typeof a._meta.prettyName=="string"?a._meta.prettyName:void 0,u=a._meta&&typeof a._meta=="object"&&"icon"in a._meta&&typeof a._meta.icon=="string"?a._meta.icon:void 0,p=a._meta&&typeof a._meta=="object"&&"subline"in a._meta&&typeof a._meta.subline=="string"?a._meta.subline:void 0,d=a._meta&&typeof a._meta=="object"&&"batchId"in a._meta&&typeof a._meta.batchId=="string"?a._meta.batchId:void 0,c=a._meta&&typeof a._meta=="object"&&"subagentPort"in a._meta&&typeof a._meta.subagentPort=="number"?a._meta.subagentPort:void 0,g=a._meta&&typeof a._meta=="object"&&"subagentSessionId"in a._meta&&typeof a._meta.subagentSessionId=="string"?a._meta.subagentSessionId:void 0,m=a._meta&&typeof a._meta=="object"&&"subagentMessages"in a._meta&&Array.isArray(a._meta.subagentMessages)?a._meta.subagentMessages:void 0,x={id:a.toolCallId??"",batchId:d,title:a.title??"",prettyName:r,icon:u,subline:p,kind:a.kind||"other",status:a.status||"pending",locations:a.locations,rawInput:a.rawInput,tokenUsage:a.tokenUsage,content:a.content?.map(v=>{if(typeof v!="object"||v===null)return{type:"text",text:""};const b=v;if(b.type==="content"&&typeof b.content=="object"&&b.content!==null){const j=b.content;if(j.type==="text")return{type:"content",content:{type:"text",text:typeof j.text=="string"?j.text:""}}}return b.type==="text"?{type:"text",text:typeof b.text=="string"?b.text:""}:b.type==="diff"?{type:"diff",path:typeof b.path=="string"?b.path:"",oldText:typeof b.oldText=="string"?b.oldText:"",newText:typeof b.newText=="string"?b.newText:"",line:typeof b.line=="number"?b.line:null}:b.type==="terminal"?{type:"terminal",terminalId:typeof b.terminalId=="string"?b.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now(),subagentPort:c,subagentSessionId:g,subagentMessages:m},h={type:"tool_call",sessionId:o,status:"active",toolCall:x,messageId:i},f=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0;if(z.info("Creating tool_call session update",{toolCallId:x.id,title:x.title,hasSubagentPort:!!c,hasSubagentSessionId:!!g,hasSubagentMessages:!!m,subagentMessagesCount:m?.length,isReplay:f,isInReplayMode:this.isInReplayMode}),f||this.isInReplayMode)this.notifySessionUpdate(h);else{const v={type:"tool_call",id:o,toolCall:x,messageId:i},b=this.chunkResolvers.shift();b?b(v):this.messageQueue.push(v)}}else if(a?.sessionUpdate==="tool_call_update"){const i=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,r=a._meta&&typeof a._meta=="object"&&"prettyName"in a._meta&&typeof a._meta.prettyName=="string"?a._meta.prettyName:void 0,u=a._meta&&typeof a._meta=="object"&&"icon"in a._meta&&typeof a._meta.icon=="string"?a._meta.icon:void 0,p=a._meta&&typeof a._meta=="object"&&"batchId"in a._meta&&typeof a._meta.batchId=="string"?a._meta.batchId:void 0,d=a._meta&&typeof a._meta=="object"&&"subagentPort"in a._meta&&typeof a._meta.subagentPort=="number"?a._meta.subagentPort:void 0,c=a._meta&&typeof a._meta=="object"&&"subagentSessionId"in a._meta&&typeof a._meta.subagentSessionId=="string"?a._meta.subagentSessionId:void 0,g=a._meta&&typeof a._meta=="object"&&"subagentMessages"in a._meta&&Array.isArray(a._meta.subagentMessages)?a._meta.subagentMessages:void 0;(d||c||g)&&z.info("Extracted subagent info from tool_call_update",{toolCallId:a.toolCallId,subagentPort:d,subagentSessionId:c,subagentMessagesCount:g?.length});const m={id:a.toolCallId??"",status:a.status,title:a.title,prettyName:r,icon:u,batchId:p,rawInput:a.rawInput,locations:a.locations,rawOutput:a.rawOutput,tokenUsage:a.tokenUsage,content:a.content?.map(h=>{if(typeof h!="object"||h===null)return{type:"text",text:""};const f=h;if(f.type==="content"&&typeof f.content=="object"&&f.content!==null){const v=f.content;if(v.type==="text")return{type:"content",content:{type:"text",text:typeof v.text=="string"?v.text:""}}}return f.type==="text"?{type:"text",text:typeof f.text=="string"?f.text:""}:f.type==="diff"?{type:"diff",path:typeof f.path=="string"?f.path:"",oldText:typeof f.oldText=="string"?f.oldText:"",newText:typeof f.newText=="string"?f.newText:"",line:typeof f.line=="number"?f.line:null}:f.type==="terminal"?{type:"terminal",terminalId:typeof f.terminalId=="string"?f.terminalId:""}:{type:"text",text:""}}),error:a.error,completedAt:a.status==="completed"||a.status==="failed"?Date.now():void 0,subagentPort:d,subagentSessionId:c,subagentMessages:g},x={type:"tool_call_update",sessionId:o,status:"active",toolCallUpdate:m,messageId:i};if(this.isInReplayMode)this.notifySessionUpdate(x);else{const h={type:"tool_call_update",id:o,toolCallUpdate:m,messageId:i},f=this.chunkResolvers.shift();f?f(h):this.messageQueue.push(h)}z.debug("Processed tool_call_update",{sessionUpdate:x,isReplay:this.isInReplayMode})}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="hook_notification"){const i=a;z.debug("Received hook_notification",{id:i.id,notificationType:i.notification.type,hookType:i.notification.hookType});const r={type:"hook_notification",id:i.id,notification:i.notification,messageId:i.messageId},u=this.chunkResolvers.shift();u?u(r):this.messageQueue.push(r)}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="tool_output"){const i=a,r=i._meta&&typeof i._meta=="object"&&"messageId"in i._meta?String(i._meta.messageId):void 0,u={id:i.toolCallId??"",rawOutput:i.rawOutput,content:i.content?.map(d=>{if(typeof d!="object"||d===null)return{type:"text",text:""};const c=d;if(c.type==="content"&&typeof c.content=="object"&&c.content!==null){const g=c.content;if(g.type==="text")return{type:"content",content:{type:"text",text:typeof g.text=="string"?g.text:""}}}return c.type==="text"?{type:"text",text:typeof c.text=="string"?c.text:""}:c.type==="diff"?{type:"diff",path:typeof c.path=="string"?c.path:"",oldText:typeof c.oldText=="string"?c.oldText:"",newText:typeof c.newText=="string"?c.newText:"",line:typeof c.line=="number"?c.line:null}:c.type==="terminal"?{type:"terminal",terminalId:typeof c.terminalId=="string"?c.terminalId:""}:c.type==="image"?{type:"image",data:typeof c.data=="string"?c.data:"",mimeType:typeof c.mimeType=="string"?c.mimeType:"image/png",alt:typeof c.alt=="string"?c.alt:void 0}:{type:"text",text:""}})},p={type:"tool_call_update",sessionId:o,status:"active",toolCallUpdate:u,messageId:r};if(this.isInReplayMode)this.notifySessionUpdate(p);else{const d={type:"tool_call_update",id:o,toolCallUpdate:u,messageId:r},c=this.chunkResolvers.shift();c?c(d):this.messageQueue.push(d)}z.debug("Queued tool_output as tool_call_update chunk",{sessionUpdate:p})}else if(a?.sessionUpdate==="agent_message_chunk"){const i=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0;if(this.isInReplayMode&&!i)return;const r=a._meta&&typeof a._meta=="object"&&"tokenUsage"in a._meta?a._meta.tokenUsage:void 0,u=a._meta&&typeof a._meta=="object"&&"contextInputTokens"in a._meta&&typeof a._meta.contextInputTokens=="number"?a._meta.contextInputTokens:void 0,p=a._meta&&typeof a._meta=="object"&&"context_size"in a._meta?a._meta.context_size:void 0,d={type:"generic",sessionId:o,status:"active",_meta:a._meta},c=a.content;if(c&&typeof c=="object"){const m=c;let x=null;if(m.type==="text"&&typeof m.text=="string"&&(x={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:m.text},tokenUsage:r,contextInputTokens:u,_meta:p?{context_size:p}:void 0,isComplete:!1}),x&&!i){const h=this.chunkResolvers.shift();h?h(x):this.messageQueue.push(x)}if(x&&typeof m.text=="string"&&(i||!this.isReceivingMessages)){const h={type:"generic",sessionId:o,status:"active",message:{id:`msg_${Date.now()}_assistant`,role:"assistant",content:[{type:"text",text:m.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(h)}}const g=d._meta&&"context_size"in d._meta;(!i||g)&&this.notifySessionUpdate(d)}else if(a?.sessionUpdate==="user_message_chunk"){z.debug("Received user_message_chunk",{update:a});const i=a.content;if(i&&typeof i=="object"){const r=i;if(r.type==="text"&&typeof r.text=="string"){const u={type:"generic",sessionId:o,status:"active",message:{id:`msg_${Date.now()}_user`,role:"user",content:[{type:"text",text:r.text}],timestamp:new Date().toISOString()}};z.debug("Notifying session update for user message"),this.notifySessionUpdate(u)}}}else{const i={type:"generic",sessionId:o,status:"active"};this.notifySessionUpdate(i)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(s){for(const n of this.sessionUpdateCallbacks)try{n(s)}catch(a){z.error("Error in session update callback",{error:a})}}notifyError(s){for(const n of this.errorCallbacks)try{n(s)}catch(a){z.error("Error in error callback",{error:a})}}}class $n{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 Fn{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(s){}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(s){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(s){return this.sessionUpdateCallbacks.add(s),()=>{this.sessionUpdateCallbacks.delete(s)}}onError(s){return this.errorCallbacks.add(s),()=>{this.errorCallbacks.delete(s)}}}const it=de("acp-client","debug");class Bn{constructor(s){this.config=s,this.transport=this.createTransport(),this.setupTransportListeners(),s.autoConnect&&this.connect().catch(n=>{it.error("Failed to auto-connect",{error:n instanceof Error?n.message:String(n)})})}transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(s){const n="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(n){const u=new Date().toISOString(),p=this.transport.getAgentInfo?.()?.name,d={id:n,status:"connected",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:u,agentName:p}};return this.sessions.set(n,d),this.currentSessionId=n,n}const a=this.generateSessionId(),o=new Date().toISOString(),i=this.transport.getAgentInfo?.()?.name,r={id:a,status:"connecting",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o,agentName:i}};return this.sessions.set(a,r),this.currentSessionId=a,this.updateSessionStatus(a,"connected"),a}async loadSession(s,n){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const a=new Date().toISOString(),o={id:s,status:"connecting",config:n?{...n,agentPath:n.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:a}};if(this.sessions.set(s,o),this.currentSessionId=s,await this.transport.loadSession(s),this.transport.getAgentInfo){const i=this.transport.getAgentInfo();i.name&&o.metadata&&(o.metadata.agentName=i.name)}return this.updateSessionStatus(s,"connected"),s}async listSessions(){return this.transport.listSessions?this.transport.listSessions():[]}async sendMessage(s,n,a){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 r=[];if(a&&a.length>0)for(const p of a)p.mimeType.startsWith("image/")&&r.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.data}});r.push({type:"text",text:s});const u={id:this.generateMessageId(),role:"user",content:r,timestamp:new Date().toISOString()};i.messages.push(u),this.updateSessionStatus(o,"active"),await this.transport.send(u)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(s){return this.sessions.get(s)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(s){return this.sessionUpdateHandlers.add(s),()=>{this.sessionUpdateHandlers.delete(s)}}onError(s){return this.errorHandlers.add(s),()=>{this.errorHandlers.delete(s)}}getAgentInfo(){return this.transport.getAgentInfo?.()||{}}createTransport(){switch(this.config.type){case"stdio":return new $n(this.config.options);case"http":return new zn(this.config.options);case"websocket":return new Fn(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(s=>{this.handleSessionUpdate(s)}),this.transport.onError(s=>{this.handleError(s)})}handleSessionUpdate(s){if(s.sessionId){const n=this.sessions.get(s.sessionId);n&&(s.status&&(n.status=s.status),s.message&&n.messages.push(s.message),s.error&&(n.error=s.error))}for(const n of this.sessionUpdateHandlers)try{n(s)}catch(a){it.error("Error in session update handler",{error:a instanceof Error?a.message:String(a)})}}handleError(s){for(const n of this.errorHandlers)try{n(s)}catch(a){it.error("Error in error handler",{error:a instanceof Error?a.message:String(a)})}}updateSessionStatus(s,n){const a=this.sessions.get(s);a&&(a.status=n,this.handleSessionUpdate({sessionId:s,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 we=de("acp-client-hook");function Hn(t){const[s,n]=l.useState(null),[a,o]=l.useState(null),[i,r]=l.useState(null);return l.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("session");p&&(we.info("Session ID found in URL",{sessionId:p}),r(p));try{we.info("Initializing ACP client",{serverUrl:t.serverUrl});const d=new Bn({type:"http",options:{baseUrl:t.serverUrl}});return n(d),we.info("ACP client initialized successfully"),()=>{we.debug("Disconnecting ACP client"),d.disconnect().catch(c=>{we.error("Failed to disconnect ACP client",{error:c instanceof Error?c.message:String(c)})})}}catch(d){const c=d instanceof Error?d.message:"Failed to initialize ACP client";o(c),we.error("Failed to initialize ACP client",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0});return}},[t.serverUrl]),{client:s,error:a,sessionId:i}}const yt=ne(["pending","in_progress","completed","failed"]),Wn=ne(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),Ss=D({path:w(),line:A().nullable().optional()}),vt=D({inputTokens:A().optional(),outputTokens:A().optional(),totalTokens:A().optional()}),wt=Me("type",[D({type:W("content"),content:D({type:W("text"),text:w()})}),D({type:W("text"),text:w()}),D({type:W("image"),data:w(),mimeType:w().optional(),alt:w().optional()}),D({type:W("image"),url:w(),alt:w().optional()}),D({type:W("diff"),path:w(),oldText:w(),newText:w(),line:A().nullable().optional()}),D({type:W("terminal"),terminalId:w()})]),ks=D({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),status:yt,content:q(wt).optional()}),Vn=Me("type",[D({type:W("text"),text:w()}),D({type:W("tool_call"),toolCall:ks})]),Cs=D({id:w(),content:w(),toolCalls:q(ks).optional(),contentBlocks:q(Vn).optional(),isStreaming:xe().optional()}),Ts=D({id:w(),batchId:w().optional(),title:w(),prettyName:w().optional(),icon:w().optional(),verbiage:D({active:w(),past:w(),paramKey:w().optional()}).optional(),subline:w().optional(),kind:Wn,status:yt,contentPosition:A().optional(),locations:q(Ss).optional(),rawInput:se(w(),ae()).optional(),rawOutput:se(w(),ae()).optional(),content:q(wt).optional(),error:w().optional(),startedAt:A().optional(),completedAt:A().optional(),tokenUsage:vt.optional(),_meta:D({truncationWarning:w().optional(),compactionAction:ne(["compacted","truncated"]).optional(),originalTokens:A().optional(),finalTokens:A().optional()}).optional(),subagentPort:A().optional(),subagentSessionId:w().optional(),subagentMessages:q(Cs).optional(),subagentStreaming:xe().optional()}),qn=D({id:w(),status:yt.optional(),title:w().optional(),prettyName:w().optional(),icon:w().optional(),batchId:w().optional(),rawInput:se(w(),ae()).optional(),locations:q(Ss).optional(),rawOutput:se(w(),ae()).optional(),content:q(wt).optional(),error:w().optional(),completedAt:A().optional(),tokenUsage:vt.optional(),subagentPort:A().optional(),subagentSessionId:w().optional(),subagentMessages:q(Cs).optional()});function Bt(t,s){return{...t,status:s.status??t.status,title:s.title??t.title,prettyName:s.prettyName??t.prettyName,icon:s.icon??t.icon,batchId:s.batchId??t.batchId,rawInput:s.rawInput??t.rawInput,locations:s.locations??t.locations,rawOutput:s.rawOutput??t.rawOutput,content:s.content?[...t.content??[],...s.content]:t.content,error:s.error??t.error,completedAt:s.completedAt??t.completedAt,tokenUsage:s.tokenUsage??t.tokenUsage,subagentPort:s.subagentPort??t.subagentPort,subagentSessionId:s.subagentSessionId??t.subagentSessionId,subagentMessages:s.subagentMessages??t.subagentMessages}}const ie=de("chat-store","debug"),Oe=[];function lt(t){const s={id:`hook_${Date.now()}_${t.hookType}_${t.callback}`,hookType:t.hookType,callback:t.callback,...t.toolCallId?{toolCallId:t.toolCallId}:{}};switch(t.type){case"hook_triggered":return{...s,status:"triggered",threshold:t.threshold,currentPercentage:t.currentPercentage,triggeredAt:t.triggeredAt??Date.now()};case"hook_completed":return{...s,status:"completed",metadata:t.metadata,completedAt:t.completedAt??Date.now()};case"hook_error":return{...s,status:"error",error:t.error,completedAt:t.completedAt??Date.now()}}}let Le={sessionId:null,toolCallId:null,todos:Oe};const Kn=t=>{const s=t.sessionId;if(!s)return Oe;const a=(t.toolCalls[s]||[]).filter(r=>r.title==="todo_write").sort((r,u)=>(u.startedAt||0)-(r.startedAt||0));if(a.length===0)return Oe;const o=a[0];if(!o?.rawInput?.todos||!Array.isArray(o.rawInput.todos))return Oe;if(Le.sessionId===s&&Le.toolCallId===o.id)return Le.todos;const i=o.rawInput.todos.map((r,u)=>({id:`${o.id}-${u}`,text:r.status==="in_progress"?r.activeForm:r.content,status:r.status}));return Le={sessionId:s,toolCallId:o.id,todos:i},i},P=La(t=>({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},latestContextSize:null,currentModel:"claude-sonnet-4-5-20250929",tokenDisplayMode:"context",logs:[],activeTab:"chat",input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:s=>t({connectionStatus:s}),setSessionId:s=>t({sessionId:s}),setError:s=>t({error:s}),addMessage:s=>t(n=>({messages:[...n.messages,s]})),updateMessage:(s,n)=>t(a=>{const o=a.messages.find(d=>d.id===s);let i=a.totalBilled,r=a.currentContext,u=n;if(n.tokenUsage){const d=o?.tokenUsage;ie.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:d});const c={inputTokens:Math.max(n.tokenUsage.inputTokens??0,d?.inputTokens??0),outputTokens:Math.max(n.tokenUsage.outputTokens??0,d?.outputTokens??0),totalTokens:Math.max(n.tokenUsage.inputTokens??0,d?.inputTokens??0)+Math.max(n.tokenUsage.outputTokens??0,d?.outputTokens??0)};ie.debug("updateMessage: merged tokenUsage",{merged:c}),u={...n,tokenUsage:c};const g=c.inputTokens-(d?.inputTokens??0),m=c.outputTokens-(d?.outputTokens??0),x=c.totalTokens-(d?.totalTokens??0);i={inputTokens:a.totalBilled.inputTokens+g,outputTokens:a.totalBilled.outputTokens+m,totalTokens:a.totalBilled.totalTokens+x},r={inputTokens:c.inputTokens,outputTokens:a.currentContext.outputTokens+m,totalTokens:c.totalTokens}}const p=a.messages.map(d=>d.id===s?{...d,...u}:d);if(n.tokenUsage&&u.tokenUsage){const d=o?.tokenUsage,c=u.tokenUsage,g=(c.inputTokens??0)-(d?.inputTokens??0),m=(c.outputTokens??0)-(d?.outputTokens??0),x=(c.totalTokens??0)-(d?.totalTokens??0),h=p.filter(b=>b.tokenUsage).map(b=>({id:b.id,role:b.role,tokens:b.tokenUsage})),f=p.reduce((b,j)=>({inputTokens:b.inputTokens+(j.tokenUsage?.inputTokens??0),outputTokens:b.outputTokens+(j.tokenUsage?.outputTokens??0),totalTokens:b.totalTokens+(j.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),v=f.inputTokens===i.inputTokens&&f.outputTokens===i.outputTokens&&f.totalTokens===i.totalTokens;ie.debug("updateMessage: tokenUsage update",{messageId:s,updates:n.tokenUsage,existing:d,messageMax:c,delta:{inputDelta:g,outputDelta:m,totalDelta:x},totalBilled:i,currentContext:r,actualSum:f,billedCorrect:v?"✅":"❌",messageCount:p.length,messagesWithTokens:h.length,breakdown:h})}return{messages:p,totalBilled:i,currentContext:r}}),clearMessages:()=>t({messages:[]}),setIsStreaming:s=>t({isStreaming:s}),setStreamingStartTime:s=>t({streamingStartTime:s}),addToolCall:(s,n)=>t(a=>({toolCalls:{...a.toolCalls,[s]:[...a.toolCalls[s]||[],n]}})),addToolCallToCurrentMessage:s=>t(n=>{const a=n.messages.findLastIndex(p=>p.role==="assistant");if(a===-1){ie.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:[{...s,contentPosition:0}]};return{messages:[...n.messages,p]}}const o=[...n.messages],i=o[a];if(!i)return n;const r=i.content.length,u={...s,contentPosition:r};return o[a]={...i,toolCalls:[...i.toolCalls||[],u]},{messages:o}}),updateToolCallInCurrentMessage:s=>t(n=>{const a=n.messages.findLastIndex(c=>c.role==="assistant");if(a===-1)return ie.warn("No assistant message found to update tool call in"),n;const o=[...n.messages],i=o[a];if(!i)return n;const r=i.toolCalls||[],u=r.findIndex(c=>c.id===s.id);if(u===-1)return ie.warn(`Tool call ${s.id} not found in message`),n;const p=r[u];if(!p)return n;const d=[...r];return d[u]=Bt(p,s),o[a]={...i,toolCalls:d},{messages:o}}),addHookNotificationToCurrentMessage:s=>t(n=>{const a=n.messages.findLastIndex(c=>c.role==="assistant");if(a===-1){ie.debug("No assistant message found, creating one for hook notification");const c={...lt(s),contentPosition:0},g={id:`msg_${Date.now()}_assistant`,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,hookNotifications:[c]};return{messages:[...n.messages,g]}}const o=[...n.messages],i=o[a];if(!i)return n;const r=i.hookNotifications||[],u=i.content.length;if(s.type==="hook_triggered"){ie.debug("Adding hook_triggered notification for loading state",{hookType:s.hookType,callback:s.callback,contentPosition:u});const c={...lt(s),contentPosition:u},g=[...r,c];return o[a]={...i,hookNotifications:g},{messages:o}}let p;const d=r.findIndex(c=>c.hookType===s.hookType&&c.callback===s.callback&&c.status==="triggered");if(d!==-1){const c=r[d];p=[...r];const g=s.type==="hook_completed"||s.type==="hook_error"?s.completedAt??Date.now():Date.now();p[d]={...c,status:s.type==="hook_completed"?"completed":"error",completedAt:g,...s.type==="hook_completed"&&s.metadata?{metadata:s.metadata}:{},...s.type==="hook_error"?{error:s.error}:{}},ie.debug("Merged hook notification with triggered state",{hookType:s.hookType,status:p[d]?.status})}else{const c={...lt(s),contentPosition:u};p=[...r,c],ie.debug("Added hook notification without prior triggered state",{hookType:s.hookType,callback:s.callback,contentPosition:u})}return o[a]={...i,hookNotifications:p},{messages:o}}),updateToolCall:(s,n)=>t(a=>{const o=a.toolCalls[s]||[],i=o.findIndex(p=>p.id===n.id);if(i===-1)return a;const r=o[i];if(!r)return a;const u=[...o];return u[i]=Bt(r,n),{toolCalls:{...a.toolCalls,[s]:u}}}),setInputValue:s=>t(n=>({input:{...n.input,value:s}})),setInputSubmitting:s=>t(n=>({input:{...n.input,isSubmitting:s}})),addFileAttachment:s=>t(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,s]}})),removeFileAttachment:s=>t(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((a,o)=>o!==s)}})),clearInput:()=>t(s=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}})),addTokenUsage:s=>t(n=>({totalBilled:{inputTokens:n.totalBilled.inputTokens+(s.inputTokens??0),outputTokens:n.totalBilled.outputTokens+(s.outputTokens??0),totalTokens:n.totalBilled.totalTokens+(s.totalTokens??0)},currentContext:{inputTokens:s.inputTokens??n.currentContext.inputTokens,outputTokens:n.currentContext.outputTokens+(s.outputTokens??0),totalTokens:(s.inputTokens??n.currentContext.inputTokens)+(n.currentContext.outputTokens+(s.outputTokens??0))}})),setLatestContextSize:s=>t({latestContextSize:s}),setCurrentModel:s=>t({currentModel:s}),resetTokens:()=>t({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}),cycleTokenDisplayMode:()=>t(s=>{const n=["context","input","output"],o=(n.indexOf(s.tokenDisplayMode)+1)%n.length,i=n[o];return i?{tokenDisplayMode:i}:s}),addLog:s=>t(n=>({logs:[...n.logs,s]})),clearLogs:()=>t({logs:[]}),setActiveTab:s=>t({activeTab:s})})),ee=de("use-chat-messages","debug");function Is(t,s){const n=P(b=>b.messages),a=P(b=>b.isStreaming),o=P(b=>b.sessionId),i=P(b=>b.setIsStreaming),r=P(b=>b.setStreamingStartTime),u=P(b=>b.addMessage),p=P(b=>b.updateMessage),d=P(b=>b.setError),c=P(b=>b.setLatestContextSize),g=P(b=>b.addToolCall),m=P(b=>b.updateToolCall),x=P(b=>b.addToolCallToCurrentMessage),h=P(b=>b.updateToolCallInCurrentMessage),f=P(b=>b.addHookNotificationToCurrentMessage),v=l.useCallback(async(b,j)=>{if(ee.debug("[sendMessage] Called with",{contentLength:b.length,attachmentsCount:j?.length||0,hasAttachments:!!j&&j.length>0}),!t){ee.error("No client available"),d("No client available");return}let N=o;if(!N){ee.info("Creating new session before sending first message");const C=await s();if(!C){ee.error("Failed to create session"),d("Failed to create session");return}N=C,ee.info("Session created successfully",{sessionId:C})}const R=`msg_${Date.now()}_assistant`;try{const C=Date.now();i(!0),r(C);const M={id:`msg_${Date.now()}_user`,role:"user",content:b,timestamp:new Date().toISOString(),isStreaming:!1,...j&&j.length>0?{images:j.filter(E=>E.mimeType.startsWith("image/")).map(E=>({mimeType:E.mimeType,data:E.data}))}:{}};u(M);const L={id:R,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:C};u(L);const O=t.receiveMessages();t.sendMessage(b,N,j).catch(E=>{const F=E instanceof Error?E.message:String(E);d(F),i(!1),r(null)});let U="",K=!1;for await(const E of O)if(E.type==="content"){const F=E._meta,H=F?.context_size||E.context_size;if(H!=null){const G=H;ee.info("✅ Received context_size from backend",{context_size:G,totalEstimated:G.totalEstimated,source:F?.context_size?"_meta":"direct"}),c(G)}else ee.debug("Chunk does not have context_size",{hasContextSize:"context_size"in E,hasMeta:"_meta"in E,metaKeys:F?Object.keys(F):null});if(E.tokenUsage&&ee.debug("Received tokenUsage from backend",{tokenUsage:E.tokenUsage}),E.isComplete){p(R,{content:U,isStreaming:!1,streamingStartTime:void 0,...E.tokenUsage?{tokenUsage:E.tokenUsage}:{}}),i(!1),r(null),K=!0;break}else E.contentDelta.type==="text"&&(U+=E.contentDelta.text,p(R,{content:U,...E.tokenUsage?{tokenUsage:E.tokenUsage}:{}}),await new Promise(G=>setTimeout(G,16)))}else E.type==="tool_call"?(ee.debug("Received tool_call chunk",{chunk:E}),g(N,E.toolCall),x(E.toolCall)):E.type==="tool_call_update"?(ee.debug("Received tool_call_update chunk",{chunk:E}),m(N,E.toolCallUpdate),h(E.toolCallUpdate)):E.type==="hook_notification"&&(ee.debug("Received hook_notification chunk",{chunk:E}),f(E.notification));K||(ee.warn("Stream ended without isComplete flag"),p(R,{isStreaming:!1,streamingStartTime:void 0}),i(!1),r(null))}catch(C){const M=C instanceof Error?C.message:String(C);d(M),i(!1),r(null),p(R,{isStreaming:!1,streamingStartTime:void 0})}},[t,o,s,u,p,i,r,d,c,g,m,x,h,f]);return{messages:n,isStreaming:a,sendMessage:v}}const Ht=de("use-chat-input","debug");function Gn(t,s){const n=P(m=>m.input),a=P(m=>m.setInputValue),o=P(m=>m.setInputSubmitting),i=P(m=>m.addFileAttachment),r=P(m=>m.removeFileAttachment),{sendMessage:u}=Is(t,s),p=l.useCallback(m=>{a(m)},[a]),d=l.useCallback(async()=>{if(!n.value.trim()||n.isSubmitting)return;const m=n.value,x=n.attachedFiles;Ht.debug("Submitting message with attachments",{messageLength:m.length,attachmentCount:x.length,hasAttachments:x.length>0}),a(""),o(!0);try{await u(m,x.length>0?x:void 0),P.setState(h=>({input:{...h.input,attachedFiles:[]}}))}catch(h){Ht.error("Failed to send message",{error:h instanceof Error?h.message:String(h)})}finally{o(!1)}},[n,a,o,u]),c=l.useCallback(m=>{i(m)},[i]),g=l.useCallback(m=>{r(m)},[r]);return{value:n.value,isSubmitting:n.isSubmitting,attachedFiles:n.attachedFiles,onChange:p,onSubmit:d,onAttachFile:c,onRemoveFile:g}}const pe=de("use-chat-session","debug");function Qn(t,s){const n=P(f=>f.connectionStatus),a=P(f=>f.sessionId),o=P(f=>f.setConnectionStatus),i=P(f=>f.setSessionId),r=P(f=>f.setError),u=P(f=>f.clearMessages),p=P(f=>f.resetTokens),d=P(f=>f.addMessage),c=P(f=>f.setLatestContextSize);l.useEffect(()=>t?t.onSessionUpdate(v=>{const b=v._meta,j=b?.context_size||v.context_size;if(j!=null){const N=j;pe.info("✅ Received context_size from session update",{context_size:N,totalEstimated:N.totalEstimated,isReplay:b?.isReplay}),c(N)}if(v.message&&(pe.debug("Session update with message",{message:v.message}),v.message.role!=="tool")){const N=v.message.content.map(L=>L.type==="text"?L.text:"").join(""),R=[];for(const L of v.message.content)if(L.type==="image"){const O=L;O.source?.data?R.push({mimeType:O.source.media_type||"image/png",data:O.source.data}):O.data&&R.push({mimeType:O.mimeType||"image/png",data:O.data})}const C=P.getState().messages,M=C[C.length-1];if(v.message.role==="assistant"&&M?.role==="assistant"&&M.content===""&&N)pe.debug("Appending text to existing assistant message"),P.getState().updateMessage(M.id,{content:M.content+N});else{const L={id:v.message.id,role:v.message.role,content:N,timestamp:v.message.timestamp,isStreaming:!1,...R.length>0?{images:R}:{}};d(L)}}}):void 0,[t,d,c]);const g=l.useCallback(async()=>{if(!t){r("No client available");return}try{o("connecting"),r(null),await t.connect();const f=t.getCurrentSession();if(f?.id&&(i(f.id),typeof window<"u")){const v=new URL(window.location.href);v.searchParams.set("session",f.id),window.history.replaceState({},"",v.toString())}o("connected")}catch(f){pe.error("Failed to connect",{error:f instanceof Error?f.message:String(f)});const v=f instanceof Error?f.message:String(f);r(v),o("error")}},[t,o,i,r]),m=l.useCallback(async f=>{if(!t){r("No client available");return}try{o("connecting"),r(null),u(),p();const v=await t.loadSession(f);i(v),o("connected"),pe.info("Session loaded successfully",{sessionId:v})}catch(v){pe.warn("Failed to load session, creating new one instead",{sessionId:f,error:v instanceof Error?v.message:String(v)});try{await g();const b=await t.startSession();if(i(b),u(),p(),typeof window<"u"){const j=new URL(window.location.href);j.searchParams.set("session",b),window.history.replaceState({},"",j.toString())}pe.info("Created new session after failed load",{sessionId:b})}catch(b){const j=b instanceof Error?b.message:String(b);r(`Failed to load or create session: ${j}`),o("error")}}},[t,o,i,r,u,p,g]),x=l.useCallback(async()=>{if(!t)return r("No client available"),null;try{const f=await t.startSession();if(i(f),P.getState().messages.length===0&&(u(),p()),typeof window<"u"){const b=new URL(window.location.href);b.searchParams.set("session",f),window.history.pushState({},"",b.toString())}return f}catch(f){const v=f instanceof Error?f.message:String(f);return r(v),null}},[t,i,r,u,p]),h=l.useCallback(async()=>{if(t)try{await t.disconnect(),o("disconnected"),i(null)}catch(f){const v=f instanceof Error?f.message:String(f);r(v)}},[t,o,i,r]);return l.useEffect(()=>{!t||n!=="disconnected"||(s?(pe.info("Loading initial session from URL",{sessionId:s}),m(s)):g())},[t,n,s,g,m]),{connectionStatus:n,sessionId:a,connect:g,loadSession:m,startSession:x,disconnect:h}}const Wt="town-message-history",Yn=100;function Xn(){const[t,s]=l.useState(-1),[n,a]=l.useState(""),o=l.useCallback(()=>{try{const c=localStorage.getItem(Wt);return c?JSON.parse(c):[]}catch{return[]}},[]),i=l.useCallback(c=>{const g=c.trim();if(g){try{const m=o();if(m[0]===g)return;const x=[g,...m].slice(0,Yn);localStorage.setItem(Wt,JSON.stringify(x))}catch{}s(-1),a("")}},[o]),r=l.useCallback(c=>{const g=o();if(g.length===0)return null;t===-1&&a(c);const m=Math.min(t+1,g.length-1);if(m===t)return null;const x=g[m];return x===void 0?null:(s(m),x)},[t,o]),u=l.useCallback(()=>{if(t===-1)return null;const c=o();if(t===0){s(-1);const x=n;return a(""),x}const g=t-1,m=c[g];return m===void 0?null:(s(g),m)},[t,n,o]),p=l.useCallback(()=>{t!==-1&&(s(-1),a(""))},[t]);return{addToHistory:i,navigatePrevious:r,navigateNext:u,resetNavigation:p,isBrowsingHistory:t!==-1,historyIndex:t}}const re=de("subagent-stream");function Jn(t){const[s,n]=l.useState([]),[a,o]=l.useState(!!t),[i,r]=l.useState(!1),[u,p]=l.useState(null),d=l.useRef(null),c=l.useRef(null),g=l.useRef(null),m=l.useCallback(()=>{g.current||(g.current=setTimeout(()=>{g.current=null,c.current&&n([{...c.current}])},250))},[]),x=l.useCallback(v=>{try{const b=JSON.parse(v);if(re.debug("Processing SSE message",{method:b.method,hasParams:!!b.params}),b.method==="session/update"&&b.params?.update){const j=b.params.update;if(re.debug("Got session update",{sessionUpdate:j.sessionUpdate}),j.sessionUpdate==="agent_message_chunk"){const N=j.content;if(N?.type==="text"&&typeof N.text=="string"&&c.current){c.current.content+=N.text;const R=c.current.contentBlocks??[],C=R[R.length-1];C&&C.type==="text"?C.text+=N.text:R.push({type:"text",text:N.text}),c.current.contentBlocks=R,m()}}else if(j.sessionUpdate==="tool_call"){const N={id:j.toolCallId??`tc-${Date.now()}`,title:j.title??"Tool call",prettyName:j._meta?.prettyName,icon:j._meta?.icon,status:j.status??"pending",content:[]};if(c.current){c.current.toolCalls=[...c.current.toolCalls??[],N];const R=c.current.contentBlocks??[];R.push({type:"tool_call",toolCall:N}),c.current.contentBlocks=R,m()}}else if(j.sessionUpdate==="tool_call_update"&&c.current?.toolCalls){const N=j.toolCallId,R=C=>C.id===N?{...C,status:j.status??C.status,content:j.content??C.content}:C;c.current.toolCalls=c.current.toolCalls.map(R),c.current.contentBlocks&&(c.current.contentBlocks=c.current.contentBlocks.map(C=>C.type==="tool_call"?{...C,toolCall:R(C.toolCall)}:C)),m()}}}catch(b){re.error("Failed to parse sub-agent SSE message",{error:b instanceof Error?b.message:String(b)})}},[m]),h=l.useCallback(async(v,b,j)=>{const N=`http://${j}:${v}`;re.info("Connecting to sub-agent SSE",{baseUrl:N,sessionId:b}),o(!0),p(null);const R=new AbortController;d.current=R;try{re.info("Fetching SSE endpoint",{url:`${N}/events`,sessionId:b});const C=await fetch(`${N}/events`,{method:"GET",headers:{"X-Session-ID":b},signal:R.signal});if(re.info("SSE response received",{status:C.status,ok:C.ok}),!C.ok)throw new Error(`SSE connection failed: HTTP ${C.status}`);if(!C.body)throw new Error("Response body is null");re.info("Sub-agent SSE connection opened, starting to read stream");const M=C.body.getReader(),L=new TextDecoder;let O="";for(c.current={id:`subagent-${Date.now()}`,content:"",toolCalls:[],contentBlocks:[],isStreaming:!0},n([c.current]);;){const{done:U,value:K}=await M.read();if(U){re.debug("Sub-agent SSE stream closed");break}O+=L.decode(K,{stream:!0});const E=O.split(`
5
- `);O=E.pop()||"";let F={event:"message",data:""};for(const H of E)H.startsWith("event:")?F.event=H.substring(6).trim():H.startsWith("data:")?F.data=H.substring(5).trim():H===""&&(F.event==="message"&&F.data&&x(F.data),F={event:"message",data:""})}}catch(C){if(C instanceof Error&&C.name==="AbortError")re.debug("Sub-agent SSE stream aborted");else{const M=C instanceof Error?C.message:"Failed to connect to sub-agent";re.error("Sub-agent SSE error",{error:M}),p(M)}}finally{c.current&&(c.current.isStreaming=!1,n(C=>C.map(M=>M.id===c.current?.id?{...M,isStreaming:!1}:M))),r(!0),o(!1),d.current=null,re.debug("Sub-agent stream completed")}},[x]);return l.useEffect(()=>{if(!t)return;const{port:v,sessionId:b,host:j="localhost"}=t;if(!(!v||!b))return n([]),p(null),r(!1),o(!0),h(v,b,j),()=>{d.current&&(d.current.abort(),d.current=null),g.current&&(clearTimeout(g.current),g.current=null)}},[t?.port,t?.sessionId,t?.host,h]),{messages:s,isStreaming:!i,error:u}}function Zn(t){const s=P(r=>r.toolCalls),n=P(r=>r.addToolCall),a=P(r=>r.updateToolCall),o=P(r=>r.addToolCallToCurrentMessage),i=P(r=>r.updateToolCallInCurrentMessage);return l.useEffect(()=>{if(!t)return;const r=t.onSessionUpdate(u=>{u.type==="tool_call"?(n(u.sessionId,u.toolCall),o(u.toolCall)):u.type==="tool_call_update"&&(a(u.sessionId,u.toolCallUpdate),i(u.toolCallUpdate))});return()=>{r()}},[t,n,a,o,i]),{toolCalls:s,getToolCallsForSession:r=>{const u=s[r];return u&&u.length>0?u:Object.values(s).flat()}}}const _s=ne(["user","assistant","system","tool"]),eo=ne(["text","image","file","tool_call","tool_result"]),Ae=D({type:eo}),to=Ae.extend({type:W("text"),text:w()}),so=Ae.extend({type:W("image"),url:w().url().optional(),source:D({type:W("base64"),media_type:ne(["image/jpeg","image/png","image/gif","image/webp"]),data:w()}).optional()}),ao=Ae.extend({type:W("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:A().optional()}),no=Ae.extend({type:W("tool_call"),id:w(),name:w(),arguments:se(w(),ae())}),oo=Ae.extend({type:W("tool_result"),callId:w(),result:ae(),error:w().optional()}),Rs=Me("type",[to,so,ao,no,oo]),Es=D({id:w(),role:_s,content:q(Rs),timestamp:Fe(),metadata:se(w(),ae()).optional()}),ro=D({type:W("content"),id:w(),role:_s,contentDelta:Rs,isComplete:xe(),tokenUsage:D({inputTokens:A().optional(),outputTokens:A().optional(),totalTokens:A().optional()}).optional(),contextInputTokens:A().optional(),_meta:D({context_size:D({systemPromptTokens:A(),userMessagesTokens:A(),assistantMessagesTokens:A(),toolInputTokens:A(),toolResultsTokens:A(),totalEstimated:A(),llmReportedInputTokens:A().optional()}).optional()}).optional()}),io=D({type:W("tool_call"),id:w(),toolCall:ft(),messageId:w().optional()}),lo=D({type:W("tool_call_update"),id:w(),toolCallUpdate:ft(),messageId:w().optional()}),Xe=ne(["context_size","tool_response"]),co=D({type:W("hook_triggered"),hookType:Xe,threshold:A(),currentPercentage:A(),callback:w(),triggeredAt:A().optional(),toolCallId:w().optional()}),uo=D({type:W("hook_completed"),hookType:Xe,callback:w(),metadata:D({action:w().optional(),messagesRemoved:A().optional(),tokensSaved:A().optional()}).passthrough().optional(),completedAt:A().optional(),toolCallId:w().optional()}),po=D({type:W("hook_error"),hookType:Xe,callback:w(),error:w(),completedAt:A().optional(),toolCallId:w().optional()}),mo=Me("type",[co,uo,po]),fo=D({type:W("hook_notification"),id:w(),notification:mo,messageId:w().optional()});Me("type",[ro,io,lo,fo]);const go=D({mimeType:w(),data:w()}),ho=D({id:w(),hookType:Xe,callback:w(),status:ne(["triggered","completed","error"]),threshold:A().optional(),currentPercentage:A().optional(),metadata:D({action:w().optional(),messagesRemoved:A().optional(),tokensSaved:A().optional(),tokensBeforeCompaction:A().optional(),summaryTokens:A().optional(),originalTokens:A().optional(),finalTokens:A().optional(),truncationWarning:w().optional()}).passthrough().optional(),error:w().optional(),triggeredAt:A().optional(),completedAt:A().optional(),contentPosition:A().optional(),toolCallId:w().optional()}),xo=D({id:w(),role:ne(["user","assistant","system"]),content:w(),timestamp:Fe(),isStreaming:xe().default(!1),streamingStartTime:A().optional(),metadata:se(w(),ae()).optional(),toolCalls:q(Ts).optional(),hookNotifications:q(ho).optional(),tokenUsage:vt.optional(),images:q(go).optional()}),bo=D({value:w(),isSubmitting:xe(),attachedFiles:q(D({name:w(),path:w(),size:A(),mimeType:w(),data:w()}))});D({sessionId:w().nullable(),isConnected:xe(),isStreaming:xe(),messages:q(xo),input:bo,error:w().nullable()});ne(["disconnected","connecting","connected","error"]);const yo=D({name:w(),description:w().optional(),parameters:se(w(),ae()).optional()}),vo=D({name:w(),description:w(),parameters:se(w(),ae()),required:q(w()).optional()}),wo=D({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:q(yo).optional(),tools:q(vo).optional(),supportedFormats:q(w()).optional()}),jo=ne(["initializing","ready","busy","error","terminated"]);D({status:jo,info:wo.optional(),pid:A().optional(),error:w().optional(),uptime:A().optional()});const Ms=ne(["idle","connecting","connected","active","streaming","error","disconnected"]),No=D({agentPath:w(),agentArgs:q(w()).optional(),environment:se(w(),w()).optional(),workingDirectory:w().optional(),timeout:A().optional()}),So=D({agentName:w().optional(),agentVersion:w().optional(),capabilities:q(w()).optional(),startedAt:Fe(),lastActivityAt:Fe().optional()});D({id:w(),status:Ms,config:No,metadata:So.optional(),messages:q(Es),error:w().optional()});const Je=D({sessionId:w(),status:Ms.optional(),message:Es.optional(),error:w().optional(),_meta:se(w(),ae()).optional()}),ko=Je.extend({type:W("tool_call"),toolCall:Ts,messageId:w().optional()}),Co=Je.extend({type:W("tool_call_update"),toolCallUpdate:qn,messageId:w().optional()}),To=Je.extend({type:W("tool_output"),toolOutput:D({id:w(),content:q(ft()).optional(),rawOutput:se(w(),ae()).optional()}),messageId:w().optional()}),Io=Je.extend({type:W("generic").optional()});Oa([ko,Co,To,Io]);const _o=[{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 Ro{data;constructor(s=_o){this.data=s}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(s){const n=o=>{for(const i of o){if(i.id===s)return i;if(i.children){const r=n(i.children);if(r)return r}}},a=n(this.data);return Promise.resolve(a?.children||[])}async getItemDetails(s){const n=o=>{for(const i of o){if(i.id===s)return i;if(i.children){const r=n(i.children);if(r)return r}}},a=n(this.data);if(!a)throw new Error(`Item with id ${s} not found`);return Promise.resolve(a)}}const Eo=[{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"}];function y(...t){return za($a(t))}const Mo=ue("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"}}),fe=l.forwardRef(({className:t,variant:s,size:n,asChild:a=!1,...o},i)=>{const r=a?ce:"button";return e.jsx(r,{className:y(Mo({variant:s,size:n,className:t})),ref:i,...o})});fe.displayName="Button";const be=l.forwardRef(({className:t,...s},n)=>e.jsx(fe,{ref:n,variant:"ghost",size:"icon",className:y("rounded-full",t),...s}));be.displayName="IconButton";const jt=qa,Nt=Ka,Ao=l.forwardRef(({className:t,inset:s,children:n,...a},o)=>e.jsxs(Qt,{ref:o,className:y("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",s&&"pl-8",t),...a,children:[n,e.jsx(_e,{className:"ml-auto h-4 w-4"})]}));Ao.displayName=Qt.displayName;const Do=l.forwardRef(({className:t,...s},n)=>e.jsx(Yt,{ref:n,className:y("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",t),...s}));Do.displayName=Yt.displayName;const Ze=l.forwardRef(({className:t,sideOffset:s=4,...n},a)=>e.jsx(Va,{children:e.jsx(Xt,{ref:a,sideOffset:s,className:y("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",t),...n})}));Ze.displayName=Xt.displayName;const le=l.forwardRef(({className:t,inset:s,...n},a)=>e.jsx(Jt,{ref:a,className:y("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",s&&"pl-8",t),...n}));le.displayName=Jt.displayName;const Po=l.forwardRef(({className:t,children:s,...n},a)=>e.jsxs(Zt,{ref:a,className:y("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",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(es,{children:e.jsx(bs,{className:"h-4 w-4"})})}),s]}));Po.displayName=Zt.displayName;const Uo=l.forwardRef(({className:t,children:s,...n},a)=>e.jsxs(ts,{ref:a,className:y("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",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(es,{children:e.jsx(Ge,{className:"h-2 w-2 fill-current"})})}),s]}));Uo.displayName=ts.displayName;const Lo=l.forwardRef(({className:t,inset:s,...n},a)=>e.jsx(ss,{ref:a,className:y("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...n}));Lo.displayName=ss.displayName;const St=l.forwardRef(({className:t,...s},n)=>e.jsx(as,{ref:n,className:y("-mx-1 my-1 h-px bg-border",t),...s}));St.displayName=as.displayName;const ct=768;function Oo(){const[t,s]=l.useState(void 0);return l.useEffect(()=>{const n=window.matchMedia(`(max-width: ${ct-1}px)`),a=()=>{s(window.innerWidth<ct)};return n.addEventListener("change",a),s(window.innerWidth<ct),()=>n.removeEventListener("change",a)},[]),!!t}const zo=ue("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"}}),As=l.forwardRef(({className:t,type:s,variant:n,...a},o)=>e.jsx("input",{type:s,className:y(zo({variant:n,className:t})),ref:o,...a}));As.displayName="Input";const $o=Ga,Fo=ns,Ds=l.forwardRef(({className:t,...s},n)=>e.jsx(We,{className:y("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",t),...s,ref:n}));Ds.displayName=We.displayName;const Bo=ue("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Ps=l.forwardRef(({side:t="right",className:s,children:n,...a},o)=>e.jsxs(Fo,{children:[e.jsx(Ds,{}),e.jsxs(Ve,{ref:o,className:y(Bo({side:t}),s),...a,children:[n,e.jsxs(os,{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-secondary",children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ps.displayName=Ve.displayName;const Us=({className:t,...s})=>e.jsx("div",{className:y("flex flex-col space-y-2 text-center sm:text-left",t),...s});Us.displayName="SheetHeader";const Ls=l.forwardRef(({className:t,...s},n)=>e.jsx(qe,{ref:n,className:y("text-lg font-semibold text-foreground",t),...s}));Ls.displayName=qe.displayName;const Os=l.forwardRef(({className:t,...s},n)=>e.jsx(Ke,{ref:n,className:y("text-sm text-muted-foreground",t),...s}));Os.displayName=Ke.displayName;const kt=Qa,Ct=Ya,Tt=Xa,et=l.forwardRef(({className:t,sideOffset:s=4,...n},a)=>e.jsx(rs,{ref:a,sideOffset:s,className:y("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",t),...n}));et.displayName=rs.displayName;const Ho="sidebar_state",Wo=3600*24*7,Vo="16rem",qo="18rem",Ko="3rem",Go="s",zs=l.createContext(null);function ye(){const t=l.useContext(zs);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const $s=l.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:n,className:a,style:o,children:i,...r},u)=>{const p=Oo(),[d,c]=l.useState(!1),[g,m]=l.useState(t),x=s??g,h=l.useCallback(j=>{const N=typeof j=="function"?j(x):j;n?n(N):m(N),document.cookie=`${Ho}=${N}; path=/; max-age=${Wo}`},[n,x]),f=l.useCallback(()=>p?c(j=>!j):h(j=>!j),[p,h,c]);l.useEffect(()=>{const j=N=>{N.key.toLowerCase()===Go&&N.shiftKey&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),f())};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[f]);const v=x?"expanded":"collapsed",b=l.useMemo(()=>({state:v,open:x,setOpen:h,isMobile:p,openMobile:d,setOpenMobile:c,toggleSidebar:f}),[v,x,h,p,d,c,f]);return e.jsx(zs.Provider,{value:b,children:e.jsx(kt,{delayDuration:0,children:e.jsx("div",{className:y("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",a),ref:u,style:{"--sidebar-width":Vo,"--sidebar-width-icon":Ko,...o},...r,children:i})})})});$s.displayName="SidebarProvider";const Fs=l.forwardRef(({side:t="left",variant:s="sidebar",collapsible:n="offcanvas",className:a,children:o,...i},r)=>{const{isMobile:u,state:p,openMobile:d,setOpenMobile:c}=ye();return n==="none"?e.jsx("div",{className:y("flex h-full w-[var(--sidebar-width)] flex-col bg-sidebar text-sidebar-foreground",a),ref:r,...i,children:o}):u?e.jsx($o,{onOpenChange:c,open:d,...i,children:e.jsxs(Ps,{className:"w-[var(--sidebar-width)] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden","data-mobile":"true","data-sidebar":"sidebar",side:t,style:{"--sidebar-width":qo},children:[e.jsxs(Us,{className:"sr-only",children:[e.jsx(Ls,{children:"Sidebar"}),e.jsx(Os,{children:"Displays the mobile sidebar."})]}),e.jsx("div",{className:"flex h-full w-full flex-col",children:o})]})}):e.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-collapsible":p==="collapsed"?n:"","data-side":t,"data-state":p,"data-variant":s,ref:r,children:[e.jsx("div",{className:y("relative w-[var(--sidebar-width)] bg-transparent transition-[width] duration-150 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",s==="floating"||s==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)]")}),e.jsx("div",{className:y("fixed inset-y-0 z-10 hidden h-svh w-[var(--sidebar-width)] transition-[left,right,width] duration-150 ease-linear md:flex",t==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",s==="floating"||s==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)] group-data-[side=left]:border-r group-data-[side=right]:border-l",a),...i,children:e.jsx("div",{className:"flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow","data-sidebar":"sidebar",children:o})})]})});Fs.displayName="Sidebar";const Qo=l.forwardRef(({className:t,onClick:s,...n},a)=>{const{toggleSidebar:o}=ye();return e.jsxs(fe,{className:y("h-7 w-7",t),"data-sidebar":"trigger",onClick:i=>{s?.(i),o()},ref:a,size:"icon",variant:"ghost",...n,children:[e.jsx(nn,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Qo.displayName="SidebarTrigger";const Yo=l.forwardRef(({className:t,...s},n)=>{const{toggleSidebar:a}=ye();return e.jsx("button",{type:"button","aria-label":"Toggle Sidebar",className:y("-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:hover:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),"data-sidebar":"rail",onClick:a,ref:n,tabIndex:-1,title:"Toggle Sidebar",...s})});Yo.displayName="SidebarRail";const Bs=l.forwardRef(({className:t,...s},n)=>e.jsx("main",{className:y("relative flex w-full flex-1 flex-col bg-background","md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",t),ref:n,...s}));Bs.displayName="SidebarInset";const Xo=l.forwardRef(({className:t,...s},n)=>e.jsx(As,{className:y("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),"data-sidebar":"input",ref:n,...s}));Xo.displayName="SidebarInput";const Hs=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex flex-col gap-2 p-2",t),"data-sidebar":"header",ref:n,...s}));Hs.displayName="SidebarHeader";const Ws=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex flex-col gap-2 p-2",t),"data-sidebar":"footer",ref:n,...s}));Ws.displayName="SidebarFooter";const Jo=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("mx-2 h-px w-auto bg-sidebar-border",t),"data-sidebar":"separator",ref:n,...s}));Jo.displayName="SidebarSeparator";const Vs=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),"data-sidebar":"content",ref:n,...s}));Vs.displayName="SidebarContent";const Ce=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("relative flex w-full min-w-0 flex-col p-2",t),"data-sidebar":"group",ref:n,...s}));Ce.displayName="SidebarGroup";const qs=l.forwardRef(({className:t,asChild:s=!1,...n},a)=>{const o=s?ce:"div";return e.jsx(o,{className:y("flex h-8 shrink-0 items-center rounded-md px-2 font-medium text-sidebar-foreground/70 text-xs outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),"data-sidebar":"group-label",ref:a,...n})});qs.displayName="SidebarGroupLabel";const Zo=l.forwardRef(({className:t,asChild:s=!1,...n},a)=>{const o=s?ce:"button";return e.jsx(o,{className:y("absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"group-action",ref:a,type:"button",...n})});Zo.displayName="SidebarGroupAction";const Te=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("w-full text-sm",t),"data-sidebar":"group-content",ref:n,...s}));Te.displayName="SidebarGroupContent";const Ks=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:y("flex w-full min-w-0 flex-col gap-1",t),"data-sidebar":"menu",ref:n,...s}));Ks.displayName="SidebarMenu";const Gs=l.forwardRef(({className:t,...s},n)=>e.jsx("li",{className:y("group/menu-item relative",t),"data-sidebar":"menu-item",ref:n,...s}));Gs.displayName="SidebarMenuItem";const er=ue("peer/menu-button group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"group-data-[collapsible=icon]:!p-0 h-12 text-sm"}},defaultVariants:{variant:"default",size:"default"}}),Qs=l.forwardRef(({asChild:t=!1,isActive:s=!1,variant:n="default",size:a="default",tooltip:o,className:i,...r},u)=>{const p=t?ce:"button",{isMobile:d,state:c}=ye(),g=e.jsx(p,{className:y(er({variant:n,size:a}),i),"data-active":s,"data-sidebar":"menu-button","data-size":a,ref:u,type:t?void 0:"button",...r});return o?(typeof o=="string"&&(o={children:o}),e.jsxs(Ct,{children:[e.jsx(Tt,{asChild:!0,children:g}),e.jsx(et,{align:"center",hidden:c!=="collapsed"||d,side:"right",...o})]})):g});Qs.displayName="SidebarMenuButton";const Ys=l.forwardRef(({className:t,asChild:s=!1,showOnHover:n=!1,...a},o)=>{const i=s?ce:"button";return e.jsx(i,{className:y("absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",n&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",t),"data-sidebar":"menu-action",ref:o,type:s?void 0:"button",...a})});Ys.displayName="SidebarMenuAction";const tr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 font-medium text-sidebar-foreground text-xs tabular-nums","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-badge",ref:n,...s}));tr.displayName="SidebarMenuBadge";const sr=l.forwardRef(({className:t,showIcon:s=!1,...n},a)=>{const o=l.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{className:y("flex h-8 items-center gap-2 rounded-md px-2",t),"data-sidebar":"menu-skeleton",ref:a,...n,children:[s&&e.jsx("div",{className:"size-4 rounded-md bg-sidebar-accent-foreground/10 animate-pulse","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 rounded-md bg-sidebar-accent-foreground/10 animate-pulse","data-sidebar":"menu-skeleton-text",style:{maxWidth:o}})]})});sr.displayName="SidebarMenuSkeleton";const ar=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:y("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-sub",ref:n,...s}));ar.displayName="SidebarMenuSub";const nr=l.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));nr.displayName="SidebarMenuSubItem";const or=l.forwardRef(({asChild:t=!1,size:s="md",isActive:n,className:a,...o},i)=>{const r=t?ce:"a";return e.jsx(r,{className:y("-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",s==="sm"&&"text-xs",s==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",a),"data-active":n,"data-sidebar":"menu-sub-button","data-size":s,ref:i,...o})});or.displayName="SidebarMenuSubButton";const rr=({session:t,isActive:s,onSelect:n,onRename:a,onArchive:o,onDelete:i,setOpenMobile:r})=>e.jsxs(Gs,{children:[e.jsx(Qs,{asChild:!0,isActive:s,onClick:()=>{n(t.sessionId),r(!1)},children:e.jsx("button",{type:"button",className:"w-full",children:e.jsx("span",{className:"truncate",children:t.firstUserMessage||"Empty session"})})}),e.jsxs(jt,{modal:!0,children:[e.jsx(Nt,{asChild:!0,children:e.jsxs(Ys,{className:"mr-0.5 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",showOnHover:!s,children:[e.jsx(on,{}),e.jsx("span",{className:"sr-only",children:"More"})]})}),e.jsxs(Ze,{align:"end",side:"bottom",children:[e.jsx(le,{className:"cursor-pointer",disabled:!a,onSelect:()=>a?.(t.sessionId),children:"Rename"}),e.jsx(le,{className:"cursor-pointer",disabled:!o,onSelect:()=>o?.(t.sessionId),children:"Archive"}),e.jsx(St,{}),e.jsx(le,{className:y("cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive"),disabled:!i,onSelect:()=>i?.(t.sessionId),children:"Delete"})]})]})]}),Se=l.memo(rr,(t,s)=>!(t.isActive!==s.isActive||t.session.sessionId!==s.session.sessionId||t.session.firstUserMessage!==s.session.firstUserMessage)),ir=de("session-history"),lr=t=>{const s=new Date;return t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},cr=t=>{const s=new Date;return s.setDate(s.getDate()-1),t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},dr=t=>{const s=new Date,n=new Date(s.getTime()-10080*60*1e3),a=new Date(s.getTime()-720*60*60*1e3);return t.reduce((o,i)=>{const r=new Date(i.updatedAt);return lr(r)?o.today.push(i):cr(r)?o.yesterday.push(i):r>n?o.lastWeek.push(i):r>a?o.lastMonth.push(i):o.older.push(i),o},{today:[],yesterday:[],lastWeek:[],lastMonth:[],older:[]})};function ur({client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:a,onArchiveSession:o,onDeleteSession:i}){const{setOpenMobile:r}=ye(),[u,p]=l.useState([]),[d,c]=l.useState(!1),g=l.useCallback(async()=>{if(t){c(!0);try{const h=await t.listSessions();p(h)}catch(h){ir.error("Failed to fetch sessions",{error:h})}finally{c(!1)}}},[t]);l.useEffect(()=>{g()},[g]);const m=h=>{if(h!==s)if(n)n(h);else{const f=new URL(window.location.href);f.searchParams.set("session",h),window.location.href=f.toString()}};if(!t)return e.jsx(Ce,{children:e.jsx(Te,{children:e.jsx("div",{className:"flex w-full flex-row items-center justify-center gap-2 px-2 text-sm text-muted-foreground",children:"Connect to an agent to see session history"})})});if(d)return e.jsxs(Ce,{children:[e.jsx(qs,{children:"Today"}),e.jsx(Te,{children:e.jsx("div",{className:"flex flex-col",children:[44,32,28,64,52].map(h=>e.jsx("div",{className:"flex h-8 items-center gap-2 rounded-md px-2",children:e.jsx("div",{className:"h-4 flex-1 rounded-md bg-sidebar-accent-foreground/10 animate-pulse",style:{maxWidth:`${h}%`}})},h))})})]});if(u.length===0)return e.jsx(Ce,{children:e.jsx(Te,{children:e.jsx("div",{className:"flex w-full flex-row items-center justify-center gap-2 px-2 py-4 text-sm text-muted-foreground",children:"Your sessions will appear here once you start chatting!"})})});const x=dr(u);return e.jsx(Ce,{children:e.jsx(Te,{children:e.jsx(Ks,{children:e.jsxs("div",{className:"flex flex-col gap-6",children:[x.today.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-sidebar-foreground/50 text-xs",children:"Today"}),x.today.map(h=>e.jsx(Se,{session:h,isActive:h.sessionId===s,onSelect:m,onRename:a,onArchive:o,onDelete:i,setOpenMobile:r},h.sessionId))]}),x.yesterday.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-sidebar-foreground/50 text-xs",children:"Yesterday"}),x.yesterday.map(h=>e.jsx(Se,{session:h,isActive:h.sessionId===s,onSelect:m,onRename:a,onArchive:o,onDelete:i,setOpenMobile:r},h.sessionId))]}),x.lastWeek.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-sidebar-foreground/50 text-xs",children:"Last 7 days"}),x.lastWeek.map(h=>e.jsx(Se,{session:h,isActive:h.sessionId===s,onSelect:m,onRename:a,onArchive:o,onDelete:i,setOpenMobile:r},h.sessionId))]}),x.lastMonth.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-sidebar-foreground/50 text-xs",children:"Last 30 days"}),x.lastMonth.map(h=>e.jsx(Se,{session:h,isActive:h.sessionId===s,onSelect:m,onRename:a,onArchive:o,onDelete:i,setOpenMobile:r},h.sessionId))]}),x.older.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-sidebar-foreground/50 text-xs",children:"Older"}),x.older.map(h=>e.jsx(Se,{session:h,isActive:h.sessionId===s,onSelect:m,onRename:a,onArchive:o,onDelete:i,setOpenMobile:r},h.sessionId))]})]})})})})}function pr({client:t,currentSessionId:s,onSessionSelect:n,onNewSession:a,onRenameSession:o,onArchiveSession:i,onDeleteSession:r,footer:u,className:p}){const{setOpenMobile:d}=ye(),c=()=>{if(a)a();else{const g=new URL(window.location.href);g.searchParams.delete("session"),window.location.href=g.toString()}d(!1)};return e.jsxs(Fs,{className:y("group-data-[side=left]:border-r-0",p),children:[e.jsx(Hs,{className:"h-16 py-5 pl-6 pr-4",children:e.jsxs("div",{className:"flex flex-row items-center justify-between w-full",children:[e.jsx("span",{className:"font-semibold text-lg",children:"Sessions"}),e.jsx(be,{onClick:c,"aria-label":"New Chat",children:e.jsx(rn,{className:"size-4 text-muted-foreground"})})]})}),e.jsx(Vs,{children:e.jsx(ur,{client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:o,onArchiveSession:i,onDeleteSession:r})}),u&&e.jsx(Ws,{children:u})]})}const mr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));mr.displayName="Card";const fr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("flex flex-col space-y-1.5 p-6",t),...s}));fr.displayName="CardHeader";const gr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("text-2xl font-semibold leading-none tracking-tight",t),...s}));gr.displayName="CardTitle";const hr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("text-sm text-muted-foreground",t),...s}));hr.displayName="CardDescription";const xr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("p-6 pt-0",t),...s}));xr.displayName="CardContent";const br=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("flex items-center p-6 pt-0",t),...s}));br.displayName="CardFooter";const Xs=l.forwardRef(({title:t,titleElement:s,description:n,guideUrl:a,guideText:o="Guide",suggestedPrompts:i=[],onPromptClick:r,onGuideClick:u,onOpenFiles:p,onOpenSettings:d,toolsAndMcpsCount:c,onPromptHover:g,onPromptLeave:m,className:x,...h},f)=>{const v=N=>{r?.(N)},b=()=>{a&&window.open(a,"_blank","noopener,noreferrer"),u?.()},j=[];for(let N=0;N<i.length;N+=2)j.push(i.slice(N,N+2));return e.jsxs("div",{ref:f,className:y("flex flex-col items-start",x),...h,children:[s?e.jsx("div",{className:"text-heading-4 text-text-primary mb-6",children:s}):e.jsx("h3",{className:"text-heading-4 text-text-primary mb-6",children:t}),e.jsx("p",{className:"text-subheading text-text-secondary max-w-prose mb-6",children:n}),(p||d)&&e.jsxs("div",{className:"flex items-center gap-1 -ml-3 mb-6",children:[p&&e.jsxs("button",{type:"button",onClick:p,className:"inline-flex items-center gap-1 py-1.5 pr-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:"View Files"}),e.jsx(_e,{className:"size-4 text-foreground shrink-0"})]}),d&&e.jsxs("button",{type:"button",onClick:d,className:"inline-flex items-center gap-1 py-1.5 pr-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsxs("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:["View Tools & MCPs",c!==void 0&&c>0&&e.jsxs("span",{className:"ml-1",children:["(",c,")"]})]}),e.jsx(_e,{className:"size-4 text-foreground shrink-0"})]})]}),(a||u)&&e.jsxs("button",{type:"button",onClick:b,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:o}),e.jsx(_e,{className:"size-4 text-foreground shrink-0"})]}),i.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[e.jsx("p",{className:"text-label text-text-tertiary",children:"Suggested Prompts"}),e.jsx("div",{className:"flex flex-col gap-2.5",children:j.map(N=>e.jsx("div",{className:"flex gap-2.5 items-center",children:N.map(R=>e.jsx("button",{type:"button",onClick:()=>v(R),onMouseEnter:()=>g?.(R),onMouseLeave:()=>m?.(),className:"flex-1 flex items-start gap-2 p-3 bg-secondary hover:bg-secondary/80 rounded-2xl transition-colors min-w-0",children:e.jsx("span",{className:"text-paragraph font-normal leading-normal text-text-tertiary truncate",children:R})},R))},N.join("-")))})]})]})});Xs.displayName="ChatEmptyState";const Js=l.createContext(void 0),It=()=>{const t=l.useContext(Js);if(!t)throw new Error("ChatHeader components must be used within ChatHeader.Root");return t},Zs=l.forwardRef(({defaultExpanded:t=!1,expanded:s,onExpandedChange:n,className:a,children:o,...i},r)=>{const[u,p]=l.useState(t),d=s??u,c=l.useCallback(h=>{p(h),n?.(h)},[n]),g=l.Children.toArray(o),m=g.find(h=>l.isValidElement(h)&&typeof h.type=="function"&&h.type.displayName==="ChatHeader.ExpandablePanel"),x=g.filter(h=>h!==m);return e.jsxs(Js.Provider,{value:{isExpanded:d,setIsExpanded:c},children:[e.jsx("div",{ref:r,className:y("flex items-center justify-between px-6 py-4",a),...i,children:x}),m]})});Zs.displayName="ChatHeader.Root";const yr=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("h1",{ref:a,className:y("m-0 text-subheading font-semibold",t),...n,children:s}));yr.displayName="ChatHeader.Title";const vr=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("flex items-center gap-3",t),...n,children:s}));vr.displayName="ChatHeader.Actions";const wr=t=>{switch(t){case"connected":return"bg-green-500";case"connecting":return"bg-yellow-500";case"error":return"bg-red-500";default:return"bg-gray-500"}},jr=t=>{switch(t){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},Nr=l.forwardRef(({status:t,statusText:s,className:n,...a},o)=>{const i=s??jr(t),r=wr(t);return e.jsxs("div",{ref:o,className:y("flex items-center gap-2",n),...a,children:[e.jsx("div",{className:y("h-2 w-2 rounded-full",r)}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:i})]})});Nr.displayName="ChatHeader.StatusIndicator";const Sr=l.forwardRef(({icon:t,className:s,children:n,onClick:a,...o},i)=>{const{isExpanded:r,setIsExpanded:u}=It(),p=d=>{u(!r),a?.(d)};return e.jsxs("button",{ref:i,type:"button",onClick:p,className:y("rounded p-1 transition-colors hover:bg-background lg:hidden",s),"aria-label":r?"Collapse header":"Expand header",...o,children:[t&&e.jsx("div",{className:y("transition-transform duration-200",r&&"rotate-180"),children:t}),n]})});Sr.displayName="ChatHeader.Toggle";const ea=l.forwardRef(({className:t,children:s,...n},a)=>{const{isExpanded:o}=It();return o?e.jsx("div",{ref:a,className:y("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",t),...n,children:s}):null});ea.displayName="ChatHeader.ExpandablePanel";const ta=l.forwardRef(({commands:t=[],showCommandMenu:s,commandMenuQuery:n,selectedMenuIndex:a,setSelectedMenuIndex:o,setMenuItemCount:i,triggerCounter:r,onChange:u,className:p,...d},c)=>{const g=l.useCallback((x,h)=>{const f=x.toLowerCase(),v=h.toLowerCase();if(!h)return 1;if(f.includes(v))return 1-v.length/f.length;let b=0;for(let j=0;j<f.length&&b<v.length;j++)f[j]===v[b]&&b++;return b===v.length?.5-b/f.length:0},[]),m=l.useMemo(()=>t.map(x=>({...x,score:Math.max(g(x.label,n),x.description?g(x.description,n):0)})).filter(x=>x.score>0).sort((x,h)=>h.score-x.score),[t,n,g]);return l.useEffect(()=>{i(m.length)},[m.length,i]),l.useEffect(()=>{o(0)},[o]),l.useEffect(()=>{r>0&&m[a]&&(m[a].onSelect(),u(""))},[r,m,a,u]),!s||m.length===0?null:e.jsxs("div",{ref:c,className:y("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),...d,children:[e.jsx("div",{className:"text-caption font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),e.jsx("div",{className:"max-h-64 overflow-y-auto",children:m.map((x,h)=>e.jsxs("button",{type:"button",onClick:()=>x.onSelect(),className:y("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",h===a&&"bg-muted"),children:[x.icon&&e.jsx("span",{className:"shrink-0 mt-0.5",children:x.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:x.label}),x.description&&e.jsx("div",{className:"text-caption text-muted-foreground truncate",children:x.description})]})]},x.id))})]})});ta.displayName="ChatInputCommandMenu";const sa=l.createContext(void 0),tt=()=>{const t=l.useContext(sa);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},aa=l.forwardRef(({client:t,startSession:s,value:n,onChange:a,onSubmit:o,disabled:i=!1,isSubmitting:r,submitOnEnter:u=!0,className:p,children:d,...c},g)=>{const m=l.useRef(null),x=l.useCallback(async()=>Promise.resolve(null),[]),h=Gn(t??null,s??x),f=P(B=>B.isStreaming),{addToHistory:v,navigatePrevious:b,navigateNext:j,resetNavigation:N}=Xn(),R=t&&s,C=R?h.value:n||"",M=R?h.onChange:a||(()=>{}),L=R?h.onSubmit:o||(async()=>{}),O=R?h.isSubmitting||f:r||!1,U=l.useCallback(async()=>{const B=C.trim();B&&v(B),await L()},[C,v,L]),[K,E]=l.useState(!1),[F,H]=l.useState(""),[G,Q]=l.useState(0),[T,k]=l.useState(0),[_,I]=l.useState(0),S=l.useCallback(()=>{I(B=>B+1)},[]),$=async B=>{B.preventDefault(),C.trim()&&!O&&!i&&(await U(),setTimeout(()=>{m.current?.focus()},0))},V=B=>{const Z=B.target;!(Z.tagName==="BUTTON"||Z.tagName==="INPUT"||Z.tagName==="TEXTAREA"||Z.closest("button"))&&m.current&&m.current.focus()},oe=B=>{const Z=B.target;!(Z.tagName==="BUTTON"||Z.tagName==="INPUT"||Z.tagName==="TEXTAREA"||Z.closest("button"))&&B.key===" "&&(B.preventDefault(),m.current&&m.current.focus())};return l.useEffect(()=>{const B=document.querySelector('textarea[name="chat-input"]');B&&m.current!==B&&(m.current=B)},[]),l.useEffect(()=>{!C&&m.current&&(m.current.style.height="auto",m.current.style.overflowY="hidden")},[C]),e.jsx(sa.Provider,{value:{value:C,onChange:M,onSubmit:U,disabled:i,isSubmitting:O,submitOnEnter:u,showCommandMenu:K,setShowCommandMenu:E,commandMenuQuery:F,setCommandMenuQuery:H,selectedMenuIndex:G,setSelectedMenuIndex:Q,menuItemCount:T,setMenuItemCount:k,triggerMenuSelect:S,triggerCounter:_,navigateHistoryPrevious:b,navigateHistoryNext:j,resetHistoryNavigation:N},children:e.jsx("form",{ref:g,onSubmit:$,onClick:V,onKeyDown:oe,className:y("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...c,children:d})})});aa.displayName="ChatInput.Root";const na=l.forwardRef(({asChild:t=!1,className:s,onKeyDown:n,onFilesDropped:a,children:o,...i},r)=>{const{value:u,onChange:p,onSubmit:d,disabled:c,isSubmitting:g,submitOnEnter:m,showCommandMenu:x,setShowCommandMenu:h,setCommandMenuQuery:f,setSelectedMenuIndex:v,menuItemCount:b,triggerMenuSelect:j,navigateHistoryPrevious:N,navigateHistoryNext:R,resetHistoryNavigation:C}=tt(),M=l.useRef(null),[L,O]=l.useState(!1),U=l.useCallback(k=>{M.current=k,typeof r=="function"?r(k):r&&(r.current=k)},[r]),K=k=>new Promise((_,I)=>{const S=new FileReader;S.readAsDataURL(k),S.onload=()=>{const $=S.result.split(",")[1];_($||"")},S.onerror=$=>I($)}),T={ref:U,name:"chat-input",value:u,onChange:k=>{const _=k.target.value;if(p(_),C(),_.startsWith("/")&&!_.includes(`
6
- `)){h(!0);const $=_.slice(1);f($)}else h(!1),f("");const I=M.current;if(!I)return;I.style.height="auto";const S=Math.min(I.scrollHeight,164);I.style.height=`${S}px`,I.scrollHeight>164?I.style.overflowY="auto":I.style.overflowY="hidden"},onKeyDown:k=>{if(x&&b>0){if(k.key==="ArrowDown"){k.preventDefault(),v(_=>(_+1)%b);return}else if(k.key==="ArrowUp"){k.preventDefault(),v(_=>(_-1+b)%b);return}else if(k.key==="Enter"&&!k.shiftKey){k.preventDefault(),j();return}else if(k.key==="Escape"){k.preventDefault(),h(!1),f("");return}}if(!x){const _=M.current,I=_?.selectionStart===0&&_?.selectionEnd===0,S=_?.selectionStart===u.length&&_?.selectionEnd===u.length,$=u.includes(`
7
- `);if(k.key==="ArrowUp"&&(I||!u||!$)){const V=N(u);if(V!==null){k.preventDefault(),p(V),setTimeout(()=>{M.current&&(M.current.selectionStart=V.length,M.current.selectionEnd=V.length)},0);return}}else if(k.key==="ArrowDown"&&(S||!u||!$)){const V=R();if(V!==null){k.preventDefault(),p(V),setTimeout(()=>{M.current&&(M.current.selectionStart=V.length,M.current.selectionEnd=V.length)},0);return}}}m&&k.key==="Enter"&&!k.shiftKey&&(u.trim()&&!g&&!c?(k.preventDefault(),d()):(g||c)&&k.preventDefault()),n?.(k)},onDrop:async k=>{k.preventDefault(),O(!1);const _=k.dataTransfer.files;if(!_||_.length===0||!a)return;const I=[];for(const S of Array.from(_))if(S.type.startsWith("image/"))try{const $=await K(S);I.push({name:S.name,path:S.name,size:S.size,mimeType:S.type,data:$})}catch($){console.error("Failed to process dropped file:",S.name,$)}I.length>0&&a(I)},onDragOver:k=>{k.preventDefault(),O(!0)},onDragLeave:k=>{k.preventDefault(),O(!1)},disabled:c,...i};return t&&l.isValidElement(o)?l.cloneElement(o,T):e.jsx("textarea",{...T,rows:1,className:y("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",L&&"ring-2 ring-primary ring-offset-2",s)})});na.displayName="ChatInput.Field";const oa=l.forwardRef(({asChild:t=!1,className:s,disabled:n,children:a,...o},i)=>{const{value:r,disabled:u,isSubmitting:p}=tt(),d=n||u||p||!r.trim(),c=t?ce:fe;return e.jsx(c,{ref:i,type:"submit",disabled:d,variant:t?void 0:"default",size:"icon",className:y(!t&&"gap-1.5 rounded-full",s),...o,children:a})});oa.displayName="ChatInput.Submit";const ra=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("flex items-center justify-between p-2",t),...n,children:s}));ra.displayName="ChatInput.Toolbar";const ia=l.forwardRef(({asChild:t=!1,className:s,children:n,onClick:a,...o},i)=>{const{value:r,onChange:u,setShowCommandMenu:p,setCommandMenuQuery:d}=tt(),c=m=>{r.startsWith("/")||(u("/"),p(!0),d("")),a?.(m)},g=t?ce:fe;return e.jsx(g,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:c,...o,children:n||e.jsx(ln,{className:"size-4"})})});ia.displayName="ChatInput.Actions";const la=l.forwardRef(({asChild:t=!1,className:s,children:n,onFilesSelected:a,...o},i)=>{const r=l.useRef(null),u=g=>new Promise((m,x)=>{const h=new FileReader;h.readAsDataURL(g),h.onload=()=>{const f=h.result.split(",")[1];m(f||"")},h.onerror=f=>x(f)}),p=async g=>{const m=g.target.files;if(!m||m.length===0)return;const x=[];for(const h of Array.from(m))if(h.type.startsWith("image/"))try{const f=await u(h);x.push({name:h.name,path:h.name,size:h.size,mimeType:h.type,data:f})}catch(f){console.error("Failed to process file:",h.name,f)}x.length>0&&a&&a(x),r.current&&(r.current.value="")},d=g=>{g.preventDefault(),r.current?.click()},c=t?ce:fe;return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:r,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:p}),e.jsx(c,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:d,...o,children:n||e.jsx(cn,{className:"size-4"})})]})});la.displayName="ChatInput.Attachment";const ca=l.forwardRef(({asChild:t=!1,className:s,children:n,...a},o)=>{const i=t?ce:fe;return e.jsx(i,{ref:o,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),...a,children:n||e.jsx(dn,{className:"size-4"})})});ca.displayName="ChatInput.VoiceInput";const da=l.forwardRef(({commands:t=[],className:s,onChange:n,...a},o)=>{const{showCommandMenu:i,commandMenuQuery:r,selectedMenuIndex:u,setSelectedMenuIndex:p,setMenuItemCount:d,triggerCounter:c,onChange:g}=tt();return e.jsx(ta,{ref:o,commands:t,showCommandMenu:i,commandMenuQuery:r,selectedMenuIndex:u,setSelectedMenuIndex:p,setMenuItemCount:d,triggerCounter:c,onChange:g,className:s,...a})});da.displayName="ChatInput.CommandMenu";function kr(){const t=l.useRef(null),s=l.useRef(null),[n,a]=l.useState(!0),o=l.useRef(!0),i=l.useRef(!1);l.useEffect(()=>{o.current=n},[n]);const r=l.useCallback(()=>{if(!t.current)return!0;const{scrollTop:c,scrollHeight:g,clientHeight:m}=t.current;return c+m>=g-100},[]),u=l.useCallback((c="smooth")=>{t.current&&t.current.scrollTo({top:t.current.scrollHeight,behavior:c})},[]);l.useEffect(()=>{const c=t.current;if(!c)return;let g;const m=()=>{i.current=!0,clearTimeout(g);const x=r();a(x),o.current=x,g=setTimeout(()=>{i.current=!1},150)};return c.addEventListener("scroll",m,{passive:!0}),()=>{c.removeEventListener("scroll",m),clearTimeout(g)}},[r]),l.useEffect(()=>{const c=t.current;if(!c)return;const g=()=>{o.current&&!i.current&&requestAnimationFrame(()=>{c.scrollTo({top:c.scrollHeight,behavior:"instant"}),a(!0),o.current=!0})},m=new MutationObserver(g);m.observe(c,{childList:!0,subtree:!0,characterData:!0});const x=new ResizeObserver(g);return x.observe(c),Array.from(c.children).forEach(h=>{x.observe(h)}),()=>{m.disconnect(),x.disconnect()}},[]);function p(){a(!0),o.current=!0}function d(){a(!1),o.current=!1}return{containerRef:t,endRef:s,isAtBottom:n,scrollToBottom:u,onViewportEnter:p,onViewportLeave:d}}const Be={normal:.25},X={smooth:[.25,.1,.25,1]},Cr={collapsed:{height:0,opacity:0,overflow:"hidden"},expanded:{height:"auto",opacity:1,overflow:"visible"}},ze={duration:2,ease:"linear",repeat:1/0,repeatType:"loop"},Tr={duration:Be.normal,ease:X.smooth};function te(t,s=Tr){return t?{duration:.01}:s}function $e(t,s=Be.normal){return t?.01:s}const Ir=({...t})=>e.jsx(Fa,{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"}},...t}),_t=l.createContext(void 0),De=()=>{const t=l.useContext(_t);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},ua=l.forwardRef(({defaultSidebarOpen:t=!1,defaultPanelSize:s="hidden",defaultActiveTab:n="todo",className:a,children:o,...i},r)=>{const[u,p]=l.useState(t),[d,c]=l.useState(s),[g,m]=l.useState(n),[x,h]=l.useState(s!=="hidden"),f=l.useCallback(()=>{c(v=>v==="hidden"?"large":"hidden"),h(v=>!v)},[]);return l.useEffect(()=>{h(d!=="hidden")},[d]),e.jsx(_t.Provider,{value:{sidebarOpen:u,setSidebarOpen:p,panelSize:d,setPanelSize:v=>{c(v),h(v!=="hidden")},activeTab:g,setActiveTab:m,panelOpen:x,setPanelOpen:h,togglePanel:f},children:e.jsx("div",{ref:r,"data-panel-state":x?"expanded":"collapsed",className:y("flex h-screen flex-row bg-background text-foreground overflow-hidden",a),...i,children:o})})});ua.displayName="ChatLayout.Root";const _r=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("relative z-10 border-b border-border bg-card shrink-0",t),...n,children:s}));_r.displayName="ChatLayout.Header";const pa=l.forwardRef(({className:t,children:s},n)=>e.jsx(Y.div,{ref:n,layout:!0,transition:{duration:.5,ease:X.smooth},className:y("flex flex-1 flex-col overflow-hidden h-full min-w-0",t),children:s}));pa.displayName="ChatLayout.Main";const ma=l.forwardRef(({showToaster:t=!0,className:s,children:n,...a},o)=>e.jsxs("div",{ref:o,className:y("relative flex flex-1 flex-col overflow-hidden",s),...a,children:[n,t&&e.jsx(Ir,{})]}));ma.displayName="ChatLayout.Body";const fa=l.forwardRef(({className:t,children:s,onScrollChange:n,showScrollToBottom:a=!0,initialScrollToBottom:o=!0,...i},r)=>{const{containerRef:u,endRef:p,isAtBottom:d,scrollToBottom:c}=kr(),g=l.useRef(!1);l.useImperativeHandle(r,()=>u.current),l.useEffect(()=>{n?.(d)},[d,n]),l.useEffect(()=>{if(!o)return;const x=u.current;if(x&&!g.current){const h=setTimeout(()=>{x.scrollTop=x.scrollHeight,g.current=!0},100);return()=>clearTimeout(h)}},[o,u]);const m=!d&&a;return e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsxs("div",{ref:u,className:y("h-full overflow-y-auto flex flex-col",t),...i,children:[e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s}),e.jsx("div",{ref:p,className:"min-h-[24px] min-w-[24px] shrink-0"})]}),m&&e.jsx("button",{type:"button",onClick:()=>c("smooth"),className:y("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:e.jsx(un,{className:"size-4"})})]})});fa.displayName="ChatLayout.Messages";const ga=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("bg-linear-to-t from-background to-transparent px-4 pb-4",t),...n,children:e.jsx("div",{className:"mx-auto max-w-chat",children:s})}));ga.displayName="ChatLayout.Footer";const Rr=l.forwardRef(({className:t,children:s,...n},a)=>{const{sidebarOpen:o}=De();return o?e.jsx("div",{ref:a,className:y("border-r border-border bg-card w-64 overflow-y-auto",t),...n,children:s}):null});Rr.displayName="ChatLayout.Sidebar";const ha=l.forwardRef(({breakpoint:t="lg",className:s,children:n},a)=>{const{panelSize:o}=De(),[i,r]=l.useState(450),u=Ba(i),[p,d]=l.useState(!1),c=l.useRef(0),g=l.useRef(i),m=o!=="hidden";l.useEffect(()=>{u.set(i)},[i,u]);const x=l.useCallback(v=>{v.preventDefault(),d(!0),c.current=v.clientX,g.current=i,v.target.setPointerCapture(v.pointerId)},[i]),h=l.useCallback(v=>{if(!p)return;const b=v.clientX-c.current,j=Math.max(250,Math.min(800,g.current-b));u.set(j)},[p,u]),f=l.useCallback(v=>{if(!p)return;const b=v.clientX-c.current,j=Math.max(250,Math.min(800,g.current-b));r(j),u.set(j),d(!1),v.target.releasePointerCapture(v.pointerId)},[p,u]);return e.jsx(Ie,{initial:!1,mode:"wait",children:m&&e.jsxs(Y.div,{ref:a,layout:!0,initial:{width:0,opacity:0},animate:{width:i,opacity:1},exit:{width:0,opacity:0},transition:{duration:.5,ease:X.smooth},style:{width:p?u:void 0},className:y("hidden h-full border-l border-border bg-card overflow-hidden relative",t==="md"&&"md:block",t==="lg"&&"lg:block",t==="xl"&&"xl:block",t==="2xl"&&"2xl:block",s),children:[e.jsx("div",{onPointerDown:x,onPointerMove:h,onPointerUp:f,className:y("absolute left-0 inset-y-0 w-2 -ml-1 cursor-col-resize z-10","group flex items-center justify-center","hover:bg-primary/5 transition-colors delay-300",p&&"bg-primary/10")}),e.jsx("div",{className:"h-full overflow-y-auto",style:{width:i},children:n})]},"aside-panel")})});ha.displayName="ChatLayout.Aside";function xa({item:t,level:s=0,onSelect:n,selectedId:a,isDropTarget:o=!1,onDownload:i,onRename:r,onDelete:u}){const[p,d]=l.useState(!0),c=a===t.id,g=()=>{t.type==="folder"&&d(!p)},m=()=>{n?.(t),t.type==="folder"&&g()},x=f=>{f.key==="Enter"||f.key===" "?(f.preventDefault(),m()):f.key==="ArrowRight"&&t.type==="folder"&&!p?(f.preventDefault(),d(!0)):f.key==="ArrowLeft"&&t.type==="folder"&&p&&(f.preventDefault(),d(!1))},h=()=>s===0?"p-2":s===1?"pl-8 pr-2 py-2":"pl-16 pr-2 py-2";return e.jsxs("div",{className:"flex flex-col w-full",children:[e.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":t.type==="folder"?p:void 0,className:y("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",h(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",c&&"bg-accent",o&&["bg-accent","border border-dashed border-border-dark"]),onClick:m,onKeyDown:x,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.type==="folder"?p?e.jsx(pn,{className:"size-4"}):e.jsx(mn,{className:"size-4"}):e.jsx(fn,{className:"size-4"})}),e.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:t.name}),e.jsxs(jt,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx("button",{className:y("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:f=>{f.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(gn,{className:"size-4"})})}),e.jsxs(Ze,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:f=>f.stopPropagation(),children:[i&&e.jsx(le,{onClick:f=>{f.stopPropagation(),i(t)},children:"Download"}),r&&e.jsx(le,{onClick:f=>{f.stopPropagation(),r(t)},children:"Rename"}),(i||r)&&u&&e.jsx(St,{}),u&&e.jsx(le,{className:"text-destructive focus:text-destructive focus:bg-muted",onClick:f=>{f.stopPropagation(),u(t)},children:e.jsx("span",{className:"text-paragraph-sm",children:"Delete"})})]})]}),t.type==="folder"&&e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-muted-foreground",children:e.jsx(me,{className:y("size-4 transition-transform",!p&&"-rotate-90")})})]}),t.type==="folder"&&p&&t.children&&e.jsx("div",{className:"flex flex-col",children:t.children.map(f=>e.jsx(xa,{item:f,level:s+1,...n&&{onSelect:n},...a&&{selectedId:a},...i&&{onDownload:i},...r&&{onRename:r},...u&&{onDelete:u}},f.id))})]})}const Er=new Ro;function Mr({className:t,provider:s=Er,onItemSelect:n,onDownload:a,onRename:o,onDelete:i}){const[r,u]=l.useState([]),[p,d]=l.useState(),[c,g]=l.useState(!0),[m,x]=l.useState();l.useEffect(()=>{(async()=>{try{g(!0);const v=await s.getRootItems();u(v),x(void 0)}catch(v){x(v instanceof Error?v.message:"Failed to load items")}finally{g(!1)}})()},[s]);const h=f=>{d(f.id),n?.(f)};return c?e.jsx("div",{className:y("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):m?e.jsx("div",{className:y("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",m]})}):e.jsx("div",{className:y("flex flex-col",t),children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items found"}):r.map(f=>e.jsx(xa,{item:f,onSelect:h,...p&&{selectedId:p},...a&&{onDownload:a},...o&&{onRename:o},...i&&{onDelete:i}},f.id))})}const ba=l.forwardRef(({source:t,isSelected:s,className:n,...a},o)=>e.jsxs("button",{ref:o,type:"button",className:y("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",s&&"bg-accent",n),onClick:()=>window.open(t.url,"_blank"),...a,children:[e.jsx("div",{className:"shrink-0 flex items-center h-5",children:e.jsx("div",{className:"relative rounded-[3px] size-4 overflow-hidden bg-muted",children:t.favicon?e.jsx("img",{alt:t.sourceName,className:"size-full object-cover",src:t.favicon}):e.jsx("div",{className:"size-full bg-muted"})})}),e.jsxs("div",{className:"flex flex-1 flex-col gap-1 min-w-0",children:[e.jsxs("div",{className:"text-paragraph-sm text-foreground",children:[e.jsx("span",{className:"font-medium",children:t.sourceName}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",t.title]})]}),e.jsx("p",{className:"text-paragraph-sm text-muted-foreground line-clamp-3",children:t.snippet})]})]}));ba.displayName="SourceListItem";const ya=l.forwardRef(({todo:t,className:s,...n},a)=>{const o=t.status==="completed";return e.jsxs("div",{ref:a,className:y("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,s),role:"button",tabIndex:0,...n,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.status==="completed"?e.jsx(Qe,{className:"size-4 text-muted-foreground"}):t.status==="in_progress"?e.jsx("div",{className:"size-2.5 rounded-full bg-foreground animate-pulse-scale"}):e.jsx(Ge,{className:"size-4 text-foreground"})}),e.jsx("p",{className:y("flex-1 text-foreground",o&&"line-through text-muted-foreground",t.status==="in_progress"&&"font-medium"),children:t.text})]})});ya.displayName="TodoListItem";function Ar(){return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(Ye,{className:"size-8 text-neutral-300"}),e.jsxs("p",{className:"text-base leading-6 text-neutral-400 text-center",children:["There's nothing on the",e.jsx("br",{}),"to-do list yet."]})]})}const Rt=l.forwardRef(({client:t,todos:s,className:n,...a},o)=>{const i=s||[];return i.length===0?e.jsx("div",{ref:o,className:y("h-full",n),...a,children:e.jsx(Ar,{})}):e.jsx("div",{ref:o,className:y("space-y-2 overflow-y-auto",n),...a,children:i.map(r=>e.jsx(ya,{todo:r},r.id))})});Rt.displayName="TodoList";const st=l.forwardRef(({todos:t=[],className:s,...n},a)=>e.jsx("div",{ref:a,className:y("h-full",s),...n,children:e.jsx(Rt,{todos:t,className:"h-full"})}));st.displayName="TodoTabContent";const at=l.forwardRef(({files:t=[],provider:s,onFileSelect:n,className:a,...o},i)=>{const r=l.useCallback(d=>{console.log("Download:",d.name)},[]),u=l.useCallback(d=>{console.log("Rename:",d.name)},[]),p=l.useCallback(d=>{console.log("Delete:",d.name)},[]);return e.jsx("div",{ref:i,className:y("h-full",a),...o,children:e.jsx(Mr,{...s&&{provider:s},onItemSelect:d=>{d.type==="file"&&n&&n(d.path||d.name)},onDownload:r,onRename:u,onDelete:p,className:"h-full"})})});at.displayName="FilesTabContent";const nt=l.forwardRef(({sources:t,className:s,...n},a)=>{const o=t&&t.length>0?t:Eo;return e.jsx("div",{ref:a,className:y("space-y-2",s),...n,children:o.map(i=>e.jsx(ba,{source:i},i.id))})});nt.displayName="SourcesTabContent";const Dr=l.forwardRef(({data:t,className:s,...n},a)=>e.jsxs("div",{ref:a,className:y("space-y-4",s),...n,children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Database"}),e.jsxs("div",{className:"text-paragraph-sm text-muted-foreground",children:[e.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),e.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[e.jsx("p",{children:"Your large data table would go here"}),t&&typeof t=="object"?e.jsx("pre",{className:"mt-2 text-caption overflow-auto",children:JSON.stringify(t,null,2)}):null]})]})]}));Dr.displayName="DatabaseTabContent";const Et=l.forwardRef(({tools:t=[],mcps:s=[],subagents:n=[],className:a,...o},i)=>e.jsxs("div",{ref:i,className:y("space-y-6",a),...o,children:[e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Tools"}),t.length>0?e.jsx("div",{className:"space-y-2",children:t.map(r=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:r.prettyName||r.name}),r.description&&e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-1",children:r.description})]},r.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No tools available"})]}),e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"MCP Servers"}),s.length>0?e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:r.name}),e.jsxs("div",{className:"text-caption text-muted-foreground mt-1",children:["Transport: ",r.transport]})]},r.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No MCP servers connected"})]}),e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Subagents"}),n.length>0?e.jsx("div",{className:"space-y-2",children:n.map(r=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:r.name}),e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-2",children:r.description})]},r.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No subagents available"})]})]}));Et.displayName="SettingsTabContent";const Mt=Ja,Re=l.forwardRef(({className:t,...s},n)=>e.jsx(is,{ref:n,className:y("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));Re.displayName=is.displayName;const Ee=l.forwardRef(({className:t,...s},n)=>e.jsx(ls,{ref:n,className:y("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",t),...s}));Ee.displayName=ls.displayName;const J=l.forwardRef(({className:t,...s},n)=>e.jsx(cs,{ref:n,className:y("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));J.displayName=cs.displayName;const Pr=l.forwardRef(({client:t,todos:s,variant:n="animated",showIcons:a=!1,visibleTabs:o=["todo","files","database"],className:i,...r},u)=>{const p=s||[],[d,c]=l.useState(o[0]||"todo"),g=l.useRef(null),m=l.useRef(null);l.useEffect(()=>{const v=setTimeout(()=>{const b=g.current;if(d&&b){const j=m.current;if(j){const N=b.getBoundingClientRect(),R=j.getBoundingClientRect(),C=R.left-N.left,M=R.width,L=C/N.width*100,O=100-(C+M)/N.width*100;b.style.clipPath=`inset(0 ${O.toFixed(2)}% 0 ${L.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(v)},[d]);const h=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:Ye},{id:"files",label:"Files",icon:ht},{id:"database",label:"Database",icon:ys},{id:"sources",label:"Sources",icon:vs}].filter(f=>o.includes(f.id));return e.jsx("div",{ref:u,className:y("select-none",i),...r,children:e.jsxs(Mt,{value:d,onValueChange:c,className:"w-full",children:[n==="pills"?e.jsx(Re,{className:y("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:h.map(f=>{const v=f.icon;return e.jsxs(Ee,{value:f.id,className:y("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[a&&v&&e.jsx(v,{className:"size-4"}),f.label]},f.id)})}):e.jsxs("div",{className:"relative mb-4 border-border",children:[e.jsx(Re,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:h.map(f=>e.jsx(Ee,{value:f.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:f.label},f.id))}),e.jsx("div",{ref:g,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:e.jsx(Re,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:h.map(f=>e.jsx(Ee,{value:f.id,ref:d===f.id?m: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:f.label},f.id))})})]}),e.jsx(J,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?e.jsx(st,{todos:p}):e.jsx(Rt,{todos:p})}),e.jsx(J,{value:"files",className:n==="pills"?"mt-0":"",children:e.jsx(at,{})}),e.jsx(J,{value:"database",className:n==="pills"?"mt-0":"",children:e.jsx("div",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})}),e.jsx(J,{value:"sources",className:n==="pills"?"mt-0":"",children:e.jsx(nt,{})})]})})});Pr.displayName="ChatSecondaryPanel";const Ur=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("flex h-full flex-col",t),...n,children:s}));Ur.displayName="ChatSidebar.Root";const Lr=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("border-b border-border px-4 py-3",t),...n,children:s}));Lr.displayName="ChatSidebar.Header";const Or=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("flex-1 overflow-y-auto p-4",t),...n,children:s}));Or.displayName="ChatSidebar.Content";const zr=l.forwardRef(({className:t,children:s,...n},a)=>e.jsx("div",{ref:a,className:y("border-t border-border px-4 py-3",t),...n,children:s}));zr.displayName="ChatSidebar.Footer";const $r=l.forwardRef(({children:t,className:s,...n},a)=>{const[o,i]=l.useState(t),[r,u]=l.useState(!1),p=l.useRef(t),d=l.useRef(!0);return l.useEffect(()=>{if(d.current){d.current=!1,p.current=t;return}if(p.current===t)return;u(!0);const c=setTimeout(()=>{i(t),p.current=t,requestAnimationFrame(()=>{u(!1)})},150);return()=>{clearTimeout(c)}},[t]),e.jsx("span",{ref:a,className:y("text-sm text-foreground opacity-60 transition-opacity duration-300",r?"opacity-0":"opacity-60",s),...n,children:o})});$r.displayName="ChatStatus";const ge=de("gui");function Fr({children:t}){const{setPanelSize:s,setActiveTab:n,panelSize:a,activeTab:o}=De(),i=()=>{a!=="hidden"&&o==="files"?s("hidden"):(s("small"),n("files"))},r=()=>{a!=="hidden"&&o==="settings"?s("hidden"):(s("small"),n("settings"))};return e.jsx(e.Fragment,{children:t({openFiles:i,openSettings:r})})}function Br({client:t,startSession:s,placeholder:n,latestContextSize:a,commandMenuItems:o}){const i=P(d=>d.input.attachedFiles),r=P(d=>d.addFileAttachment),u=P(d=>d.removeFileAttachment),p=d=>{for(const c of d)r(c)};return e.jsxs(aa,{client:t,startSession:s,children:[e.jsx(da,{commands:o}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border-b border-border",children:i.map((d,c)=>e.jsxs("div",{className:"relative group rounded-md overflow-hidden border border-border",children:[e.jsx("img",{src:`data:${d.mimeType};base64,${d.data}`,alt:d.name,className:"h-20 w-20 object-cover"}),e.jsx("button",{type:"button",onClick:()=>u(c),className:"absolute top-1 right-1 p-1 rounded-full bg-background/80 hover:bg-background opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(gt,{className:"size-3"})})]},c))}),e.jsx(na,{placeholder:n,autoFocus:!0,onFilesDropped:p}),e.jsxs(ra,{children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx(ia,{}),e.jsx(la,{onFilesSelected:p}),a!=null&&e.jsx(va,{contextSize:a})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ca,{}),e.jsx(oa,{children:e.jsx(xn,{className:"size-4"})})]})]})]})}function Hr({todos:t,tools:s,mcps:n,subagents:a}){const{activeTab:o,setActiveTab:i}=De();return e.jsxs(Mt,{value:o,onValueChange:r=>i(r),className:"flex flex-col h-full",children:[e.jsx("div",{className:y("border-b border-border bg-card","px-4 py-2 h-16","flex items-center","[border-bottom-width:0.5px]"),children:e.jsx(Dt,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(J,{value:"todo",className:"flex-1 p-4 mt-0",children:e.jsx(st,{todos:t})}),e.jsx(J,{value:"files",className:"flex-1 p-4 mt-0",children:e.jsx(at,{})}),e.jsx(J,{value:"sources",className:"flex-1 p-4 mt-0",children:e.jsx(nt,{})}),e.jsx(J,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(Et,{tools:s??[],mcps:n??[],subagents:a??[]})})]})}function Wr({agentName:t,showHeader:s}){const{isExpanded:n,setIsExpanded:a}=It();return e.jsxs("div",{className:"flex lg:hidden items-center flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(Ea,{}),s&&e.jsx("span",{className:"text-heading-4 text-foreground",children:t})]}),e.jsx(Aa,{}),e.jsx(be,{"aria-label":"Toggle menu",onClick:()=>a(!n),children:e.jsx(js,{className:y("size-4 text-muted-foreground transition-transform duration-200",n?"":"rotate-180")})})]})}function Vr({agentName:t,todos:s,sources:n,showHeader:a,sessionId:o,debuggerUrl:i,tools:r,mcps:u,subagents:p}){const{togglePanel:d,panelOpen:c}=De(),g=i?o?`${i}/sessions/${o}`:i:null;return e.jsxs(Zs,{className:y("border-b border-border bg-card relative lg:p-0","[border-bottom-width:0.5px]"),children:[e.jsxs("div",{className:"hidden lg:flex items-center w-full h-16 py-5 pl-6 pr-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(Ea,{}),a&&e.jsx("span",{className:"text-heading-4 text-foreground",children:t})]}),i&&e.jsx(kt,{children:e.jsxs(Ct,{children:[e.jsx(Tt,{asChild:!0,children:e.jsx(be,{"aria-label":"View session in debugger",disabled:!g,asChild:!!g,children:g?e.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ot,{className:"size-4 text-muted-foreground"})}):e.jsx(Ot,{className:"size-4 text-muted-foreground"})})}),e.jsx(et,{children:e.jsx("p",{children:o?"View session in debugger":"Open debugger"})})]})}),e.jsx(Aa,{}),e.jsx(be,{"aria-label":"Toggle panel",onClick:d,"data-state":c?"open":"closed",children:e.jsx(hn,{className:"size-4 text-muted-foreground"})})]}),e.jsx(Wr,{agentName:t,showHeader:a}),e.jsx(ea,{className:y("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:e.jsxs(Mt,{defaultValue:"todo",className:"w-full",children:[e.jsx(Dt,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"default"}),e.jsx(J,{value:"todo",className:"mt-4",children:e.jsx(st,{todos:s})}),e.jsx(J,{value:"files",className:"mt-4",children:e.jsx(at,{})}),e.jsx(J,{value:"sources",className:"mt-4",children:e.jsx(nt,{sources:n})}),e.jsx(J,{value:"settings",className:"mt-4",children:e.jsx(Et,{tools:r??[],mcps:u??[],subagents:p??[]})})]})})]})}function qr({client:t,initialSessionId:s,error:n,debuggerUrl:a}){const{connectionStatus:o,connect:i,sessionId:r,startSession:u}=Qn(t,s),{messages:p,sendMessage:d}=Is(t,u);Zn(t);const c=P(I=>I.error),[g,m]=l.useState("Agent"),[x,h]=l.useState("This research agent can help you find and summarize information, analyze sources, track tasks, and answer questions about your research. Start by typing a message below to begin your investigation."),[f,v]=l.useState(["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","What can you help me with?"]),[b,j]=l.useState([]),[N,R]=l.useState([]),[C,M]=l.useState([]),[L,O]=l.useState(typeof window<"u"?window.innerWidth>=1024:!0),[U,K]=l.useState("Type a message or / for commands..."),[E,F]=l.useState(!1);l.useEffect(()=>{ge.debug("Connection status changed",{status:o}),o==="error"&&c&&ge.error("Connection error occurred",{error:c})},[o,c]),l.useEffect(()=>{if(t){const I=t.getCurrentSession();I?.metadata?.agentName&&m(I.metadata.agentName);const S=t.getAgentInfo();S.displayName?m(S.displayName):S.name&&m(S.name),S.description&&h(S.description),S.suggestedPrompts&&S.suggestedPrompts.length>0&&v(S.suggestedPrompts),S.tools&&S.tools.length>0&&(j(S.tools),ge.info("Agent tools loaded",{tools:S.tools})),S.mcps&&S.mcps.length>0&&(R(S.mcps),ge.info("Agent MCPs loaded",{mcps:S.mcps})),S.subagents&&S.subagents.length>0&&(M(S.subagents),ge.info("Agent subagents loaded",{subagents:S.subagents})),S.uiConfig?.hideTopBar&&F(!0)}},[t,r,o]),l.useEffect(()=>{const I=window.matchMedia("(min-width: 1024px)"),S=$=>{O($.matches)};return O(I.matches),I.addEventListener("change",S),()=>{I.removeEventListener("change",S)}},[]);const H=I=>{K(I)},G=()=>{K("Type a message or / for commands...")};if(n)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:e.jsxs("div",{className:"text-center p-8 max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-destructive mb-4",children:"Initialization Error"}),e.jsx("p",{className:"text-foreground mb-4",children:n}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})});const Q=P(Kn),T=[{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"}],k=P(I=>I.latestContextSize),_=[{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx(ws,{className:"h-4 w-4"}),category:"action",onSelect:()=>{ge.info("User opened settings")}}];return e.jsxs($s,{defaultOpen:!1,children:[e.jsx(pr,{client:t,currentSessionId:r}),e.jsx(Bs,{children:e.jsxs(ua,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsxs(pa,{children:[!E&&e.jsx(Vr,{agentName:g,todos:Q,sources:T,showHeader:p.length>0,sessionId:r,tools:b,mcps:N,subagents:C,...a&&{debuggerUrl:a}}),o==="error"&&c&&e.jsx("div",{className:"border-b border-destructive/20 bg-destructive/10 px-6 py-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"mb-1 text-paragraph-sm font-semibold text-destructive",children:"Connection Error"}),e.jsx("p",{className:"whitespace-pre-line text-paragraph-sm text-foreground",children:c})]}),e.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"})]})}),e.jsxs(ma,{children:[e.jsx(fa,{children:p.length===0?e.jsx(Fr,{children:({openFiles:I,openSettings:S})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Xs,{title:g,description:x,suggestedPrompts:f,onPromptClick:$=>{d($),K("Type a message or / for commands..."),ge.info("Prompt clicked",{prompt:$})},onPromptHover:H,onPromptLeave:G,onOpenFiles:I,onOpenSettings:S,toolsAndMcpsCount:b.length+N.length+C.length})})}):e.jsx("div",{className:"flex flex-col px-4",children:p.map((I,S)=>{const $=S===0,V=$?null:p[S-1];let oe="mt-2";return $?oe=I.role==="assistant"?"mt-8":"mt-2":I.role==="user"?oe=(V?.role==="user","mt-4"):I.role==="assistant"&&(oe=V?.role==="assistant"?"mt-2":"mt-6"),e.jsx(ja,{message:I,className:oe,isLastMessage:S===p.length-1,children:e.jsx(Ia,{message:I,thinkingDisplayStyle:"collapsible"})},I.id)})})}),e.jsx(ga,{children:e.jsx(Br,{client:t,startSession:u,placeholder:U,latestContextSize:k,commandMenuItems:_})})]})]}),L&&e.jsx(ha,{breakpoint:"lg",children:e.jsx(Hr,{todos:Q,tools:b,mcps:N,subagents:C})})]})})]})}const Kr=2e5,va=l.forwardRef(({contextSize:t,className:s,...n},a)=>{const o=Math.max(t.totalEstimated,t.llmReportedInputTokens??0),i=t.modelContextWindow??Kr,r=o/i*100,u=`${r.toFixed(1)}%`,p=Math.min(100,Math.max(0,r)),c=(j=>j<50?"text-foreground":j<75?"text-yellow-500":"text-red-500")(r),g=j=>o===0?"0.0%":`${(j/o*100).toFixed(1)}%`,m=16,x=2,h=(m-x)/2,f=m/2,v=2*Math.PI*h,b=v-p/100*v;return e.jsx(kt,{children:e.jsxs(Ct,{children:[e.jsx(Tt,{asChild:!0,children:e.jsx(fe,{ref:a,type:"button",variant:"ghost",size:"icon",className:y("rounded-full cursor-default",c,s),...n,children:e.jsxs("svg",{width:m,height:m,viewBox:`0 0 ${m} ${m}`,className:"transform -rotate-90",children:[e.jsx("circle",{cx:f,cy:f,r:h,stroke:"currentColor",strokeWidth:x,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:f,cy:f,r:h,stroke:"currentColor",strokeWidth:x,fill:"transparent",strokeDasharray:v,strokeDashoffset:b,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(et,{side:"top",align:"center",className:"p-3",children:e.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"System Prompt:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.systemPromptTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.systemPromptTokens),")"]})]})]}),t.toolOverheadTokens!==void 0&&t.toolOverheadTokens>0&&e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tools Definition:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.toolOverheadTokens),")"]})]})]}),t.mcpOverheadTokens!==void 0&&t.mcpOverheadTokens>0&&e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"MCPs Definition:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.mcpOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.mcpOverheadTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"User Messages:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.userMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.userMessagesTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Assistant Messages:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.assistantMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.assistantMessagesTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tool Inputs:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolInputTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.toolInputTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tool Results:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolResultsTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",g(t.toolResultsTokens),")"]})]})]})]}),e.jsx("div",{className:"border-t border-border pt-2",children:e.jsxs("div",{className:y("flex justify-end gap-2 font-semibold",c),children:[e.jsx("span",{children:o.toLocaleString()}),e.jsxs("span",{children:["(",u,")"]})]})})]})})]})})});va.displayName="ContextUsageButton";const Gr=l.forwardRef(({autoScroll:t=!0,isStreaming:s=!1,scrollBehavior:n="smooth",scrollThreshold:a=100,showScrollButton:o=!0,scrollButton:i,className:r,children:u,...p},d)=>{const c=l.useRef(null),[g,m]=l.useState(!0),[x,h]=l.useState(!1),f=l.useRef(0);l.useImperativeHandle(d,()=>{if(!c.current)throw new Error("Container ref not initialized");return c.current});const v=l.useCallback(()=>{const j=c.current;if(!j)return;const{scrollTop:N,scrollHeight:R,clientHeight:C}=j,L=R-N-C<a;m(L),h(!L&&o),f.current=N},[a,o]),b=l.useCallback((j=n)=>{const N=c.current;N&&N.scrollTo({top:N.scrollHeight,behavior:j})},[n]);return l.useEffect(()=>{!t||!c.current||(s&&g?b("auto"):!s&&g&&b())},[t,s,g,b]),l.useEffect(()=>{const j=c.current;if(!j)return;const N=()=>{v()};return j.addEventListener("scroll",N,{passive:!0}),v(),()=>{j.removeEventListener("scroll",N)}},[v]),l.useEffect(()=>{const j=c.current;if(!j)return;const N=new ResizeObserver(()=>{g&&t&&b("auto")});return N.observe(j),()=>{N.disconnect()}},[g,t,b]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx("div",{ref:c,className:y("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",r),...p,children:e.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:u})}),x&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||e.jsxs("button",{type:"button",onClick:()=>b(),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:[e.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:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})}),"Scroll to bottom"]})})]})});Gr.displayName="Conversation";const Qr=ns,wa=l.forwardRef(({className:t,...s},n)=>e.jsx(We,{ref:n,className:y("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",t),...s}));wa.displayName=We.displayName;const Yr=l.forwardRef(({className:t,children:s,...n},a)=>e.jsxs(Qr,{children:[e.jsx(wa,{}),e.jsxs(Ve,{ref:a,className:y("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",t),...n,children:[s,e.jsxs(os,{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:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Yr.displayName=Ve.displayName;const Xr=l.forwardRef(({className:t,...s},n)=>e.jsx(qe,{ref:n,className:y("text-subheading font-semibold leading-none tracking-tight",t),...s}));Xr.displayName=qe.displayName;const Jr=l.forwardRef(({className:t,...s},n)=>e.jsx(Ke,{ref:n,className:y("text-paragraph-sm text-muted-foreground",t),...s}));Jr.displayName=Ke.displayName;function Zr(t,s,n,a){const o=n==="triggered",i=a==="no_action_needed";return t==="context_size"?o?{icon:rt,title:"Compacting Context..."}:{icon:rt,title:i?"Context Check":"Context Compacted"}:t==="tool_response"?o?{icon:zt,title:"Compacting Response..."}:{icon:zt,title:i?"Response Check":"Tool Response Compacted"}:{icon:rt,title:o?"Running Hook...":"Hook Executed"}}function ke(t){return t.toLocaleString()}function dt({notification:t}){const[s,n]=l.useState(!1),[a,o]=l.useState(0),{icon:i,title:r}=Zr(t.hookType,t.callback,t.status,t.metadata?.action),u=t.status==="triggered",p=t.status==="completed",d=t.status==="error";l.useEffect(()=>{if(!u||!t.triggeredAt)return;const m=()=>{const h=(Date.now()-t.triggeredAt)/1e3;o(h)};m();const x=setInterval(m,100);return()=>clearInterval(x)},[u,t.triggeredAt]);let c="";if(u&&t.currentPercentage!==void 0)c=`Context at ${t.currentPercentage.toFixed(1)}% (threshold: ${t.threshold}%)`;else if(p&&t.metadata?.tokensSaved!==void 0){const{tokensSaved:m,originalTokens:x}=t.metadata;if(x!==void 0&&x>0)c=`${((m??0)/x*100).toFixed(0)}% reduced`;else if(t.currentPercentage!==void 0&&t.currentPercentage>0){const f=t.currentPercentage/100*2e5;c=`${((m??0)/f*100).toFixed(1)}% context freed`}else c=`${ke(m)} tokens saved`}else d&&t.error&&(c=t.error);const g=t.metadata?.truncationWarning;return e.jsxs("div",{className:"flex flex-col my-3",children:[e.jsxs("button",{type:"button",className:"flex flex-col items-start gap-0.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>n(!s),"aria-expanded":s,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("div",{className:d?"text-destructive":"text-muted-foreground",children:e.jsx(i,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:r}),u&&e.jsxs(e.Fragment,{children:[e.jsx(xt,{className:"h-3 w-3 text-muted-foreground animate-spin"}),e.jsxs("span",{className:"text-muted-foreground/70 tabular-nums",children:[a.toFixed(1),"s"]})]}),p&&e.jsx(Qe,{className:"h-3 w-3 text-green-500"}),d&&e.jsx(Ns,{className:"h-3 w-3 text-destructive"}),!u&&e.jsx(me,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${s?"rotate-180":""}`})]}),c&&e.jsx("span",{className:`text-paragraph-sm pl-4.5 ${d?"text-destructive/70":"text-muted-foreground/70"}`,children:c})]}),s&&!u&&e.jsxs("div",{className:"mt-2 text-sm border border-border rounded-lg bg-card overflow-hidden w-full",children:[e.jsxs("div",{className:"p-3 border-b border-border",children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Hook Details"}),e.jsxs("div",{className:"space-y-1 text-[11px]",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"text-foreground font-mono",children:t.hookType})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Callback:"}),e.jsx("span",{className:"text-foreground font-mono",children:t.callback})]}),t.threshold!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Threshold:"}),e.jsxs("span",{className:"text-foreground",children:[t.threshold,"%"]})]}),t.currentPercentage!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context Usage:"}),e.jsxs("span",{className:"text-foreground",children:[t.currentPercentage.toFixed(1),"%"]})]})]})]}),t.metadata&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0",children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Result"}),e.jsxs("div",{className:"space-y-1 text-[11px]",children:[t.metadata.action&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Action:"}),e.jsx("span",{className:"text-foreground",children:t.metadata.action})]}),t.metadata.messagesRemoved!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Messages Removed:"}),e.jsx("span",{className:"text-foreground",children:ke(t.metadata.messagesRemoved)})]}),t.metadata.tokensSaved!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tokens Saved:"}),e.jsx("span",{className:"text-green-500 font-medium",children:ke(t.metadata.tokensSaved)})]}),t.metadata.originalTokens!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Original Size:"}),e.jsxs("span",{className:"text-foreground",children:[ke(t.metadata.originalTokens)," ","tokens"]})]}),t.metadata.finalTokens!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Final Size:"}),e.jsxs("span",{className:"text-foreground",children:[ke(t.metadata.finalTokens)," tokens"]})]})]})]}),g&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0 bg-yellow-500/5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-bold text-yellow-600 dark:text-yellow-500 uppercase tracking-wider mb-1.5 font-sans",children:[e.jsx(bn,{className:"h-3 w-3"}),"Warning"]}),e.jsx("div",{className:"text-[11px] text-yellow-700 dark:text-yellow-400",children:g})]}),t.error&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0",children:[e.jsx("div",{className:"text-[10px] font-bold text-destructive uppercase tracking-wider mb-1.5 font-sans",children:"Error"}),e.jsx("div",{className:"text-[11px] text-destructive font-mono",children:t.error})]}),e.jsxs("div",{className:"p-2 bg-muted/50 border-t border-border text-[10px] text-muted-foreground font-sans space-y-0.5",children:[t.triggeredAt&&e.jsxs("div",{children:["Started:"," ",new Date(t.triggeredAt).toLocaleTimeString()]}),t.completedAt&&e.jsxs("div",{children:["Completed:"," ",new Date(t.completedAt).toLocaleTimeString()]}),t.triggeredAt&&t.completedAt&&e.jsxs("div",{children:["Duration:"," ",((t.completedAt-t.triggeredAt)/1e3).toFixed(1),"s"]})]})]})]})}const ei=l.forwardRef(({className:t,...s},n)=>e.jsx(ds,{ref:n,className:y("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));ei.displayName=ds.displayName;function ut({content:t,className:s}){if(!t)return null;const n={table:({node:a,...o})=>e.jsx("div",{className:"overflow-x-auto my-4",children:e.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...o})}),thead:({node:a,...o})=>e.jsx("thead",{className:"bg-card border-b border-border",...o}),tbody:({node:a,...o})=>e.jsx("tbody",{...o}),tr:({node:a,...o})=>e.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...o}),th:({node:a,...o})=>e.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...o}),td:({node:a,...o})=>e.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...o}),input:({node:a,checked:o,...i})=>i.type==="checkbox"?e.jsx("input",{type:"checkbox",checked:o||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...i}):e.jsx("input",{...i}),code:({node:a,...o})=>o.className?.includes("language-")?e.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-code text-foreground",...o}):e.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code text-foreground",...o}),pre:({node:a,...o})=>e.jsx("pre",{className:"my-4",...o}),h1:({node:a,...o})=>e.jsx("h1",{className:"text-heading-3 mt-6 mb-4 text-foreground",...o}),h2:({node:a,...o})=>e.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground",...o}),h3:({node:a,...o})=>e.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...o}),ul:({node:a,...o})=>{const i=a?.children?.some(r=>typeof r=="object"&&r!==null&&"type"in r&&r.type==="element"&&"tagName"in r&&r.tagName==="li"&&"children"in r&&Array.isArray(r.children)&&r.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 e.jsx("ul",{className:y("my-2 space-y-1 text-foreground",i?"list-none space-y-2":"list-disc list-inside"),...o})},ol:({node:a,...o})=>e.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...o}),li:({node:a,...o})=>{const i=a?.children?.some(r=>typeof r=="object"&&r!==null&&"type"in r&&r.type==="element"&&"tagName"in r&&r.tagName==="input"&&"properties"in r&&typeof r.properties=="object"&&r.properties!==null&&"type"in r.properties&&r.properties.type==="checkbox");return e.jsx("li",{className:y("flex items-start",i?"gap-2":"ml-2"),...o})},a:({node:a,...o})=>e.jsx("a",{className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",...o}),p:({node:a,...o})=>e.jsx("p",{className:"my-2 text-foreground leading-relaxed",...o}),blockquote:({node:a,...o})=>e.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2",...o})};return e.jsx("div",{className:y("markdown-content prose prose-sm max-w-none dark:prose-invert",s),children:e.jsx(Da,{remarkPlugins:[En],components:n,children:t})})}const ti=ue("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"}}),ja=l.forwardRef(({message:t,role:s,layout:n,className:a,children:o,messageId:i,autoScroll:r,isLastMessage:u=!1,...p},d)=>{const c=t?t.role:s||"assistant",g=t?t.id:i,m=l.useRef(null),[x,h]=l.useState(void 0);return l.useImperativeHandle(d,()=>m.current),l.useEffect(()=>{if(!u||c!=="assistant"){h(void 0);return}const f=()=>{const b=m.current;if(!b)return;let j=b.parentElement;for(;j&&!j.classList.contains("overflow-y-auto");)j=j.parentElement;if(!j)return;const N=b.previousElementSibling;if(!N||N.getAttribute("aria-label")!=="user message"){h(void 0);return}const R=j.clientHeight,C=N.offsetHeight,L=Math.max(0,R-C-32);h(L)};f();const v=new ResizeObserver(f);if(m.current){v.observe(m.current);let b=m.current.parentElement;for(;b&&!b.classList.contains("overflow-y-auto");)b=b.parentElement;b&&v.observe(b)}return()=>v.disconnect()},[u,c]),l.useEffect(()=>{if((r!==void 0?r:c==="user")&&m.current){const v=setTimeout(()=>{m.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(v)}},[c,r]),e.jsx("article",{ref:m,"aria-label":`${c} message`,"data-message-id":g,className:y(ti({role:c,layout:n}),a),style:{minHeight:x!==void 0?`${x}px`:void 0},...p,children:o})});ja.displayName="Message";const si={Read:{active:"Reading {file}",past:"Read {file}",paramKey:"file_path"},Write:{active:"Writing {file}",past:"Wrote {file}",paramKey:"file_path"},Grep:{active:"Searching for {query}",past:"Searched for {query}",paramKey:"pattern"},WebSearch:{active:"Searching the web for {query}",past:"Searched the web for {query}",paramKey:"query"},WebFetch:{active:"Fetching {url}",past:"Fetched {url}",paramKey:"url"},read_file:{active:"Reading {file}",past:"Read {file}",paramKey:"target_file"},write:{active:"Writing {file}",past:"Wrote {file}",paramKey:"file_path"},grep:{active:"Searching for {query}",past:"Searched for {query}",paramKey:"pattern"},web_search:{active:"Searching the web for {query}",past:"Searched the web for {query}",paramKey:"search_term"},search_replace:{active:"Editing {file}",past:"Edited {file}",paramKey:"file_path"},delete_file:{active:"Deleting {file}",past:"Deleted {file}",paramKey:"target_file"},codebase_search:{active:"Searching codebase for {query}",past:"Searched codebase for {query}",paramKey:"query"},glob_file_search:{active:"Finding files matching {pattern}",past:"Found files matching {pattern}",paramKey:"glob_pattern"},run_terminal_cmd:{active:"Running {command}",past:"Ran {command}",paramKey:"command"},list_dir:{active:"Listing {directory}",past:"Listed {directory}",paramKey:"target_directory"},edit_notebook:{active:"Editing notebook",past:"Edited notebook"},read_lints:{active:"Reading linter errors",past:"Read linter errors"},todo_write:{active:"Updating to-do's",past:"Updated to-do's"}};function ai(t,s){if(!s||!t.rawInput)return null;const n=t.rawInput[s];return typeof n=="string"?n:null}function ni(t,s){let n=t;for(const[a,o]of Object.entries(s))n=n.replace(`{${a}}`,o);return n}function oi(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function He(t,s){const n=t.verbiage||si[t.title];if(!n){const o=t.prettyName||t.title;return s==="active"?`Using ${o}`:`Used ${o}`}const a=s==="active"?n.active:n.past;if(n.paramKey){const o=ai(t,n.paramKey);if(o){const i=oi(o,50);let r="value";return n.paramKey.includes("file")||n.paramKey.includes("path")?r="file":n.paramKey.includes("query")||n.paramKey.includes("pattern")?r="query":n.paramKey.includes("command")?r="command":n.paramKey.includes("directory")&&(r="directory"),ni(a,{[r]:i})}}if(t.subline){const o=a.split("{")[0];return o?`${o.trim()} ${t.subline}`:t.subline}return a.replace(/\s*\{[^}]+\}/g,"")}function ri(t){return t.prettyName||t.title}function Ne(t){return t.status==="pending"&&(!t.rawInput||Object.keys(t.rawInput).length===0)}function ot(t){return t.status==="failed"||t.error?"failed":t.status==="completed"?"completed":Ne(t)?"selecting":(t.status==="pending"||t.status==="in_progress","executing")}function Na(t){switch(ot(t)){case"selecting":return`Selecting ${t.prettyName||t.title}`;case"executing":return He(t,"active");case"completed":return He(t,"past");case"failed":return`Failed to use ${t.prettyName||t.title}`;default:return t.prettyName||t.title}}function ii(t){return t.every(s=>ot(s)==="completed")}function li(t){return t.some(s=>ot(s)==="failed")}function ci(t){return li(t)?"failed":ii(t)?"completed":t.every(s=>Ne(s))?"selecting":"executing"}const Vt=ue("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"}}),di=ue("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Sa=l.forwardRef(({content:t,isStreaming:s=!1,mode:n="collapsible",defaultExpanded:a=!1,autoExpand:o=!1,autoCollapse:i=!0,autoCollapseDelay:r=2e3,label:u="Thinking",variant:p,className:d},c)=>{const[g,m]=l.useState(n==="inline"?!0:a),[x,h]=l.useState(!1);return l.useEffect(()=>{if(i&&!s&&t&&n==="collapsible"){const f=setTimeout(()=>{h(!0),m(!1)},r);return()=>clearTimeout(f)}},[s,t,i,r,n]),l.useEffect(()=>{o&&s&&n==="collapsible"&&!x&&m(!0)},[o,s,n,x]),!t&&!s?null:n==="inline"?e.jsxs("div",{ref:c,className:y(Vt({variant:p}),"p-3",d),children:[e.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[e.jsx("span",{className:"text-caption font-medium text-foreground opacity-60 uppercase tracking-wide",children:u}),s&&e.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse"})]}),e.jsxs("div",{className:"text-paragraph-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[t,s&&t&&e.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):e.jsxs("div",{ref:c,className:y("mb-3",d),children:[e.jsxs("button",{type:"button",onClick:()=>{m(!g),h(!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":g,"aria-label":`${g?"Collapse":"Expand"} reasoning`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"text-caption font-medium text-foreground opacity-60 uppercase tracking-wide shrink-0",children:u}),s&&e.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!g&&t&&e.jsxs("span",{className:"text-caption text-foreground opacity-50 truncate",children:[t.substring(0,60),t.length>60&&"..."]})]}),e.jsx(me,{className:di({expanded:g}),"aria-hidden":"true"})]}),g&&e.jsx("div",{className:y(Vt({variant:p}),"mt-2 p-3 animate-fadeIn"),children:e.jsxs("div",{className:"text-paragraph-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[t,s&&t&&e.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});Sa.displayName="Reasoning";const je=l.memo(l.forwardRef(({content:t,isStreaming:s=!1,showEmpty:n=!0,emptyMessage:a="",className:o,...i},r)=>!t&&s&&n?e.jsx("div",{ref:r,className:y("opacity-70 italic text-paragraph-sm",o),...i,children:a}):t?e.jsx("div",{ref:r,...i,children:e.jsx(Ha,{className:y("size-full","[&>*:first-child]:mt-0 [&>*:last-child]:mb-0","[&_code]:whitespace-pre-wrap [&_code]:break-words","[&_pre]:max-w-full [&_pre]:overflow-x-auto",o),children:t})}):null),(t,s)=>t.content===s.content);je.displayName="Response";function ui(t){if(!t.rawInput)return null;const s=["query","search_term","pattern","target_file","file_path","command","target_directory"];for(const n of s){const a=t.rawInput[n];if(typeof a=="string"&&a.trim())return a.trim()}return t.subline?t.subline:null}function mt(t,s=3){if(t.length===0)return"";if(t.length===1)return t[0];if(t.length<=s)return t.slice(0,-1).join(", ")+" and "+t[t.length-1];const n=t.slice(0,s),a=t.length-s;return n.join(", ")+` and ${a} more`}function pi(t){if(t.length===0)return null;const s=t[0],n=s.lastIndexOf("/");if(n===-1)return null;const a=s.substring(0,n);return t.every(i=>i.startsWith(a+"/"))?a:null}function mi(t,s){if(t.length===0)return"";if(t.length===1)return He(t[0],s);const n=t[0],a=n.title,o=t.map(ui).filter(d=>d!==null);if((a==="Read"||a==="Write"||a==="read_file"||a==="write"||a==="search_replace"||a==="delete_file")&&o.length>0){const d=pi(o);if(d){const g=s==="active"?"working on":"worked on";return`${g.charAt(0).toUpperCase()+g.slice(1)} ${o.length} files in ${d}`}return`${a==="Read"||a==="read_file"?s==="active"?"Reading":"Read":a==="Write"||a==="write"?s==="active"?"Writing":"Wrote":a==="search_replace"?s==="active"?"Editing":"Edited":s==="active"?"Deleting":"Deleted"} ${mt(o)}`}if((a==="WebSearch"||a==="Grep"||a==="web_search"||a==="codebase_search"||a==="grep")&&o.length>0)return`${a==="WebSearch"||a==="web_search"?s==="active"?"Searching the web for":"Searched the web for":a==="codebase_search"?s==="active"?"Searching codebase for":"Searched codebase for":s==="active"?"Searching for":"Searched for"} ${mt(o)}`;const u=ri(n);return`${s==="active"?"Using":"Used"} ${u} ${t.length} times`}function fi(t,s){if(t.length===0)return"";if(t.length===1)return He(t[0],s);if([...new Set(t.map(i=>i.title))].length===1)return mi(t,s);const a=t.map(i=>i.prettyName||i.title).filter((i,r,u)=>u.indexOf(i)===r);return`${s==="active"?"Running":"Ran"} ${mt(a)}`}const gi=50;function ka({port:t,sessionId:s,host:n,parentStatus:a,agentName:o,query:i,isExpanded:r,onExpandChange:u,storedMessages:p,isReplay:d=!1}){const[c,g]=l.useState(!1),m=r??c,[x,h]=l.useState(!0),[f,v]=l.useState(!0),b=l.useRef(null),N=!d&&t!==void 0&&s!==void 0?{port:t,sessionId:s,...n!==void 0?{host:n}:{}}:null,{messages:R,isStreaming:C,error:M}=Jn(N),L=p&&p.length>0?p:R,O=d?!1:a==="in_progress"||a==="pending"||C,U=L[L.length-1],K=U&&(U.content||U.toolCalls&&U.toolCalls.length>0||U.contentBlocks&&U.contentBlocks.length>0),E=l.useRef(O);l.useEffect(()=>{E.current&&!O&&h(!1),E.current=O},[O]);const F=l.useCallback(()=>{const k=b.current;if(!k)return;const{scrollTop:_,scrollHeight:I,clientHeight:S}=k,$=I-_-S;v($<gi)},[]),H=l.useCallback(()=>{const k=b.current;k&&(k.scrollTop=k.scrollHeight)},[]);l.useEffect(()=>{f&&(O||K)&&H()},[U?.content,U?.toolCalls,f,O,K,H]),l.useEffect(()=>{const k=b.current;if(!k)return;const _=()=>F();return k.addEventListener("scroll",_,{passive:!0}),F(),()=>k.removeEventListener("scroll",_)},[F,x,m]),l.useEffect(()=>{x&&(v(!0),requestAnimationFrame(()=>{H()}))},[x,H]);const G=U?.content&&U.content.split(`
8
- `).filter(Boolean).pop()||"",Q=G.length>100?`${G.slice(0,100)}...`:G,T=i?(i.split(`
9
- `)[0]??"").slice(0,100)+(i.length>100?"...":""):"";return e.jsxs("div",{children:[!m&&e.jsx("div",{className:"w-full max-w-md",children:Q?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:Q}):T?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate",children:T}):null}),m&&e.jsxs("div",{className:"space-y-3",children:[(o||i)&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Input"}),e.jsxs("div",{className:"text-[11px] font-mono space-y-1",children:[o&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"agentName: "}),e.jsx("span",{className:"text-foreground",children:o})]}),i&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"query: "}),e.jsx("span",{className:"text-foreground",children:i})]})]})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>h(!x),className:"flex items-center gap-2 cursor-pointer bg-transparent border-none p-0 text-left group",children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider font-sans",children:"Stream"}),e.jsx(me,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${x?"rotate-180":""}`})]}),x&&e.jsxs("div",{ref:b,className:"mt-2 rounded-md overflow-hidden bg-muted/30 border border-border/50 max-h-[200px] overflow-y-auto",children:[M&&e.jsxs("div",{className:"px-2 py-2 text-[11px] text-destructive",children:["Error: ",M]}),!M&&!K&&O&&e.jsx("div",{className:"px-2 py-2 text-[11px] text-muted-foreground",children:"Waiting for sub-agent response..."}),U&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[U.contentBlocks&&U.contentBlocks.length>0?U.contentBlocks.map((k,_)=>k.type==="text"?e.jsx("div",{className:"text-[11px] text-foreground prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(ut,{content:k.text})},`text-${_}`):e.jsx(hi,{toolCall:k.toolCall},k.toolCall.id)):U.content&&e.jsx("div",{className:"text-[11px] text-foreground prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(ut,{content:U.content})}),U.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!O&&U?.content&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Output"}),e.jsx("div",{className:"text-[11px] text-foreground max-h-[200px] overflow-y-auto rounded-md bg-muted/30 border border-border/50 px-2 py-2 prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(ut,{content:U.content})})]})]})]})}function hi({toolCall:t}){const s={pending:"...",in_progress:"",completed:"",failed:""}[t.status],n={pending:"text-muted-foreground",in_progress:"text-blue-500",completed:"text-green-500",failed:"text-destructive"}[t.status];return e.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:n,children:s}),e.jsx("span",{className:"font-medium",children:t.prettyName||t.title}),t.status==="in_progress"&&e.jsx(xt,{className:"h-2.5 w-2.5 animate-spin"})]})}const xi={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Ca=l.createContext(xi);function bi({children:t,defaultTheme:s="system",storageKey:n="vite-ui-theme"}){const[a,o]=l.useState(()=>localStorage.getItem(n)||s),[i,r]=l.useState("light");l.useEffect(()=>{const p=window.document.documentElement;if(p.classList.remove("light","dark"),a==="system"){const d=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";p.classList.add(d),r(d);return}p.classList.add(a),r(a)},[a]);const u={theme:a,setTheme:p=>{localStorage.setItem(n,p),o(p)},resolvedTheme:i};return e.jsx(Ca.Provider,{value:u,children:t})}const At=()=>{const t=l.useContext(Ca);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function yi({todos:t,className:s}){if(!t||t.length===0)return null;const n=l.useMemo(()=>{const o=t.find(r=>r.status==="in_progress");if(o)return o;const i=t.find(r=>r.status==="completed");return i||t[0]},[t]);if(!n)return null;const a=n.status==="in_progress"&&n.activeForm||n.content;return e.jsxs("span",{className:y("flex items-center gap-1.5",s),children:[n.status==="completed"?e.jsx(Qe,{className:"size-3 text-muted-foreground shrink-0"}):n.status==="in_progress"?e.jsx("span",{className:"size-2 rounded-full bg-foreground animate-pulse-scale shrink-0"}):e.jsx(Ge,{className:"size-3 text-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:a})]})}const qt={Globe:Cn,Image:kn,Link:Sn,Cloud:Nn,CheckSquare:Ye,Search:jn,FileText:ht,Edit:wn,Wrench:vn,BrainCircuit:yn,CircleDot:bt};function he({toolCalls:t,isGrouped:s=!1,autoMinimize:n=!0,hookNotifications:a=[]}){const[o,i]=l.useState(!1),[r,u]=l.useState(!1),[p,d]=l.useState(!1),{resolvedTheme:c}=At(),g=Gt(),m=t.length===1?t[0]:null,x=m?.title==="todo_write",h=m?a.find(T=>T.toolCallId===m.id):void 0,f=!!(m?.subagentPort&&m?.subagentSessionId),v=!!(m?.subagentMessages&&m.subagentMessages.length>0),b=f||v,j=v,[N,R]=l.useState(!1),C=pt.useContext(_t),M=s?ci(t):m?ot(m):"executing",L=M==="completed",O=M==="failed",U=M==="selecting",K=M==="executing";l.useEffect(()=>{if(n&&L&&!r&&!p){const T=setTimeout(()=>{u(!0),i(!1)},500);return()=>clearTimeout(T)}},[n,L,r,p]);const E=pt.useCallback(()=>{x&&C&&m?C.panelSize!=="hidden"&&C.activeTab==="todo"?C.setPanelSize("hidden"):(C.setPanelSize("small"),C.setActiveTab("todo")):b?(d(!0),R(!N)):(d(!0),i(!o),r&&u(!1))},[x,C,o,r,m,b,N]),H=s?$t:m?.icon&&qt[m.icon]?qt[m.icon]:bt,Q=s?fi(t,L?"past":"active"):m?Na(m):"Tool operation";return U&&!s?e.jsx(Y.div,{className:"flex flex-col my-4 rounded-md px-1 -mx-1 w-fit",animate:{backgroundPosition:["200% 0","-200% 0"]},transition:{...ze,duration:$e(g??!1,1.5)},style:{backgroundImage:"linear-gradient(90deg, transparent 5%, rgba(255, 255, 255, 0.75) 25%, transparent 35%)",backgroundSize:"200% 100%"},children:e.jsx("span",{className:"text-paragraph-sm text-text-secondary/50",children:Q})}):U&&s?e.jsxs(Y.div,{className:"flex flex-col my-4 rounded-md px-1 -mx-1 w-fit",animate:{backgroundPosition:["200% 0","-200% 0"]},transition:{...ze,duration:$e(g??!1,1.5)},style:{backgroundImage:"linear-gradient(90deg, transparent 5%, rgba(255, 255, 255, 0.75) 25%, transparent 35%)",backgroundSize:"200% 100%"},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"text-text-secondary/70",children:e.jsx($t,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Selecting tools"}),e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-text-secondary/70",children:t.length})]}),e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:Q})]}):e.jsxs(Y.div,{className:"flex flex-col my-4",initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(g??!1,{duration:.5,ease:X.smooth}),children:[e.jsxs(Y.button,{type:"button",className:"flex flex-col items-start gap-0.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit rounded-md px-1 -mx-1",onClick:E,"aria-expanded":x?void 0:o,animate:K||U?{backgroundPosition:["200% 0","-200% 0"]}:{},transition:K||U?{...ze,duration:$e(g??!1,1.5)}:{},style:K||U?{backgroundImage:"linear-gradient(90deg, transparent 5%, rgba(255, 255, 255, 0.75) 25%, transparent 35%)",backgroundSize:"200% 100%"}:{},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:e.jsx(H,{className:"h-3 w-3"})}),e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:[s&&e.jsx("span",{className:"mr-1",children:"Parallel operation"}),!s&&Q]}),s&&e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-text-secondary/70",children:t.length}),O&&e.jsx(Ns,{className:"h-3 w-3 text-destructive"}),x?e.jsx(_e,{className:"h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors"}):e.jsx(Y.div,{animate:{rotate:o?180:0},transition:te(g??!1,{duration:Be.normal,ease:X.smooth}),className:"h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:e.jsx(me,{className:"h-3 w-3"})})]}),!s&&m&&(x&&m.rawInput?.todos?e.jsx(yi,{todos:m.rawInput.todos,className:"text-paragraph-sm text-text-secondary/70 pl-4.5"}):m.subline?e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:m.subline}):null),!s&&h&&e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:h.status==="triggered"?"Compacting response...":h.status==="completed"?h.metadata?.action==="no_action_needed"?`Response checked (${h.currentPercentage?.toFixed(0)}% context)`:h.metadata?.tokensSaved?`Response compacted (${(h.metadata.tokensSaved/(h.metadata.originalTokens||1)*100).toFixed(0)}% reduced)`:"Response compacted":h.status==="error"?`Compaction error: ${h.error}`:null}),s&&!o&&e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:Q}),s&&a.length>0&&(()=>{const T=a.filter(_=>_.status==="completed"&&_.metadata?.action!=="no_action_needed").length,k=a.filter(_=>_.status==="triggered").length;return k>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:["Compacting ",k," response",k>1?"s":"","..."]}):T>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:[T," response",T>1?"s":""," ","compacted"]}):null})()]}),!x&&b&&m&&e.jsx("div",{className:"pl-4.5 mt-2",children:e.jsx(ka,{port:m.subagentPort,sessionId:m.subagentSessionId,parentStatus:m.status,agentName:m.rawInput?.agentName,query:m.rawInput?.query,isExpanded:N,onExpandChange:R,storedMessages:m.subagentMessages,isReplay:j})}),e.jsx(Ie,{initial:!1,children:!x&&o&&e.jsx(Y.div,{initial:"collapsed",animate:"expanded",exit:"collapsed",variants:Cr,transition:te(g??!1,{duration:Be.normal,ease:X.smooth}),className:"mt-1",children:s?e.jsx("div",{className:"flex flex-col gap-4 mt-2",children:t.map(T=>{const k=a.find(_=>_.toolCallId===T.id);return e.jsx(vi,{toolCall:T,...k?{hookNotification:k}:{}},T.id)})}):m&&e.jsx(Ta,{toolCall:m,...h?{hookNotification:h}:{}})},"expanded-content")})]})}function vi({toolCall:t,hookNotification:s}){const[n,a]=l.useState(!1),o=!!(t.subagentPort&&t.subagentSessionId),i=!!(t.subagentMessages&&t.subagentMessages.length>0),r=o||i,u=i;return r?e.jsxs("div",{className:"flex flex-col ml-5",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>a(!n),"aria-expanded":n,children:[e.jsx("div",{className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:e.jsx(bt,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:t.rawInput?.agentName||"Subagent"}),e.jsx(me,{className:`h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors transition-transform duration-200 ${n?"rotate-180":""}`})]}),e.jsx("div",{className:"pl-4.5",children:e.jsx(ka,{port:t.subagentPort,sessionId:t.subagentSessionId,parentStatus:t.status,agentName:t.rawInput?.agentName,query:t.rawInput?.query,isExpanded:n,onExpandChange:a,storedMessages:t.subagentMessages,isReplay:u})})]}):e.jsx("div",{className:"flex items-start gap-1.5",children:e.jsx("div",{className:"flex-1 ml-5",children:e.jsx(Ta,{toolCall:t,...s?{hookNotification:s}:{}})})})}function Ta({toolCall:t,hookNotification:s}){const{resolvedTheme:n}=At();if(Ne(t))return e.jsx("div",{className:"text-paragraph-sm text-text-secondary/70 ml-2",children:Na(t)});const a={fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit","--w-rjv-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-key-string":n==="dark"?"#fafafa":"#09090b","--w-rjv-background-color":"transparent","--w-rjv-line-color":n==="dark"?"#27272a":"#e4e4e7","--w-rjv-arrow-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-edit-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-info-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-update-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-success-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-curlybraces-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-colon-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-brackets-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-string-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-type-string-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-type-int-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-float-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-bigint-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-boolean-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-date-color":n==="dark"?"#ec4899":"#db2777","--w-rjv-type-url-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-null-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-nan-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-undefined-color":n==="dark"?"#ef4444":"#dc2626"};return e.jsxs("div",{className:"text-sm border border-border rounded-lg bg-card overflow-hidden w-full",children:[t.locations&&t.locations.length>0&&e.jsxs("div",{className:"p-3 border-b border-border",children:[e.jsx("div",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider mb-1.5 font-sans",children:"Files"}),e.jsx("ul",{className:"space-y-1",children:t.locations.map(o=>e.jsxs("li",{className:"font-mono text-[11px] text-foreground bg-muted px-1.5 py-0.5 rounded w-fit",children:[o.path,o.line!==null&&o.line!==void 0&&`:${o.line}`]},`${o.path}:${o.line??""}`))})]}),t.rawInput&&Object.keys(t.rawInput).length>0&&e.jsxs("div",{className:"p-3 border-b border-border",children:[e.jsx("div",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider mb-1.5 font-sans",children:"Input"}),e.jsx("div",{className:"text-[11px] font-mono text-foreground",children:e.jsx(Ut,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:a})})]}),(t.content&&t.content.length>0||t.error)&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0",children:[e.jsx("div",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider mb-1.5 font-sans",children:"Output"}),e.jsxs("div",{className:"space-y-2 text-[11px] text-foreground",children:[t.content?.map((o,i)=>{const r=()=>o.type==="diff"&&"path"in o?`diff-${o.path}-${i}`:o.type==="terminal"&&"terminalId"in o?`terminal-${o.terminalId}`:o.type==="text"&&"text"in o?`text-${o.text.substring(0,20)}-${i}`:o.type==="content"&&"content"in o?`content-${o.content.text?.substring(0,20)}-${i}`:`block-${i}`,u=(p,d)=>{try{const c=JSON.parse(p);if(typeof c=="object"&&c!==null)return e.jsx("div",{className:"text-[11px]",children:e.jsx(Ut,{value:c,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:a})},d)}catch{}return e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-foreground overflow-x-auto",children:p},d)};if(o.type==="content"&&"content"in o){const p=o.content;if(p.type==="text"&&p.text)return u(p.text,r())}if(o.type==="text"&&"text"in o)return u(o.text,r());if(o.type==="image"){const p=o.alt||"Generated image";let d;if("data"in o)d=`data:${o.mimeType||"image/png"};base64,${o.data}`;else if("url"in o)d=o.url;else return null;return e.jsx("div",{className:"my-2",children:e.jsx("img",{src:d,alt:p,className:"max-w-full h-auto rounded-md border border-border"})},r())}return o.type==="diff"&&"path"in o&&"oldText"in o&&"newText"in o?e.jsxs("div",{className:"border border-border rounded bg-card",children:[e.jsxs("div",{className:"bg-muted px-2 py-1 text-[10px] font-mono text-text-secondary border-b border-border",children:[o.path,"line"in o&&o.line!==null&&o.line!==void 0&&`:${o.line}`]}),e.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"text-red-500 dark:text-red-400",children:["- ",o.oldText]}),e.jsxs("div",{className:"text-green-500 dark:text-green-400",children:["+ ",o.newText]})]})]},r()):null}),t.error&&e.jsxs("div",{className:"text-destructive font-mono text-[11px] mt-2",children:["Error: ",t.error]})]})]}),t._meta?.truncationWarning&&e.jsxs("div",{className:"mx-3 mt-3 mb-0 flex items-center gap-2 rounded-md bg-yellow-50 dark:bg-yellow-950/20 px-3 py-2 text-[11px] text-yellow-800 dark:text-yellow-200 border border-yellow-200 dark:border-yellow-900",children:[e.jsx("span",{className:"text-yellow-600 dark:text-yellow-500",children:"⚠️"}),e.jsx("span",{children:t._meta.truncationWarning})]}),s&&s.status==="completed"&&s.metadata?.action!=="no_action_needed"&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0",children:[e.jsx("div",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider mb-1.5 font-sans",children:"Response Compaction"}),e.jsxs("div",{className:"space-y-1 text-[11px]",children:[s.metadata?.originalTokens!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-text-secondary",children:"Original:"}),e.jsxs("span",{className:"text-foreground",children:[s.metadata.originalTokens.toLocaleString()," ","tokens"]})]}),s.metadata?.finalTokens!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-text-secondary",children:"Compacted:"}),e.jsxs("span",{className:"text-foreground",children:[s.metadata.finalTokens.toLocaleString()," ","tokens"]})]}),s.metadata?.tokensSaved!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-text-secondary",children:"Saved:"}),e.jsxs("span",{className:"text-green-500 font-medium",children:[s.metadata.tokensSaved.toLocaleString()," ","tokens",s.metadata?.originalTokens&&e.jsxs("span",{className:"text-text-secondary font-normal ml-1",children:["(",(s.metadata.tokensSaved/s.metadata.originalTokens*100).toFixed(0),"% reduced)"]})]})]})]})]}),(t.tokenUsage||t.startedAt)&&e.jsxs("div",{className:"p-2 bg-muted/50 border-b border-border last:border-0 flex flex-wrap gap-4 text-[10px] text-text-secondary font-sans",children:[t.tokenUsage&&e.jsxs("div",{className:"flex gap-3",children:[t.tokenUsage.inputTokens!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Input:"}),t.tokenUsage.inputTokens.toLocaleString()]}),t.tokenUsage.outputTokens!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Output:"}),t.tokenUsage.outputTokens.toLocaleString()]}),t.tokenUsage.totalTokens!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Total:"}),t.tokenUsage.totalTokens.toLocaleString()]})]}),t.startedAt&&e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsxs("span",{children:["Started: ",new Date(t.startedAt).toLocaleTimeString()]}),t.completedAt&&e.jsxs("span",{children:["Completed:"," ",new Date(t.completedAt).toLocaleTimeString()," (",Math.round((t.completedAt-t.startedAt)/1e3),"s)"]})]})]})]})}const wi=ue("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"}}),Ia=l.forwardRef(({role:t,variant:s,isStreaming:n,message:a,thinkingDisplayStyle:o="collapsible",className:i,children:r,...u},p)=>{const d=P(f=>f.streamingStartTime);P(f=>f.currentModel);const c=Gt(),g=a&&!r,m=g?a.role:t||"assistant",x=g?a.isStreaming:n;let h=r;if(g){const f=a.metadata?.thinking,v=!!f,b=a.isStreaming&&!a.content&&a.role==="assistant";h=e.jsxs(e.Fragment,{children:[a.role==="assistant"&&v&&e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.5,ease:X.smooth}),children:e.jsx(Sa,{content:f,isStreaming:a.isStreaming,mode:o,autoCollapse:!0})}),b&&d&&e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:e.jsx(Y.div,{className:"flex flex-col my-4 rounded-md px-1 -mx-1 w-fit",animate:{backgroundPosition:["-200% 0","200% 0"]},transition:{...ze,duration:$e(c??!1,1.5)},style:{backgroundImage:"linear-gradient(90deg, transparent 5%, rgba(255, 255, 255, 0.75) 25%, transparent 35%)",backgroundSize:"200% 100%"},children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Thinking..."})})})}),a.role==="assistant"?(()=>{const j=(a.toolCalls||[]).slice().sort((T,k)=>(T.contentPosition??1/0)-(k.contentPosition??1/0)),N=T=>{const k=[],_=new Map;let I=[],S=[],$=null;const V=()=>{I.length>1?k.push({type:"selecting",toolCalls:I}):I.length===1&&k.push(I[0]),I=[]},oe=()=>{S.length>1?k.push({type:"batch",toolCalls:S}):S.length===1&&k.push(S[0]),S=[],$=null};for(const B of T)if(B.batchId){V(),oe();const Z=_.get(B.batchId);if(Z)Z.push(B);else{const Pe=[B];_.set(B.batchId,Pe),k.push({type:"batch",toolCalls:Pe})}}else Ne(B)?(oe(),I.push(B)):(V(),$===B.title?S.push(B):(oe(),S=[B],$=B.title));return V(),oe(),k},R=(a.hookNotifications||[]).filter(T=>T.hookType==="tool_response"),C=(T,k)=>{if(typeof T=="object"&&"type"in T&&T.type==="batch"){const S=R.filter($=>T.toolCalls.some(V=>V.id===$.toolCallId));return e.jsx(he,{toolCalls:T.toolCalls,isGrouped:!0,hookNotifications:S},`batch-${T.toolCalls[0]?.batchId||k}`)}if(typeof T=="object"&&"type"in T&&T.type==="selecting")return e.jsx(he,{toolCalls:T.toolCalls,isGrouped:!0},`selecting-${T.toolCalls[0]?.id||k}`);const _=T,I=R.filter(S=>S.toolCallId===_.id);return e.jsx(he,{toolCalls:[_],isGrouped:!1,hookNotifications:I},_.id)},M=(a.hookNotifications||[]).filter(T=>T.hookType!=="tool_response").slice().sort((T,k)=>(T.contentPosition??1/0)-(k.contentPosition??1/0));if(j.length===0||!j.some(T=>T.contentPosition!==void 0)){const T=N(j);if(!M.some(S=>S.contentPosition!==void 0))return e.jsxs(e.Fragment,{children:[M.length>0&&e.jsx("div",{className:"flex flex-col gap-2 mb-1",children:M.map(S=>e.jsx(dt,{notification:S},S.id))}),T.length>0&&e.jsx(Ie,{mode:"popLayout",children:e.jsx("div",{className:"flex flex-col gap-2 mb-1",children:T.map((S,$)=>C(S,$))})}),e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:e.jsx(je,{content:a.content,isStreaming:a.isStreaming,showEmpty:!1})})]});const _=[];let I=0;if(M.forEach(S=>{const $=S.contentPosition??a.content.length;if($>I){const V=a.content.slice(I,$);V&&_.push(e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:e.jsx(je,{content:V,isStreaming:!1,showEmpty:!1})},`text-before-hook-${S.id}`))}_.push(e.jsx(dt,{notification:S},S.id)),I=$}),I<a.content.length){const S=a.content.slice(I);S&&_.push(e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:e.jsx(je,{content:S,isStreaming:a.isStreaming,showEmpty:!1})},"text-end-hooks"))}return T.length>0&&T.forEach((S,$)=>{_.push(C(S,$))}),e.jsx(Ie,{mode:"popLayout",children:_})}const L=[],O=[],U=j.filter(Ne);j.filter(T=>!Ne(T)).forEach(T=>{O.push({type:"toolCall",item:T,position:T.contentPosition??a.content.length})}),M.forEach(T=>{O.push({type:"hookNotification",item:T,position:T.contentPosition??0})}),O.sort((T,k)=>T.position-k.position);let E=0,F=[],H,G;const Q=()=>{F.length>1?L.push(e.jsx(he,{toolCalls:F,isGrouped:!0},`group-${H||G}-${F[0].id}`)):F.length===1&&L.push(e.jsx("div",{children:e.jsx(he,{toolCalls:[F[0]],isGrouped:!1})},`tool-${F[0].id}`)),F=[],H=void 0,G=void 0};if(O.forEach((T,k)=>{const _=T.position;if(_>E){Q();const I=a.content.slice(E,_);if(I){const S=(T.type==="toolCall",T.item.id);L.push(e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:e.jsx(je,{content:I,isStreaming:!1,showEmpty:!1})},`text-before-${S}`))}}if(T.type==="hookNotification")Q(),L.push(e.jsx(dt,{notification:T.item},T.item.id));else{const I=T.item;I.batchId?H===I.batchId?F.push(I):(Q(),H=I.batchId,G=I.title,F=[I]):G===I.title&&!H?F.push(I):(Q(),G=I.title,F=[I])}E=_,k===O.length-1&&Q()}),E<a.content.length){const T=a.content.slice(E);T&&L.push(e.jsx(Y.div,{initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:e.jsx(je,{content:T,isStreaming:a.isStreaming,showEmpty:!1})},"text-end"))}return U.length>0&&(U.length>1?L.push(e.jsx(he,{toolCalls:U,isGrouped:!0},`selecting-group-${U[0].id}`)):L.push(e.jsx("div",{children:e.jsx(he,{toolCalls:[U[0]],isGrouped:!1})},`tool-${U[0].id}`))),e.jsx(Ie,{mode:"popLayout",children:L})})():e.jsxs("div",{className:"flex flex-col gap-2",children:[a.images&&a.images.length>0&&e.jsx(Y.div,{className:"flex flex-wrap gap-2",initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.5,ease:X.smooth}),children:a.images.map((j,N)=>e.jsx("img",{src:`data:${j.mimeType};base64,${j.data}`,alt:`Attachment ${N+1}`,className:"max-w-[200px] max-h-[200px] rounded-lg object-cover"},N))}),a.content&&e.jsx(Y.div,{className:"whitespace-pre-wrap",initial:{filter:"blur(12px)",opacity:0,y:12},animate:{filter:"blur(0px)",opacity:1,y:0},exit:{filter:"blur(12px)",opacity:0,y:-12},transition:te(c??!1,{duration:.4,ease:X.smooth}),children:a.content})]})]})}return e.jsx("div",{ref:p,className:y(wi({role:m,variant:s}),x&&"animate-pulse-subtle",i),...u,children:h})});Ia.displayName="MessageContent";const Dt=l.forwardRef(({showIcons:t=!0,visibleTabs:s=["todo","files"],variant:n="default",className:a,...o},i)=>{const u=[{id:"todo",label:"To-do",icon:Ye},{id:"files",label:"Files",icon:ht},{id:"database",label:"Database",icon:ys},{id:"sources",label:"Sources",icon:vs},{id:"settings",label:"Settings",icon:ws}].filter(d=>s.includes(d.id)),p=n==="compact"?"gap-[4px]":"gap-3";return e.jsx(Re,{ref:i,className:y("w-full justify-start bg-transparent p-0 h-auto",p,a),...o,children:u.map(d=>{const c=d.icon;return e.jsxs(Ee,{value:d.id,className:y("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground hover:text-foreground transition-colors"),children:[t&&c&&e.jsx(c,{className:"size-4"}),d.label]},d.id)})})});Dt.displayName="PanelTabsHeader";const ji=l.forwardRef(({className:t,children:s,...n},a)=>e.jsxs(us,{ref:a,className:y("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",t),...n,children:[s,e.jsx(Za,{asChild:!0,children:e.jsx(Tn,{className:"h-4 w-4 opacity-50"})})]}));ji.displayName=us.displayName;const _a=l.forwardRef(({className:t,...s},n)=>e.jsx(ps,{ref:n,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(js,{className:"h-4 w-4"})}));_a.displayName=ps.displayName;const Ra=l.forwardRef(({className:t,...s},n)=>e.jsx(ms,{ref:n,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(me,{className:"h-4 w-4"})}));Ra.displayName=ms.displayName;const Ni=l.forwardRef(({className:t,children:s,position:n="popper",...a},o)=>e.jsx(en,{children:e.jsxs(fs,{ref:o,className:y("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",t),position:n,...a,children:[e.jsx(_a,{}),e.jsx(tn,{className:y("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(Ra,{})]})}));Ni.displayName=fs.displayName;const Si=l.forwardRef(({className:t,...s},n)=>e.jsx(gs,{ref:n,className:y("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));Si.displayName=gs.displayName;const ki=l.forwardRef(({className:t,children:s,...n},a)=>e.jsxs(hs,{ref:a,className:y("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",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(sn,{children:e.jsx(bs,{className:"h-4 w-4"})})}),e.jsx(an,{children:s})]}));ki.displayName=hs.displayName;const Ci=l.forwardRef(({className:t,...s},n)=>e.jsx(xs,{ref:n,className:y("-mx-1 my-1 h-px bg-muted",t),...s}));Ci.displayName=xs.displayName;function Ea({className:t}){const{toggleSidebar:s,open:n}=ye();return e.jsx(be,{className:y(t),"data-testid":"sidebar-toggle-button","data-state":n?"open":"closed",onClick:s,"aria-label":"Toggle sidebar",children:e.jsx(In,{className:"size-4 text-muted-foreground"})})}const Ma=l.forwardRef(({task:t,collapsible:s=!0,defaultExpanded:n=!1,onTaskClick:a,className:o,...i},r)=>{const[u,p]=l.useState(n),d=!!(t.details||t.files&&t.files.length>0),c={pending:Ge,in_progress:xt,completed:Qe}[t.status],g=()=>{switch(t.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},m=()=>{d&&s&&p(!u),a?.(t)};return e.jsxs("div",{ref:r,className:y("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",o),...i,children:[e.jsxs("button",{type:"button",onClick:m,className:y("w-full flex items-center gap-3 px-3 py-2.5 text-left",d&&s&&"cursor-pointer"),disabled:!d&&!s,children:[e.jsx(c,{className:y("w-4 h-4 shrink-0",g(),t.status==="in_progress"&&"animate-spin")}),e.jsx("span",{className:y("flex-1 text-paragraph-sm font-[var(--font-family)]",t.status==="completed"&&"line-through opacity-60",t.status==="in_progress"&&"font-medium"),children:t.text}),d&&s&&e.jsx(me,{className:y("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",u&&"rotate-180"),"aria-hidden":"true"})]}),d&&u&&e.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[t.details&&e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-80 leading-relaxed mb-2",children:t.details}),t.files&&t.files.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-caption font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),e.jsx("div",{className:"space-y-1",children:t.files.map(x=>e.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:x},x))})]})]})]})});Ma.displayName="Subagent";const Ti=l.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:n,emptyMessage:a="No subagents yet.",className:o,...i},r)=>e.jsx("div",{ref:r,className:y("space-y-2 max-h-96 overflow-y-auto",o),...i,children:t.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:a}):t.map(u=>e.jsx(Ma,{task:u,collapsible:s,...n?{onTaskClick:n}:{}},u.id))}));Ti.displayName="SubagentList";const Ii=ue("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"}}),_i=l.forwardRef(({className:t,autoResize:s=!1,maxHeight:n=200,variant:a,...o},i)=>{const r=l.useRef(null),u=l.useCallback(d=>{r.current=d,typeof i=="function"?i(d):i&&(i.current=d)},[i]),p=l.useCallback(()=>{const d=r.current;if(!d||!s)return;d.style.height="auto";const c=Math.min(d.scrollHeight,n);d.style.height=`${c}px`,d.scrollHeight>n?d.style.overflowY="auto":d.style.overflowY="hidden"},[s,n]);return l.useEffect(()=>{p()},[p]),e.jsx("textarea",{className:y(Ii({variant:a}),s&&"overflow-y-hidden",t),ref:u,...o})});_i.displayName="Textarea";function Aa(){const{setTheme:t}=At();return e.jsxs(jt,{children:[e.jsx(Nt,{asChild:!0,children:e.jsxs(be,{children:[e.jsx(_n,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Rn,{className:"absolute size-4 text-muted-foreground rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(Ze,{align:"end",children:[e.jsx(le,{onClick:()=>t("light"),children:"Light"}),e.jsx(le,{onClick:()=>t("dark"),children:"Dark"}),e.jsx(le,{onClick:()=>t("system"),children:"System"})]})]})}function Ri(){return"http://localhost:3100"}const Kt={agentServerUrl:Ri(),debuggerUrl:void 0};function Ei(){const{client:t,error:s,sessionId:n}=Hn({serverUrl:Kt.agentServerUrl});return e.jsx(bi,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(qr,{client:t,initialSessionId:n,error:s,...Kt.debuggerUrl})})}const Mi="bibliotecha_auth";function Ai(t){return document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`))?.[2]??null}async function Di(){new URLSearchParams(window.location.search).get("token"),Ai(Mi);const s=document.getElementById("root");if(!s)throw new Error("Root element not found");Pa.createRoot(s).render(e.jsx(pt.StrictMode,{children:e.jsx(Ei,{})}))}Di();
@@ -1 +0,0 @@
1
- import{g as i,e,f as k}from"./vendor-DXWxTThl.js";const c={};function d(s){const t=this,n=s||c,o=t.data(),r=o.micromarkExtensions||(o.micromarkExtensions=[]),a=o.fromMarkdownExtensions||(o.fromMarkdownExtensions=[]),m=o.toMarkdownExtensions||(o.toMarkdownExtensions=[]);r.push(i(n)),a.push(e()),m.push(k(n))}export{d as r};