@townco/gui-template 0.1.65 → 0.1.67

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,P as qs,h as Gs,i as Qs,M as Ks,b as Fe,k as Js}from"./react-C-kc7QcQ.js";import{S as pe,L as Ys,M as st,N as te,O as U,P as O,Q as j,R as Ee,T as q,U as G,W as ce,X as Y,Y as X,Z as Xs,$ as ke,a0 as Oe,a1 as Zs,a2 as en,a3 as tn,a4 as de,a5 as sn,a6 as nn,a7 as nt}from"./vendor-BQECuh54.js";import{P as ot,a as on}from"./acp-sdk-DRjn3Sp9.js";import{S as ve,a as gt,b as ht,P as an,C as xt,I as bt,c as yt,d as vt,R as wt,L as jt,e as Nt,f as rn,T as ln,g as St,h as Ct,i as Tt,j as cn,k as kt,l as dn,m as un,n as pn,O as It,o as mn,p as Et,q as fn,r as Rt,D as _t,s as Mt,t as At,u as gn,v as Pt,w as Dt,x as hn,y as Ut,V as xn,z as Lt,A as zt,B as bn,E as yn,F as Ft}from"./radix-yQv6PSMx.js";import{c as he,S as vn,P as wn,d as jn,A as Nn,e as Ot,f as $e,F as Sn,g as Cn,h as Tn,E as kn,i as ie,j as $t,k as Re,l as Be,m as Bt,n as Ht,B as at,o as In,p as En,q as Wt,r as Rn,s as Vt,t as qt,u as Gt,v as Qt,w as Kt,W as _n,x as Mn,y as An,z as Pn,G as Dn,I as Un,H as Ln,J as zn,K as Fn,N as On,O as $n}from"./icons-C9l3jYlj.js";import{r as Bn}from"./markdown-Bw9Dl2td.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function o(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=o(r);fetch(r.href,i)}})();var Hn={};const je=typeof process<"u"&&process.versions?.node;let Wn,Vn=0;const qn=new Set;function Gn(t){for(const s of qn)s(t)}const rt={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},Qn={trace:pe.TRACE,debug:pe.DEBUG,info:pe.INFO,warn:pe.WARN,error:pe.ERROR,fatal:pe.FATAL};class Kn{service;minLevel;logFilePath;logsDir;writeQueue=[];isWriting=!1;enableConsoleOutput;constructor(s,o="debug"){this.service=s,this.minLevel=o,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&Hn?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){if(!(!this.logFilePath||!je)&&(this.writeQueue.push(s),!this.isWriting)){for(this.isWriting=!0;this.writeQueue.length>0;){const n=`${this.writeQueue.splice(0,this.writeQueue.length).join(`
2
- `)}
3
- `;try{await require("node:fs").promises.appendFile(this.logFilePath,n,"utf-8")}catch{}}this.isWriting=!1}}shouldLog(s){return rt[s]>=rt[this.minLevel]}log(s,o,n){if(!this.shouldLog(s))return;const r={id:`log_${++Vn}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:o,...n&&{metadata:n}};if(Gn(r),je&&this.logFilePath,je&&this.logFilePath){const u={timestamp:r.timestamp,level:r.level,service:r.service,message:r.message,...r.metadata&&{metadata:r.metadata}};this.writeToFile(JSON.stringify(u)).catch(()=>{})}if(je&&this.enableConsoleOutput){const u=r.timestamp,p=r.level.toUpperCase().padEnd(5),d=`[${this.service}]`,c=r.metadata?` ${JSON.stringify(r.metadata)}`:"";console.log(`${u} ${p} ${d} ${r.message}${c}`)}const i=Ys.getLogger(this.service),a=st.trace.getSpan(st.context.active());i.emit({severityNumber:Qn[s],severityText:s.toUpperCase(),body:o,attributes:{service:this.service,...n&&Object.fromEntries(Object.entries(n).map(([u,p])=>[`log.${u}`,typeof p=="object"?JSON.stringify(p):p])),...a&&{trace_id:a.spanContext().traceId,span_id:a.spanContext().spanId}}})}trace(s,o){this.log("trace",s,o)}debug(s,o){this.log("debug",s,o)}info(s,o){this.log("info",s,o)}warn(s,o){this.log("warn",s,o)}error(s,o){this.log("error",s,o)}fatal(s,o){this.log("fatal",s,o)}}function oe(t,s="debug"){return new Kn(t,s)}const L=oe("http-transport");class Jn{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:ot,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},o=await this.sendRpcRequest("initialize",s);if(o.agentInfo){const i=o._meta,a=i&&typeof i=="object",u=a&&"agentDescription"in i?String(i.agentDescription):void 0,p=a&&"suggestedPrompts"in i&&Array.isArray(i.suggestedPrompts)?i.suggestedPrompts:void 0,d=a&&"tools"in i&&Array.isArray(i.tools)?i.tools:void 0,c=a&&"mcps"in i&&Array.isArray(i.mcps)?i.mcps:void 0,h=a&&"subagents"in i&&Array.isArray(i.subagents)?i.subagents:void 0,f=a&&"initialMessage"in i&&i.initialMessage&&typeof i.initialMessage=="object"?i.initialMessage:void 0,b=a&&"uiConfig"in i&&i.uiConfig&&typeof i.uiConfig=="object"?i.uiConfig:void 0;this.agentInfo={name:o.agentInfo.name,...o.agentInfo.title?{displayName:o.agentInfo.title}:{},version:o.agentInfo.version,...u?{description:u}:{},...p?{suggestedPrompts:p}:{},...f?{initialMessage:f}:{},...b?{uiConfig:b}:{},...d?{tools:d}:{},...c?{mcps:c}:{},...h?{subagents:h}:{}}}L.info("ACP connection initialized",{initResponse:o});const n={cwd:"/",mcpServers:[]},r=await this.sendRpcRequest("session/new",n);this.currentSessionId=r.sessionId,L.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(s){this.connected=!1;const o=s instanceof Error?s:new Error(String(s));throw this.notifyError(o),o}}async loadSession(s){this.connected&&(L.warn("Transport already connected, disconnecting first",{sessionId:s}),await this.disconnect());try{this.abortController=new AbortController;const o={protocolVersion:ot,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};L.info("Loading session - initializing connection",{sessionId:s});const n=await this.sendRpcRequest("initialize",o);if(n.agentInfo){const a=n._meta,u=a&&typeof a=="object",p=u&&"agentDescription"in a?String(a.agentDescription):void 0,d=u&&"suggestedPrompts"in a&&Array.isArray(a.suggestedPrompts)?a.suggestedPrompts:void 0,c=u&&"tools"in a&&Array.isArray(a.tools)?a.tools:void 0,h=u&&"mcps"in a&&Array.isArray(a.mcps)?a.mcps:void 0,f=u&&"subagents"in a&&Array.isArray(a.subagents)?a.subagents:void 0,b=u&&"initialMessage"in a&&a.initialMessage&&typeof a.initialMessage=="object"?a.initialMessage:void 0,v=u&&"uiConfig"in a&&a.uiConfig&&typeof a.uiConfig=="object"?a.uiConfig:void 0;this.agentInfo={name:n.agentInfo.name,...n.agentInfo.title?{displayName:n.agentInfo.title}:{},version:n.agentInfo.version,...p?{description:p}:{},...d?{suggestedPrompts:d}:{},...b?{initialMessage:b}:{},...v?{uiConfig:v}:{},...c?{tools:c}:{},...h?{mcps:h}:{},...f?{subagents:f}:{}}}if(!n.agentCapabilities?.loadSession)throw L.error("Agent does not support loading sessions",{capabilities:n.agentCapabilities}),new Error("Agent does not support loading sessions");L.info("ACP connection initialized, loading session",{sessionId:s,capabilities:n.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=s,await this.connectSSE();const r={sessionId:s,cwd:"/",mcpServers:[]};L.info("Sending session/load request",{loadRequest:r});const i=await this.sendRpcRequest("session/load",r);L.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:i}),this.connected=!0,this.reconnectAttempts=0}catch(o){this.connected=!1;const n=o instanceof Error?o:new Error(String(o));throw L.error("Failed to load session",{sessionId:s,error:n.message,stack:n.stack}),this.notifyError(n),n}}async listSessions(){try{const s={method:"GET"};this.options.headers&&(s.headers=this.options.headers);const o=await fetch(`${this.options.baseUrl}/sessions`,s);if(!o.ok)throw new Error(`HTTP ${o.status}: ${await o.text()}`);return(await o.json()).sessions||[]}catch(s){return L.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 o=s instanceof Error?s:new Error(String(s));throw this.notifyError(o),o}}async send(s){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");this.isInReplayMode&&(L.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const o=s.content.map(a=>a.type==="text"?{type:"text",text:a.text}:a.type==="image"?"source"in a&&a.source?{type:"image",data:a.source.data,mimeType:a.source.media_type}:"data"in a&&"mimeType"in a?{type:"image",data:a.data,mimeType:a.mimeType}:a:a),n={sessionId:this.currentSessionId,prompt:o},r=await this.sendRpcRequest("session/prompt",n);L.debug("Prompt sent",{promptResponse:r}),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(o){this.streamComplete=!0;const n=o instanceof Error?o:new Error(String(o));throw this.notifyError(n),n}}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(o=>{this.chunkResolvers.push(o)});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,o){const r={jsonrpc:"2.0",id:this.generateRequestId(),method:s,params:o};L.debug("Sending RPC request",{method:s,params:o,request:r});const i={"Content-Type":"application/json",...this.options.headers},a=this.options.timeout??600*1e3,u=new AbortController,p=setTimeout(()=>u.abort(),a);try{const d=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(r),signal:u.signal});if(clearTimeout(p),!d.ok){const h=await d.text();throw new Error(`HTTP ${d.status}: ${h}`)}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 ${a}ms`):d}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const s=`${this.options.baseUrl}/events`,o={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const n=await fetch(s,{method:"GET",headers:o,signal:this.sseAbortController.signal});if(!n.ok)throw new Error(`SSE connection failed: HTTP ${n.status}`);if(!n.body)throw new Error("Response body is null");L.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const r=n.body.getReader(),i=new TextDecoder;let a="";(async()=>{try{for(;;){const{done:u,value:p}=await r.read();if(u){L.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}a+=i.decode(p,{stream:!0});const d=a.split(`
4
- `);a=d.pop()||"";let c={event:"message",data:""};for(const h of d)h.startsWith("event:")?c.event=h.substring(6).trim():h.startsWith("data:")?c.data=h.substring(5).trim():h===""&&(c.event==="message"&&c.data&&this.handleSSEMessage(c.data),c={event:"message",data:""})}}catch(u){if(u instanceof Error&&u.name==="AbortError"){L.debug("SSE stream aborted");return}L.error("Error reading SSE stream",{error:u}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(n){throw L.error("SSE connection error",{error:n}),n}}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 o=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(o),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const s=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);L.debug("SSE reconnecting",{delay:s,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(o=>setTimeout(o,s));try{await this.connectSSE(),L.info("SSE reconnected successfully"),this.reconnecting=!1}catch(o){L.error("SSE reconnection failed",{error:o}),this.reconnecting=!1}}handleSSEMessage(s){try{const o=JSON.parse(s);L.debug("Received SSE message",{message:o});const n=on.safeParse(o);if(!n.success){L.error("Invalid ACP message from SSE",{issues:n.error.issues});return}const r=n.data;L.debug("Parsed ACP message",{method:"method"in r?r.method:"(no method)"}),"method"in r&&r.method==="session/update"&&(L.debug("Received session/update notification"),"params"in r&&r.params&&(L.debug("Calling handleSessionNotification",{params:r.params}),this.handleSessionNotification(r.params)))}catch(o){L.error("Error parsing SSE message",{error:o}),this.notifyError(o instanceof Error?o:new Error(String(o)))}}handleSessionNotification(s){L.debug("handleSessionNotification called",{params:s});const n=s.update,r=this.currentSessionId||s.sessionId;if(L.debug("Update session type",{sessionUpdate:n?.sessionUpdate}),n?.sessionUpdate==="tool_call"){L.debug("Tool call notification",{tokenUsage:n.tokenUsage});const i=n._meta&&typeof n._meta=="object"&&"messageId"in n._meta?String(n._meta.messageId):void 0,a=n._meta&&typeof n._meta=="object"&&"prettyName"in n._meta&&typeof n._meta.prettyName=="string"?n._meta.prettyName:void 0,u=n._meta&&typeof n._meta=="object"&&"icon"in n._meta&&typeof n._meta.icon=="string"?n._meta.icon:void 0,p=n._meta&&typeof n._meta=="object"&&"subline"in n._meta&&typeof n._meta.subline=="string"?n._meta.subline:void 0,d=n._meta&&typeof n._meta=="object"&&"batchId"in n._meta&&typeof n._meta.batchId=="string"?n._meta.batchId:void 0,c=n._meta&&typeof n._meta=="object"&&"subagentPort"in n._meta&&typeof n._meta.subagentPort=="number"?n._meta.subagentPort:void 0,h=n._meta&&typeof n._meta=="object"&&"subagentSessionId"in n._meta&&typeof n._meta.subagentSessionId=="string"?n._meta.subagentSessionId:void 0,f=n._meta&&typeof n._meta=="object"&&"subagentMessages"in n._meta&&Array.isArray(n._meta.subagentMessages)?n._meta.subagentMessages:void 0,b={id:n.toolCallId??"",batchId:d,title:n.title??"",prettyName:a,icon:u,subline:p,kind:n.kind||"other",status:n.status||"pending",locations:n.locations,rawInput:n.rawInput,tokenUsage:n.tokenUsage,content:n.content?.map(x=>{if(typeof x!="object"||x===null)return{type:"text",text:""};const g=x;if(g.type==="content"&&typeof g.content=="object"&&g.content!==null){const w=g.content;if(w.type==="text")return{type:"content",content:{type:"text",text:typeof w.text=="string"?w.text:""}}}return g.type==="text"?{type:"text",text:typeof g.text=="string"?g.text:""}:g.type==="diff"?{type:"diff",path:typeof g.path=="string"?g.path:"",oldText:typeof g.oldText=="string"?g.oldText:"",newText:typeof g.newText=="string"?g.newText:"",line:typeof g.line=="number"?g.line:null}:g.type==="terminal"?{type:"terminal",terminalId:typeof g.terminalId=="string"?g.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now(),subagentPort:c,subagentSessionId:h,subagentMessages:f},v={type:"tool_call",sessionId:r,status:"active",toolCall:b,messageId:i},m=n._meta&&typeof n._meta=="object"&&"isReplay"in n._meta&&n._meta.isReplay===!0;if(L.info("Creating tool_call session update",{toolCallId:b.id,title:b.title,hasSubagentPort:!!c,hasSubagentSessionId:!!h,hasSubagentMessages:!!f,subagentMessagesCount:f?.length,isReplay:m,isInReplayMode:this.isInReplayMode}),m||this.isInReplayMode)this.notifySessionUpdate(v);else{const x={type:"tool_call",id:r,toolCall:b,messageId:i},g=this.chunkResolvers.shift();g?g(x):this.messageQueue.push(x)}}else if(n?.sessionUpdate==="tool_call_update"){const i=n._meta&&typeof n._meta=="object"&&"messageId"in n._meta?String(n._meta.messageId):void 0,a=n._meta&&typeof n._meta=="object"&&"prettyName"in n._meta&&typeof n._meta.prettyName=="string"?n._meta.prettyName:void 0,u=n._meta&&typeof n._meta=="object"&&"icon"in n._meta&&typeof n._meta.icon=="string"?n._meta.icon:void 0,p=n._meta&&typeof n._meta=="object"&&"batchId"in n._meta&&typeof n._meta.batchId=="string"?n._meta.batchId:void 0,d=n._meta&&typeof n._meta=="object"&&"subagentPort"in n._meta&&typeof n._meta.subagentPort=="number"?n._meta.subagentPort:void 0,c=n._meta&&typeof n._meta=="object"&&"subagentSessionId"in n._meta&&typeof n._meta.subagentSessionId=="string"?n._meta.subagentSessionId:void 0,h=n._meta&&typeof n._meta=="object"&&"subagentMessages"in n._meta&&Array.isArray(n._meta.subagentMessages)?n._meta.subagentMessages:void 0;(d||c||h)&&L.info("Extracted subagent info from tool_call_update",{toolCallId:n.toolCallId,subagentPort:d,subagentSessionId:c,subagentMessagesCount:h?.length});const f={id:n.toolCallId??"",status:n.status,title:n.title,prettyName:a,icon:u,batchId:p,rawInput:n.rawInput,locations:n.locations,rawOutput:n.rawOutput,tokenUsage:n.tokenUsage,content:n.content?.map(v=>{if(typeof v!="object"||v===null)return{type:"text",text:""};const m=v;if(m.type==="content"&&typeof m.content=="object"&&m.content!==null){const x=m.content;if(x.type==="text")return{type:"content",content:{type:"text",text:typeof x.text=="string"?x.text:""}}}return m.type==="text"?{type:"text",text:typeof m.text=="string"?m.text:""}:m.type==="diff"?{type:"diff",path:typeof m.path=="string"?m.path:"",oldText:typeof m.oldText=="string"?m.oldText:"",newText:typeof m.newText=="string"?m.newText:"",line:typeof m.line=="number"?m.line:null}:m.type==="terminal"?{type:"terminal",terminalId:typeof m.terminalId=="string"?m.terminalId:""}:{type:"text",text:""}}),error:n.error,completedAt:n.status==="completed"||n.status==="failed"?Date.now():void 0,subagentPort:d,subagentSessionId:c,subagentMessages:h},b={type:"tool_call_update",sessionId:r,status:"active",toolCallUpdate:f,messageId:i};if(this.isInReplayMode)this.notifySessionUpdate(b);else{const v={type:"tool_call_update",id:r,toolCallUpdate:f,messageId:i},m=this.chunkResolvers.shift();m?m(v):this.messageQueue.push(v)}L.debug("Processed tool_call_update",{sessionUpdate:b,isReplay:this.isInReplayMode})}else if(n&&"sessionUpdate"in n&&n.sessionUpdate==="tool_output"){const i=n,a=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 h=c.content;if(h.type==="text")return{type:"content",content:{type:"text",text:typeof h.text=="string"?h.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:r,status:"active",toolCallUpdate:u,messageId:a};if(this.isInReplayMode)this.notifySessionUpdate(p);else{const d={type:"tool_call_update",id:r,toolCallUpdate:u,messageId:a},c=this.chunkResolvers.shift();c?c(d):this.messageQueue.push(d)}L.debug("Queued tool_output as tool_call_update chunk",{sessionUpdate:p})}else if(n?.sessionUpdate==="agent_message_chunk"){const i=n._meta&&typeof n._meta=="object"&&"isReplay"in n._meta&&n._meta.isReplay===!0;if(this.isInReplayMode&&!i)return;const a=n._meta&&typeof n._meta=="object"&&"tokenUsage"in n._meta?n._meta.tokenUsage:void 0,u=n._meta&&typeof n._meta=="object"&&"contextInputTokens"in n._meta&&typeof n._meta.contextInputTokens=="number"?n._meta.contextInputTokens:void 0,p=n._meta&&typeof n._meta=="object"&&"context_size"in n._meta?n._meta.context_size:void 0,d={type:"generic",sessionId:r,status:"active",_meta:n._meta},c=n.content;if(c&&typeof c=="object"){const f=c;let b=null;if(f.type==="text"&&typeof f.text=="string"&&(b={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:f.text},tokenUsage:a,contextInputTokens:u,_meta:p?{context_size:p}:void 0,isComplete:!1}),b&&!i){const v=this.chunkResolvers.shift();v?v(b):this.messageQueue.push(b)}if(b&&typeof f.text=="string"&&(i||!this.isReceivingMessages)){const v={type:"generic",sessionId:r,status:"active",message:{id:`msg_${Date.now()}_assistant`,role:"assistant",content:[{type:"text",text:f.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(v)}}const h=d._meta&&"context_size"in d._meta;(!i||h)&&this.notifySessionUpdate(d)}else if(n?.sessionUpdate==="user_message_chunk"){L.debug("Received user_message_chunk",{update:n});const i=n.content;if(i&&typeof i=="object"){const a=i;if(a.type==="text"&&typeof a.text=="string"){const u={type:"generic",sessionId:r,status:"active",message:{id:`msg_${Date.now()}_user`,role:"user",content:[{type:"text",text:a.text}],timestamp:new Date().toISOString()}};L.debug("Notifying session update for user message"),this.notifySessionUpdate(u)}}}else{const i={type:"generic",sessionId:r,status:"active"};this.notifySessionUpdate(i)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(s){for(const o of this.sessionUpdateCallbacks)try{o(s)}catch(n){L.error("Error in session update callback",{error:n})}}notifyError(s){for(const o of this.errorCallbacks)try{o(s)}catch(n){L.error("Error in error callback",{error:n})}}}class Yn{constructor(){throw new Error("StdioTransport is not available in the browser. Use HttpTransport or WebSocketTransport instead.")}async connect(){throw new Error("StdioTransport not available in browser")}async disconnect(){}async send(){throw new Error("StdioTransport not available in browser")}async*receive(){throw new Error("StdioTransport not available in browser")}isConnected(){return!1}onSessionUpdate(){return()=>{}}onError(){return()=>{}}}class Xn{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(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 Le=oe("acp-client","debug");class Zn{constructor(s){this.config=s,this.transport=this.createTransport(),this.setupTransportListeners(),s.autoConnect&&this.connect().catch(o=>{Le.error("Failed to auto-connect",{error:o instanceof Error?o.message:String(o)})})}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 o="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(o){const u=new Date().toISOString(),p=this.transport.getAgentInfo?.()?.name,d={id:o,status:"connected",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:u,agentName:p}};return this.sessions.set(o,d),this.currentSessionId=o,o}const n=this.generateSessionId(),r=new Date().toISOString(),i=this.transport.getAgentInfo?.()?.name,a={id:n,status:"connecting",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:r,agentName:i}};return this.sessions.set(n,a),this.currentSessionId=n,this.updateSessionStatus(n,"connected"),n}async loadSession(s,o){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const n=new Date().toISOString(),r={id:s,status:"connecting",config:o?{...o,agentPath:o.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:n}};if(this.sessions.set(s,r),this.currentSessionId=s,await this.transport.loadSession(s),this.transport.getAgentInfo){const i=this.transport.getAgentInfo();i.name&&r.metadata&&(r.metadata.agentName=i.name)}return this.updateSessionStatus(s,"connected"),s}async listSessions(){return this.transport.listSessions?this.transport.listSessions():[]}async sendMessage(s,o,n){const r=o||this.currentSessionId;if(!r)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(r);if(!i)throw new Error(`Session ${r} not found`);const a=[];if(n&&n.length>0)for(const p of n)p.mimeType.startsWith("image/")&&a.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.data}});a.push({type:"text",text:s});const u={id:this.generateMessageId(),role:"user",content:a,timestamp:new Date().toISOString()};i.messages.push(u),this.updateSessionStatus(r,"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 Yn(this.config.options);case"http":return new Jn(this.config.options);case"websocket":return new Xn(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(s=>{this.handleSessionUpdate(s)}),this.transport.onError(s=>{this.handleError(s)})}handleSessionUpdate(s){if(s.sessionId){const o=this.sessions.get(s.sessionId);o&&(s.status&&(o.status=s.status),s.message&&o.messages.push(s.message),s.error&&(o.error=s.error))}for(const o of this.sessionUpdateHandlers)try{o(s)}catch(n){Le.error("Error in session update handler",{error:n instanceof Error?n.message:String(n)})}}handleError(s){for(const o of this.errorHandlers)try{o(s)}catch(n){Le.error("Error in error handler",{error:n instanceof Error?n.message:String(n)})}}updateSessionStatus(s,o){const n=this.sessions.get(s);n&&(n.status=o,this.handleSessionUpdate({sessionId:s,status:o}))}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 me=oe("acp-client-hook");function eo(t){const[s,o]=l.useState(null),[n,r]=l.useState(null),[i,a]=l.useState(null);return l.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("session");p&&(me.info("Session ID found in URL",{sessionId:p}),a(p));try{me.info("Initializing ACP client",{serverUrl:t.serverUrl});const d=new Zn({type:"http",options:{baseUrl:t.serverUrl}});return o(d),me.info("ACP client initialized successfully"),()=>{me.debug("Disconnecting ACP client"),d.disconnect().catch(c=>{me.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";r(c),me.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:n,sessionId:i}}const He=te(["pending","in_progress","completed","failed"]),to=te(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),Jt=U({path:j(),line:O().nullable().optional()}),We=U({inputTokens:O().optional(),outputTokens:O().optional(),totalTokens:O().optional()}),Ve=Ee("type",[U({type:q("content"),content:U({type:q("text"),text:j()})}),U({type:q("text"),text:j()}),U({type:q("image"),data:j(),mimeType:j().optional(),alt:j().optional()}),U({type:q("image"),url:j(),alt:j().optional()}),U({type:q("diff"),path:j(),oldText:j(),newText:j(),line:O().nullable().optional()}),U({type:q("terminal"),terminalId:j()})]),Yt=U({id:j(),title:j(),prettyName:j().optional(),icon:j().optional(),status:He,content:G(Ve).optional()}),so=Ee("type",[U({type:q("text"),text:j()}),U({type:q("tool_call"),toolCall:Yt})]),Xt=U({id:j(),content:j(),toolCalls:G(Yt).optional(),contentBlocks:G(so).optional(),isStreaming:ce().optional()}),Zt=U({id:j(),batchId:j().optional(),title:j(),prettyName:j().optional(),icon:j().optional(),subline:j().optional(),kind:to,status:He,contentPosition:O().optional(),locations:G(Jt).optional(),rawInput:Y(j(),X()).optional(),rawOutput:Y(j(),X()).optional(),content:G(Ve).optional(),error:j().optional(),startedAt:O().optional(),completedAt:O().optional(),tokenUsage:We.optional(),_meta:U({truncationWarning:j().optional(),compactionAction:te(["compacted","truncated"]).optional(),originalTokens:O().optional(),finalTokens:O().optional()}).optional(),subagentPort:O().optional(),subagentSessionId:j().optional(),subagentMessages:G(Xt).optional(),subagentStreaming:ce().optional()}),no=U({id:j(),status:He.optional(),title:j().optional(),prettyName:j().optional(),icon:j().optional(),batchId:j().optional(),rawInput:Y(j(),X()).optional(),locations:G(Jt).optional(),rawOutput:Y(j(),X()).optional(),content:G(Ve).optional(),error:j().optional(),completedAt:O().optional(),tokenUsage:We.optional(),subagentPort:O().optional(),subagentSessionId:j().optional(),subagentMessages:G(Xt).optional()});function it(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 fe=oe("chat-store","debug"),Se=[];let Ne={sessionId:null,toolCallId:null,todos:Se};const oo=t=>{const s=t.sessionId;if(!s)return Se;const n=(t.toolCalls[s]||[]).filter(a=>a.title==="todo_write").sort((a,u)=>(u.startedAt||0)-(a.startedAt||0));if(n.length===0)return Se;const r=n[0];if(!r?.rawInput?.todos||!Array.isArray(r.rawInput.todos))return Se;if(Ne.sessionId===s&&Ne.toolCallId===r.id)return Ne.todos;const i=r.rawInput.todos.map((a,u)=>({id:`${r.id}-${u}`,text:a.status==="in_progress"?a.activeForm:a.content,status:a.status}));return Ne={sessionId:s,toolCallId:r.id,todos:i},i},P=Xs(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(o=>({messages:[...o.messages,s]})),updateMessage:(s,o)=>t(n=>{const r=n.messages.find(d=>d.id===s);let i=n.totalBilled,a=n.currentContext,u=o;if(o.tokenUsage){const d=r?.tokenUsage;fe.debug("updateMessage: incoming tokenUsage",{incoming:o.tokenUsage,existing:d});const c={inputTokens:Math.max(o.tokenUsage.inputTokens??0,d?.inputTokens??0),outputTokens:Math.max(o.tokenUsage.outputTokens??0,d?.outputTokens??0),totalTokens:Math.max(o.tokenUsage.inputTokens??0,d?.inputTokens??0)+Math.max(o.tokenUsage.outputTokens??0,d?.outputTokens??0)};fe.debug("updateMessage: merged tokenUsage",{merged:c}),u={...o,tokenUsage:c};const h=c.inputTokens-(d?.inputTokens??0),f=c.outputTokens-(d?.outputTokens??0),b=c.totalTokens-(d?.totalTokens??0);i={inputTokens:n.totalBilled.inputTokens+h,outputTokens:n.totalBilled.outputTokens+f,totalTokens:n.totalBilled.totalTokens+b},a={inputTokens:c.inputTokens,outputTokens:n.currentContext.outputTokens+f,totalTokens:c.totalTokens}}const p=n.messages.map(d=>d.id===s?{...d,...u}:d);if(o.tokenUsage&&u.tokenUsage){const d=r?.tokenUsage,c=u.tokenUsage,h=(c.inputTokens??0)-(d?.inputTokens??0),f=(c.outputTokens??0)-(d?.outputTokens??0),b=(c.totalTokens??0)-(d?.totalTokens??0),v=p.filter(g=>g.tokenUsage).map(g=>({id:g.id,role:g.role,tokens:g.tokenUsage})),m=p.reduce((g,w)=>({inputTokens:g.inputTokens+(w.tokenUsage?.inputTokens??0),outputTokens:g.outputTokens+(w.tokenUsage?.outputTokens??0),totalTokens:g.totalTokens+(w.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),x=m.inputTokens===i.inputTokens&&m.outputTokens===i.outputTokens&&m.totalTokens===i.totalTokens;fe.debug("updateMessage: tokenUsage update",{messageId:s,updates:o.tokenUsage,existing:d,messageMax:c,delta:{inputDelta:h,outputDelta:f,totalDelta:b},totalBilled:i,currentContext:a,actualSum:m,billedCorrect:x?"✅":"❌",messageCount:p.length,messagesWithTokens:v.length,breakdown:v})}return{messages:p,totalBilled:i,currentContext:a}}),clearMessages:()=>t({messages:[]}),setIsStreaming:s=>t({isStreaming:s}),setStreamingStartTime:s=>t({streamingStartTime:s}),addToolCall:(s,o)=>t(n=>({toolCalls:{...n.toolCalls,[s]:[...n.toolCalls[s]||[],o]}})),addToolCallToCurrentMessage:s=>t(o=>{const n=o.messages.findLastIndex(p=>p.role==="assistant");if(n===-1){fe.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:[...o.messages,p]}}const r=[...o.messages],i=r[n];if(!i)return o;const a=i.content.length,u={...s,contentPosition:a};return r[n]={...i,toolCalls:[...i.toolCalls||[],u]},{messages:r}}),updateToolCallInCurrentMessage:s=>t(o=>{const n=o.messages.findLastIndex(c=>c.role==="assistant");if(n===-1)return fe.warn("No assistant message found to update tool call in"),o;const r=[...o.messages],i=r[n];if(!i)return o;const a=i.toolCalls||[],u=a.findIndex(c=>c.id===s.id);if(u===-1)return fe.warn(`Tool call ${s.id} not found in message`),o;const p=a[u];if(!p)return o;const d=[...a];return d[u]=it(p,s),r[n]={...i,toolCalls:d},{messages:r}}),updateToolCall:(s,o)=>t(n=>{const r=n.toolCalls[s]||[],i=r.findIndex(p=>p.id===o.id);if(i===-1)return n;const a=r[i];if(!a)return n;const u=[...r];return u[i]=it(a,o),{toolCalls:{...n.toolCalls,[s]:u}}}),setInputValue:s=>t(o=>({input:{...o.input,value:s}})),setInputSubmitting:s=>t(o=>({input:{...o.input,isSubmitting:s}})),addFileAttachment:s=>t(o=>({input:{...o.input,attachedFiles:[...o.input.attachedFiles,s]}})),removeFileAttachment:s=>t(o=>({input:{...o.input,attachedFiles:o.input.attachedFiles.filter((n,r)=>r!==s)}})),clearInput:()=>t(s=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}})),addTokenUsage:s=>t(o=>({totalBilled:{inputTokens:o.totalBilled.inputTokens+(s.inputTokens??0),outputTokens:o.totalBilled.outputTokens+(s.outputTokens??0),totalTokens:o.totalBilled.totalTokens+(s.totalTokens??0)},currentContext:{inputTokens:s.inputTokens??o.currentContext.inputTokens,outputTokens:o.currentContext.outputTokens+(s.outputTokens??0),totalTokens:(s.inputTokens??o.currentContext.inputTokens)+(o.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 o=["context","input","output"],r=(o.indexOf(s.tokenDisplayMode)+1)%o.length,i=o[r];return i?{tokenDisplayMode:i}:s}),addLog:s=>t(o=>({logs:[...o.logs,s]})),clearLogs:()=>t({logs:[]}),setActiveTab:s=>t({activeTab:s})})),Z=oe("use-chat-messages","debug");function es(t,s){const o=P(x=>x.messages),n=P(x=>x.isStreaming),r=P(x=>x.sessionId),i=P(x=>x.setIsStreaming),a=P(x=>x.setStreamingStartTime),u=P(x=>x.addMessage),p=P(x=>x.updateMessage),d=P(x=>x.setError),c=P(x=>x.setLatestContextSize),h=P(x=>x.addToolCall),f=P(x=>x.updateToolCall),b=P(x=>x.addToolCallToCurrentMessage),v=P(x=>x.updateToolCallInCurrentMessage),m=l.useCallback(async(x,g)=>{if(Z.debug("[sendMessage] Called with",{contentLength:x.length,attachmentsCount:g?.length||0,hasAttachments:!!g&&g.length>0}),!t){Z.error("No client available"),d("No client available");return}let w=r;if(!w){Z.info("Creating new session before sending first message");const T=await s();if(!T){Z.error("Failed to create session"),d("Failed to create session");return}w=T,Z.info("Session created successfully",{sessionId:T})}const S=`msg_${Date.now()}_assistant`;try{const T=Date.now();i(!0),a(T);const C={id:`msg_${Date.now()}_user`,role:"user",content:x,timestamp:new Date().toISOString(),isStreaming:!1,...g&&g.length>0?{images:g.filter(R=>R.mimeType.startsWith("image/")).map(R=>({mimeType:R.mimeType,data:R.data}))}:{}};u(C);const N={id:S,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:T};u(N);const M=t.receiveMessages();t.sendMessage(x,w,g).catch(R=>{const F=R instanceof Error?R.message:String(R);d(F),i(!1),a(null)});let A="",D=!1;for await(const R of M)if(R.type==="content"){const F=R._meta,$=F?.context_size||R.context_size;if($!=null){const k=$;Z.info("✅ Received context_size from backend",{context_size:k,totalEstimated:k.totalEstimated,source:F?.context_size?"_meta":"direct"}),c(k)}else Z.debug("Chunk does not have context_size",{hasContextSize:"context_size"in R,hasMeta:"_meta"in R,metaKeys:F?Object.keys(F):null});if(R.tokenUsage&&Z.debug("Received tokenUsage from backend",{tokenUsage:R.tokenUsage}),R.isComplete){p(S,{content:A,isStreaming:!1,streamingStartTime:void 0,...R.tokenUsage?{tokenUsage:R.tokenUsage}:{}}),i(!1),a(null),D=!0;break}else R.contentDelta.type==="text"&&(A+=R.contentDelta.text,p(S,{content:A,...R.tokenUsage?{tokenUsage:R.tokenUsage}:{}}),await new Promise(k=>setTimeout(k,16)))}else R.type==="tool_call"?(Z.debug("Received tool_call chunk",{chunk:R}),h(w,R.toolCall),b(R.toolCall)):R.type==="tool_call_update"&&(Z.debug("Received tool_call_update chunk",{chunk:R}),f(w,R.toolCallUpdate),v(R.toolCallUpdate));D||(Z.warn("Stream ended without isComplete flag"),p(S,{isStreaming:!1,streamingStartTime:void 0}),i(!1),a(null))}catch(T){const C=T instanceof Error?T.message:String(T);d(C),i(!1),a(null),p(S,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,s,u,p,i,a,d,c,h,f,b,v]);return{messages:o,isStreaming:n,sendMessage:m}}const lt=oe("use-chat-input","debug");function ao(t,s){const o=P(f=>f.input),n=P(f=>f.setInputValue),r=P(f=>f.setInputSubmitting),i=P(f=>f.addFileAttachment),a=P(f=>f.removeFileAttachment),{sendMessage:u}=es(t,s),p=l.useCallback(f=>{n(f)},[n]),d=l.useCallback(async()=>{if(!o.value.trim()||o.isSubmitting)return;const f=o.value,b=o.attachedFiles;lt.debug("Submitting message with attachments",{messageLength:f.length,attachmentCount:b.length,hasAttachments:b.length>0}),n(""),r(!0);try{await u(f,b.length>0?b:void 0),P.setState(v=>({input:{...v.input,attachedFiles:[]}}))}catch(v){lt.error("Failed to send message",{error:v instanceof Error?v.message:String(v)})}finally{r(!1)}},[o,n,r,u]),c=l.useCallback(f=>{i(f)},[i]),h=l.useCallback(f=>{a(f)},[a]);return{value:o.value,isSubmitting:o.isSubmitting,attachedFiles:o.attachedFiles,onChange:p,onSubmit:d,onAttachFile:c,onRemoveFile:h}}const ae=oe("use-chat-session","debug");function ro(t,s){const o=P(m=>m.connectionStatus),n=P(m=>m.sessionId),r=P(m=>m.setConnectionStatus),i=P(m=>m.setSessionId),a=P(m=>m.setError),u=P(m=>m.clearMessages),p=P(m=>m.resetTokens),d=P(m=>m.addMessage),c=P(m=>m.setLatestContextSize);l.useEffect(()=>t?t.onSessionUpdate(x=>{const g=x._meta,w=g?.context_size||x.context_size;if(w!=null){const S=w;ae.info("✅ Received context_size from session update",{context_size:S,totalEstimated:S.totalEstimated,isReplay:g?.isReplay}),c(S)}if(x.message&&(ae.debug("Session update with message",{message:x.message}),x.message.role!=="tool")){const S=x.message.content.map(M=>M.type==="text"?M.text:"").join(""),T=[];for(const M of x.message.content)if(M.type==="image"){const A=M;A.source?.data?T.push({mimeType:A.source.media_type||"image/png",data:A.source.data}):A.data&&T.push({mimeType:A.mimeType||"image/png",data:A.data})}const C=P.getState().messages,N=C[C.length-1];if(x.message.role==="assistant"&&N?.role==="assistant"&&N.content===""&&S)ae.debug("Appending text to existing assistant message"),P.getState().updateMessage(N.id,{content:N.content+S});else{const M={id:x.message.id,role:x.message.role,content:S,timestamp:x.message.timestamp,isStreaming:!1,...T.length>0?{images:T}:{}};d(M)}}}):void 0,[t,d,c]);const h=l.useCallback(async()=>{if(!t){a("No client available");return}try{r("connecting"),a(null),await t.connect();const m=t.getCurrentSession();if(m?.id&&(i(m.id),typeof window<"u")){const x=new URL(window.location.href);x.searchParams.set("session",m.id),window.history.replaceState({},"",x.toString())}r("connected")}catch(m){ae.error("Failed to connect",{error:m instanceof Error?m.message:String(m)});const x=m instanceof Error?m.message:String(m);a(x),r("error")}},[t,r,i,a]),f=l.useCallback(async m=>{if(!t){a("No client available");return}try{r("connecting"),a(null),u(),p();const x=await t.loadSession(m);i(x),r("connected"),ae.info("Session loaded successfully",{sessionId:x})}catch(x){ae.warn("Failed to load session, creating new one instead",{sessionId:m,error:x instanceof Error?x.message:String(x)});try{await h();const g=await t.startSession();if(i(g),u(),p(),typeof window<"u"){const w=new URL(window.location.href);w.searchParams.set("session",g),window.history.replaceState({},"",w.toString())}ae.info("Created new session after failed load",{sessionId:g})}catch(g){const w=g instanceof Error?g.message:String(g);a(`Failed to load or create session: ${w}`),r("error")}}},[t,r,i,a,u,p,h]),b=l.useCallback(async()=>{if(!t)return a("No client available"),null;try{const m=await t.startSession();if(i(m),P.getState().messages.length===0&&(u(),p()),typeof window<"u"){const g=new URL(window.location.href);g.searchParams.set("session",m),window.history.pushState({},"",g.toString())}return m}catch(m){const x=m instanceof Error?m.message:String(m);return a(x),null}},[t,i,a,u,p]),v=l.useCallback(async()=>{if(t)try{await t.disconnect(),r("disconnected"),i(null)}catch(m){const x=m instanceof Error?m.message:String(m);a(x)}},[t,r,i,a]);return l.useEffect(()=>{!t||o!=="disconnected"||(s?(ae.info("Loading initial session from URL",{sessionId:s}),f(s)):h())},[t,o,s,h,f]),{connectionStatus:o,sessionId:n,connect:h,loadSession:f,startSession:b,disconnect:v}}const ct="town-message-history",io=100;function lo(){const[t,s]=l.useState(-1),[o,n]=l.useState(""),r=l.useCallback(()=>{try{const c=localStorage.getItem(ct);return c?JSON.parse(c):[]}catch{return[]}},[]),i=l.useCallback(c=>{const h=c.trim();if(h){try{const f=r();if(f[0]===h)return;const b=[h,...f].slice(0,io);localStorage.setItem(ct,JSON.stringify(b))}catch{}s(-1),n("")}},[r]),a=l.useCallback(c=>{const h=r();if(h.length===0)return null;t===-1&&n(c);const f=Math.min(t+1,h.length-1);if(f===t)return null;const b=h[f];return b===void 0?null:(s(f),b)},[t,r]),u=l.useCallback(()=>{if(t===-1)return null;const c=r();if(t===0){s(-1);const b=o;return n(""),b}const h=t-1,f=c[h];return f===void 0?null:(s(h),f)},[t,o,r]),p=l.useCallback(()=>{t!==-1&&(s(-1),n(""))},[t]);return{addToHistory:i,navigatePrevious:a,navigateNext:u,resetNavigation:p,isBrowsingHistory:t!==-1,historyIndex:t}}const ee=oe("subagent-stream");function co(t){const[s,o]=l.useState([]),[n,r]=l.useState(!!t),[i,a]=l.useState(!1),[u,p]=l.useState(null),d=l.useRef(null),c=l.useRef(null),h=l.useRef(null),f=l.useCallback(()=>{h.current||(h.current=setTimeout(()=>{h.current=null,c.current&&o([{...c.current}])},250))},[]),b=l.useCallback(x=>{try{const g=JSON.parse(x);if(ee.debug("Processing SSE message",{method:g.method,hasParams:!!g.params}),g.method==="session/update"&&g.params?.update){const w=g.params.update;if(ee.debug("Got session update",{sessionUpdate:w.sessionUpdate}),w.sessionUpdate==="agent_message_chunk"){const S=w.content;if(S?.type==="text"&&typeof S.text=="string"&&c.current){c.current.content+=S.text;const T=c.current.contentBlocks??[],C=T[T.length-1];C&&C.type==="text"?C.text+=S.text:T.push({type:"text",text:S.text}),c.current.contentBlocks=T,f()}}else if(w.sessionUpdate==="tool_call"){const S={id:w.toolCallId??`tc-${Date.now()}`,title:w.title??"Tool call",prettyName:w._meta?.prettyName,icon:w._meta?.icon,status:w.status??"pending",content:[]};if(c.current){c.current.toolCalls=[...c.current.toolCalls??[],S];const T=c.current.contentBlocks??[];T.push({type:"tool_call",toolCall:S}),c.current.contentBlocks=T,f()}}else if(w.sessionUpdate==="tool_call_update"&&c.current?.toolCalls){const S=w.toolCallId,T=C=>C.id===S?{...C,status:w.status??C.status,content:w.content??C.content}:C;c.current.toolCalls=c.current.toolCalls.map(T),c.current.contentBlocks&&(c.current.contentBlocks=c.current.contentBlocks.map(C=>C.type==="tool_call"?{...C,toolCall:T(C.toolCall)}:C)),f()}}}catch(g){ee.error("Failed to parse sub-agent SSE message",{error:g instanceof Error?g.message:String(g)})}},[f]),v=l.useCallback(async(x,g,w)=>{const S=`http://${w}:${x}`;ee.info("Connecting to sub-agent SSE",{baseUrl:S,sessionId:g}),r(!0),p(null);const T=new AbortController;d.current=T;try{ee.info("Fetching SSE endpoint",{url:`${S}/events`,sessionId:g});const C=await fetch(`${S}/events`,{method:"GET",headers:{"X-Session-ID":g},signal:T.signal});if(ee.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");ee.info("Sub-agent SSE connection opened, starting to read stream");const N=C.body.getReader(),M=new TextDecoder;let A="";for(c.current={id:`subagent-${Date.now()}`,content:"",toolCalls:[],contentBlocks:[],isStreaming:!0},o([c.current]);;){const{done:D,value:R}=await N.read();if(D){ee.debug("Sub-agent SSE stream closed");break}A+=M.decode(R,{stream:!0});const F=A.split(`
5
- `);A=F.pop()||"";let $={event:"message",data:""};for(const k of F)k.startsWith("event:")?$.event=k.substring(6).trim():k.startsWith("data:")?$.data=k.substring(5).trim():k===""&&($.event==="message"&&$.data&&b($.data),$={event:"message",data:""})}}catch(C){if(C instanceof Error&&C.name==="AbortError")ee.debug("Sub-agent SSE stream aborted");else{const N=C instanceof Error?C.message:"Failed to connect to sub-agent";ee.error("Sub-agent SSE error",{error:N}),p(N)}}finally{c.current&&(c.current.isStreaming=!1,o(C=>C.map(N=>N.id===c.current?.id?{...N,isStreaming:!1}:N))),a(!0),r(!1),d.current=null,ee.debug("Sub-agent stream completed")}},[b]);return l.useEffect(()=>{if(!t)return;const{port:x,sessionId:g,host:w="localhost"}=t;if(!(!x||!g))return o([]),p(null),a(!1),r(!0),v(x,g,w),()=>{d.current&&(d.current.abort(),d.current=null),h.current&&(clearTimeout(h.current),h.current=null)}},[t?.port,t?.sessionId,t?.host,v]),{messages:s,isStreaming:!i,error:u}}function uo(t){const s=P(a=>a.toolCalls),o=P(a=>a.addToolCall),n=P(a=>a.updateToolCall),r=P(a=>a.addToolCallToCurrentMessage),i=P(a=>a.updateToolCallInCurrentMessage);return l.useEffect(()=>{if(!t)return;const a=t.onSessionUpdate(u=>{u.type==="tool_call"?(o(u.sessionId,u.toolCall),r(u.toolCall)):u.type==="tool_call_update"&&(n(u.sessionId,u.toolCallUpdate),i(u.toolCallUpdate))});return()=>{a()}},[t,o,n,r,i]),{toolCalls:s,getToolCallsForSession:a=>{const u=s[a];return u&&u.length>0?u:Object.values(s).flat()}}}const po=U({mimeType:j(),data:j()}),mo=U({id:j(),role:te(["user","assistant","system"]),content:j(),timestamp:ke(),isStreaming:ce().default(!1),streamingStartTime:O().optional(),metadata:Y(j(),X()).optional(),toolCalls:G(Zt).optional(),tokenUsage:We.optional(),images:G(po).optional()}),fo=U({value:j(),isSubmitting:ce(),attachedFiles:G(U({name:j(),path:j(),size:O(),mimeType:j(),data:j()}))});U({sessionId:j().nullable(),isConnected:ce(),isStreaming:ce(),messages:G(mo),input:fo,error:j().nullable()});te(["disconnected","connecting","connected","error"]);const go=U({name:j(),description:j().optional(),parameters:Y(j(),X()).optional()}),ho=U({name:j(),description:j(),parameters:Y(j(),X()),required:G(j()).optional()}),xo=U({name:j(),version:j().optional(),description:j().optional(),author:j().optional(),capabilities:G(go).optional(),tools:G(ho).optional(),supportedFormats:G(j()).optional()}),bo=te(["initializing","ready","busy","error","terminated"]);U({status:bo,info:xo.optional(),pid:O().optional(),error:j().optional(),uptime:O().optional()});const ts=te(["user","assistant","system","tool"]),yo=te(["text","image","file","tool_call","tool_result"]),we=U({type:yo}),vo=we.extend({type:q("text"),text:j()}),wo=we.extend({type:q("image"),url:j().url().optional(),source:U({type:q("base64"),media_type:te(["image/jpeg","image/png","image/gif","image/webp"]),data:j()}).optional()}),jo=we.extend({type:q("file"),name:j(),path:j().optional(),url:j().url().optional(),mimeType:j(),size:O().optional()}),No=we.extend({type:q("tool_call"),id:j(),name:j(),arguments:Y(j(),X())}),So=we.extend({type:q("tool_result"),callId:j(),result:X(),error:j().optional()}),ss=Ee("type",[vo,wo,jo,No,So]),ns=U({id:j(),role:ts,content:G(ss),timestamp:ke(),metadata:Y(j(),X()).optional()}),Co=U({type:q("content"),id:j(),role:ts,contentDelta:ss,isComplete:ce(),tokenUsage:U({inputTokens:O().optional(),outputTokens:O().optional(),totalTokens:O().optional()}).optional(),contextInputTokens:O().optional(),_meta:U({context_size:U({systemPromptTokens:O(),userMessagesTokens:O(),assistantMessagesTokens:O(),toolInputTokens:O(),toolResultsTokens:O(),totalEstimated:O(),llmReportedInputTokens:O().optional()}).optional()}).optional()}),To=U({type:q("tool_call"),id:j(),toolCall:Oe(),messageId:j().optional()}),ko=U({type:q("tool_call_update"),id:j(),toolCallUpdate:Oe(),messageId:j().optional()});Ee("type",[Co,To,ko]);const os=te(["idle","connecting","connected","active","streaming","error","disconnected"]),Io=U({agentPath:j(),agentArgs:G(j()).optional(),environment:Y(j(),j()).optional(),workingDirectory:j().optional(),timeout:O().optional()}),Eo=U({agentName:j().optional(),agentVersion:j().optional(),capabilities:G(j()).optional(),startedAt:ke(),lastActivityAt:ke().optional()});U({id:j(),status:os,config:Io,metadata:Eo.optional(),messages:G(ns),error:j().optional()});const _e=U({sessionId:j(),status:os.optional(),message:ns.optional(),error:j().optional(),_meta:Y(j(),X()).optional()}),Ro=_e.extend({type:q("tool_call"),toolCall:Zt,messageId:j().optional()}),_o=_e.extend({type:q("tool_call_update"),toolCallUpdate:no,messageId:j().optional()}),Mo=_e.extend({type:q("tool_output"),toolOutput:U({id:j(),content:G(Oe()).optional(),rawOutput:Y(j(),X()).optional()}),messageId:j().optional()}),Ao=_e.extend({type:q("generic").optional()});Zs([Ro,_o,Mo,Ao]);const Po=[{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 Do{data;constructor(s=Po){this.data=s}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(s){const o=r=>{for(const i of r){if(i.id===s)return i;if(i.children){const a=o(i.children);if(a)return a}}},n=o(this.data);return Promise.resolve(n?.children||[])}async getItemDetails(s){const o=r=>{for(const i of r){if(i.id===s)return i;if(i.children){const a=o(i.children);if(a)return a}}},n=o(this.data);if(!n)throw new Error(`Item with id ${s} not found`);return Promise.resolve(n)}}const Uo=[{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 en(tn(t))}const Lo=de("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"}}),ue=l.forwardRef(({className:t,variant:s,size:o,asChild:n=!1,...r},i)=>{const a=n?ve:"button";return e.jsx(a,{className:y(Lo({variant:s,size:o,className:t})),ref:i,...r})});ue.displayName="Button";const zo=l.forwardRef(({className:t,...s},o)=>e.jsx("div",{ref:o,className:y("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));zo.displayName="Card";const Fo=l.forwardRef(({className:t,...s},o)=>e.jsx("div",{ref:o,className:y("flex flex-col space-y-1.5 p-6",t),...s}));Fo.displayName="CardHeader";const Oo=l.forwardRef(({className:t,...s},o)=>e.jsx("div",{ref:o,className:y("text-2xl font-semibold leading-none tracking-tight",t),...s}));Oo.displayName="CardTitle";const $o=l.forwardRef(({className:t,...s},o)=>e.jsx("div",{ref:o,className:y("text-sm text-muted-foreground",t),...s}));$o.displayName="CardDescription";const Bo=l.forwardRef(({className:t,...s},o)=>e.jsx("div",{ref:o,className:y("p-6 pt-0",t),...s}));Bo.displayName="CardContent";const Ho=l.forwardRef(({className:t,...s},o)=>e.jsx("div",{ref:o,className:y("flex items-center p-6 pt-0",t),...s}));Ho.displayName="CardFooter";const as=l.forwardRef(({title:t,titleElement:s,description:o,guideUrl:n,guideText:r="Guide",suggestedPrompts:i=[],onPromptClick:a,onGuideClick:u,onOpenFiles:p,onOpenSettings:d,toolsAndMcpsCount:c,onPromptHover:h,onPromptLeave:f,className:b,...v},m)=>{const x=S=>{a?.(S)},g=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),u?.()},w=[];for(let S=0;S<i.length;S+=2)w.push(i.slice(S,S+2));return e.jsxs("div",{ref:m,className:y("flex flex-col items-start",b),...v,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:o}),(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(he,{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(he,{className:"size-4 text-foreground shrink-0"})]})]}),(n||u)&&e.jsxs("button",{type:"button",onClick:g,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:r}),e.jsx(he,{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:w.map(S=>e.jsx("div",{className:"flex gap-2.5 items-center",children:S.map(T=>e.jsx("button",{type:"button",onClick:()=>x(T),onMouseEnter:()=>h?.(T),onMouseLeave:()=>f?.(),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:T})},T))},S.join("-")))})]})]})});as.displayName="ChatEmptyState";const rs=l.createContext(void 0),qe=()=>{const t=l.useContext(rs);if(!t)throw new Error("ChatHeader components must be used within ChatHeader.Root");return t},is=l.forwardRef(({defaultExpanded:t=!1,expanded:s,onExpandedChange:o,className:n,children:r,...i},a)=>{const[u,p]=l.useState(t),d=s??u,c=l.useCallback(v=>{p(v),o?.(v)},[o]),h=l.Children.toArray(r),f=h.find(v=>l.isValidElement(v)&&typeof v.type=="function"&&v.type.displayName==="ChatHeader.ExpandablePanel"),b=h.filter(v=>v!==f);return e.jsxs(rs.Provider,{value:{isExpanded:d,setIsExpanded:c},children:[e.jsx("div",{ref:a,className:y("flex items-center justify-between px-6 py-4",n),...i,children:b}),f]})});is.displayName="ChatHeader.Root";const Wo=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("h1",{ref:n,className:y("m-0 text-subheading font-semibold",t),...o,children:s}));Wo.displayName="ChatHeader.Title";const Vo=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("flex items-center gap-3",t),...o,children:s}));Vo.displayName="ChatHeader.Actions";const qo=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"}},Go=t=>{switch(t){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},Qo=l.forwardRef(({status:t,statusText:s,className:o,...n},r)=>{const i=s??Go(t),a=qo(t);return e.jsxs("div",{ref:r,className:y("flex items-center gap-2",o),...n,children:[e.jsx("div",{className:y("h-2 w-2 rounded-full",a)}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:i})]})});Qo.displayName="ChatHeader.StatusIndicator";const Ko=l.forwardRef(({icon:t,className:s,children:o,onClick:n,...r},i)=>{const{isExpanded:a,setIsExpanded:u}=qe(),p=d=>{u(!a),n?.(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":a?"Collapse header":"Expand header",...r,children:[t&&e.jsx("div",{className:y("transition-transform duration-200",a&&"rotate-180"),children:t}),o]})});Ko.displayName="ChatHeader.Toggle";const ls=l.forwardRef(({className:t,children:s,...o},n)=>{const{isExpanded:r}=qe();return r?e.jsx("div",{ref:n,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),...o,children:s}):null});ls.displayName="ChatHeader.ExpandablePanel";const cs=l.forwardRef(({commands:t=[],showCommandMenu:s,commandMenuQuery:o,selectedMenuIndex:n,setSelectedMenuIndex:r,setMenuItemCount:i,triggerCounter:a,onChange:u,className:p,...d},c)=>{const h=l.useCallback((b,v)=>{const m=b.toLowerCase(),x=v.toLowerCase();if(!v)return 1;if(m.includes(x))return 1-x.length/m.length;let g=0;for(let w=0;w<m.length&&g<x.length;w++)m[w]===x[g]&&g++;return g===x.length?.5-g/m.length:0},[]),f=l.useMemo(()=>t.map(b=>({...b,score:Math.max(h(b.label,o),b.description?h(b.description,o):0)})).filter(b=>b.score>0).sort((b,v)=>v.score-b.score),[t,o,h]);return l.useEffect(()=>{i(f.length)},[f.length,i]),l.useEffect(()=>{r(0)},[r]),l.useEffect(()=>{a>0&&f[n]&&(f[n].onSelect(),u(""))},[a,f,n,u]),!s||f.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:f.map((b,v)=>e.jsxs("button",{type:"button",onClick:()=>b.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",v===n&&"bg-muted"),children:[b.icon&&e.jsx("span",{className:"shrink-0 mt-0.5",children:b.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:b.label}),b.description&&e.jsx("div",{className:"text-caption text-muted-foreground truncate",children:b.description})]})]},b.id))})]})});cs.displayName="ChatInputCommandMenu";const ds=l.createContext(void 0),Me=()=>{const t=l.useContext(ds);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},us=l.forwardRef(({client:t,startSession:s,value:o,onChange:n,onSubmit:r,disabled:i=!1,isSubmitting:a,submitOnEnter:u=!0,className:p,children:d,...c},h)=>{const f=l.useRef(null),b=l.useCallback(async()=>Promise.resolve(null),[]),v=ao(t??null,s??b),m=P(W=>W.isStreaming),{addToHistory:x,navigatePrevious:g,navigateNext:w,resetNavigation:S}=lo(),T=t&&s,C=T?v.value:o||"",N=T?v.onChange:n||(()=>{}),M=T?v.onSubmit:r||(async()=>{}),A=T?v.isSubmitting||m:a||!1,D=l.useCallback(async()=>{const W=C.trim();W&&x(W),await M()},[C,x,M]),[R,F]=l.useState(!1),[$,k]=l.useState(""),[H,K]=l.useState(0),[Q,I]=l.useState(0),[z,B]=l.useState(0),_=l.useCallback(()=>{B(W=>W+1)},[]),E=async W=>{W.preventDefault(),C.trim()&&!A&&!i&&(await D(),setTimeout(()=>{f.current?.focus()},0))},V=W=>{const se=W.target;!(se.tagName==="BUTTON"||se.tagName==="INPUT"||se.tagName==="TEXTAREA"||se.closest("button"))&&f.current&&f.current.focus()},le=W=>{const se=W.target;!(se.tagName==="BUTTON"||se.tagName==="INPUT"||se.tagName==="TEXTAREA"||se.closest("button"))&&W.key===" "&&(W.preventDefault(),f.current&&f.current.focus())};return l.useEffect(()=>{const W=document.querySelector('textarea[name="chat-input"]');W&&f.current!==W&&(f.current=W)},[]),l.useEffect(()=>{!C&&f.current&&(f.current.style.height="auto",f.current.style.overflowY="hidden")},[C]),e.jsx(ds.Provider,{value:{value:C,onChange:N,onSubmit:D,disabled:i,isSubmitting:A,submitOnEnter:u,showCommandMenu:R,setShowCommandMenu:F,commandMenuQuery:$,setCommandMenuQuery:k,selectedMenuIndex:H,setSelectedMenuIndex:K,menuItemCount:Q,setMenuItemCount:I,triggerMenuSelect:_,triggerCounter:z,navigateHistoryPrevious:g,navigateHistoryNext:w,resetHistoryNavigation:S},children:e.jsx("form",{ref:h,onSubmit:E,onClick:V,onKeyDown:le,className:y("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...c,children:d})})});us.displayName="ChatInput.Root";const ps=l.forwardRef(({asChild:t=!1,className:s,onKeyDown:o,onFilesDropped:n,children:r,...i},a)=>{const{value:u,onChange:p,onSubmit:d,disabled:c,isSubmitting:h,submitOnEnter:f,showCommandMenu:b,setShowCommandMenu:v,setCommandMenuQuery:m,setSelectedMenuIndex:x,menuItemCount:g,triggerMenuSelect:w,navigateHistoryPrevious:S,navigateHistoryNext:T,resetHistoryNavigation:C}=Me(),N=l.useRef(null),[M,A]=l.useState(!1),D=l.useCallback(I=>{N.current=I,typeof a=="function"?a(I):a&&(a.current=I)},[a]),R=I=>new Promise((z,B)=>{const _=new FileReader;_.readAsDataURL(I),_.onload=()=>{const E=_.result.split(",")[1];z(E||"")},_.onerror=E=>B(E)}),Q={ref:D,name:"chat-input",value:u,onChange:I=>{const z=I.target.value;if(p(z),C(),z.startsWith("/")&&!z.includes(`
6
- `)){v(!0);const E=z.slice(1);m(E)}else v(!1),m("");const B=N.current;if(!B)return;B.style.height="auto";const _=Math.min(B.scrollHeight,164);B.style.height=`${_}px`,B.scrollHeight>164?B.style.overflowY="auto":B.style.overflowY="hidden"},onKeyDown:I=>{if(b&&g>0){if(I.key==="ArrowDown"){I.preventDefault(),x(z=>(z+1)%g);return}else if(I.key==="ArrowUp"){I.preventDefault(),x(z=>(z-1+g)%g);return}else if(I.key==="Enter"&&!I.shiftKey){I.preventDefault(),w();return}else if(I.key==="Escape"){I.preventDefault(),v(!1),m("");return}}if(!b){const z=N.current,B=z?.selectionStart===0&&z?.selectionEnd===0,_=z?.selectionStart===u.length&&z?.selectionEnd===u.length,E=u.includes(`
7
- `);if(I.key==="ArrowUp"&&(B||!u||!E)){const V=S(u);if(V!==null){I.preventDefault(),p(V),setTimeout(()=>{N.current&&(N.current.selectionStart=V.length,N.current.selectionEnd=V.length)},0);return}}else if(I.key==="ArrowDown"&&(_||!u||!E)){const V=T();if(V!==null){I.preventDefault(),p(V),setTimeout(()=>{N.current&&(N.current.selectionStart=V.length,N.current.selectionEnd=V.length)},0);return}}}f&&I.key==="Enter"&&!I.shiftKey&&(u.trim()&&!h&&!c?(I.preventDefault(),d()):(h||c)&&I.preventDefault()),o?.(I)},onDrop:async I=>{I.preventDefault(),A(!1);const z=I.dataTransfer.files;if(!z||z.length===0||!n)return;const B=[];for(const _ of Array.from(z))if(_.type.startsWith("image/"))try{const E=await R(_);B.push({name:_.name,path:_.name,size:_.size,mimeType:_.type,data:E})}catch(E){console.error("Failed to process dropped file:",_.name,E)}B.length>0&&n(B)},onDragOver:I=>{I.preventDefault(),A(!0)},onDragLeave:I=>{I.preventDefault(),A(!1)},disabled:c,...i};return t&&l.isValidElement(r)?l.cloneElement(r,Q):e.jsx("textarea",{...Q,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",M&&"ring-2 ring-primary ring-offset-2",s)})});ps.displayName="ChatInput.Field";const ms=l.forwardRef(({asChild:t=!1,className:s,disabled:o,children:n,...r},i)=>{const{value:a,disabled:u,isSubmitting:p}=Me(),d=o||u||p||!a.trim(),c=t?ve:ue;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),...r,children:n})});ms.displayName="ChatInput.Submit";const fs=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("flex items-center justify-between p-2",t),...o,children:s}));fs.displayName="ChatInput.Toolbar";const gs=l.forwardRef(({asChild:t=!1,className:s,children:o,onClick:n,...r},i)=>{const{value:a,onChange:u,setShowCommandMenu:p,setCommandMenuQuery:d}=Me(),c=f=>{a.startsWith("/")||(u("/"),p(!0),d("")),n?.(f)},h=t?ve:ue;return e.jsx(h,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:c,...r,children:o||e.jsx(vn,{className:"size-4"})})});gs.displayName="ChatInput.Actions";const hs=l.forwardRef(({asChild:t=!1,className:s,children:o,onFilesSelected:n,...r},i)=>{const a=l.useRef(null),u=h=>new Promise((f,b)=>{const v=new FileReader;v.readAsDataURL(h),v.onload=()=>{const m=v.result.split(",")[1];f(m||"")},v.onerror=m=>b(m)}),p=async h=>{const f=h.target.files;if(!f||f.length===0)return;const b=[];for(const v of Array.from(f))if(v.type.startsWith("image/"))try{const m=await u(v);b.push({name:v.name,path:v.name,size:v.size,mimeType:v.type,data:m})}catch(m){console.error("Failed to process file:",v.name,m)}b.length>0&&n&&n(b),a.current&&(a.current.value="")},d=h=>{h.preventDefault(),a.current?.click()},c=t?ve:ue;return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:a,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,...r,children:o||e.jsx(wn,{className:"size-4"})})]})});hs.displayName="ChatInput.Attachment";const xs=l.forwardRef(({asChild:t=!1,className:s,children:o,...n},r)=>{const i=t?ve:ue;return e.jsx(i,{ref:r,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),...n,children:o||e.jsx(jn,{className:"size-4"})})});xs.displayName="ChatInput.VoiceInput";const bs=l.forwardRef(({commands:t=[],className:s,onChange:o,...n},r)=>{const{showCommandMenu:i,commandMenuQuery:a,selectedMenuIndex:u,setSelectedMenuIndex:p,setMenuItemCount:d,triggerCounter:c,onChange:h}=Me();return e.jsx(cs,{ref:r,commands:t,showCommandMenu:i,commandMenuQuery:a,selectedMenuIndex:u,setSelectedMenuIndex:p,setMenuItemCount:d,triggerCounter:c,onChange:h,className:s,...n})});bs.displayName="ChatInput.CommandMenu";const Jo=({className:t,...s})=>e.jsx(qs,{className:y("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",t),...s}),ys=({className:t,...s})=>e.jsx(Gs,{className:y(t),...s}),Yo=({withHandle:t,className:s,...o})=>e.jsx(Qs,{className:y("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",s),...o,children:t&&e.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"h-2.5 w-2.5",children:[e.jsx("title",{children:"Resize Handle"}),e.jsx("circle",{cx:"9",cy:"12",r:"1"}),e.jsx("circle",{cx:"9",cy:"5",r:"1"}),e.jsx("circle",{cx:"9",cy:"19",r:"1"}),e.jsx("circle",{cx:"15",cy:"12",r:"1"}),e.jsx("circle",{cx:"15",cy:"5",r:"1"}),e.jsx("circle",{cx:"15",cy:"19",r:"1"})]})})}),Xo=({...t})=>e.jsx(sn,{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}),Ge=l.createContext(void 0),ge=()=>{const t=l.useContext(Ge);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},vs=l.forwardRef(({defaultSidebarOpen:t=!1,defaultPanelSize:s="hidden",defaultActiveTab:o="todo",className:n,children:r,...i},a)=>{const[u,p]=l.useState(t),[d,c]=l.useState(s),[h,f]=l.useState(o);return e.jsx(Ge.Provider,{value:{sidebarOpen:u,setSidebarOpen:p,panelSize:d,setPanelSize:c,activeTab:h,setActiveTab:f},children:e.jsx("div",{ref:a,className:y("flex h-screen flex-row bg-background text-foreground",n),...i,children:e.jsx(Jo,{direction:"horizontal",className:"flex-1",children:r})})})});vs.displayName="ChatLayout.Root";const Zo=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("relative z-10 border-b border-border bg-card shrink-0",t),...o,children:s}));Zo.displayName="ChatLayout.Header";const ws=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx(ys,{defaultSize:70,minSize:50,children:e.jsx("div",{ref:n,className:y("flex flex-1 flex-col overflow-hidden h-full",t),...o,children:s})}));ws.displayName="ChatLayout.Main";const js=l.forwardRef(({showToaster:t=!0,className:s,children:o,...n},r)=>e.jsxs("div",{ref:r,className:y("relative flex flex-1 flex-col overflow-hidden",s),...n,children:[o,t&&e.jsx(Xo,{})]}));js.displayName="ChatLayout.Body";const Ns=l.forwardRef(({className:t,children:s,onScrollChange:o,showScrollToBottom:n=!0,...r},i)=>{const a=l.useRef(null),[u,p]=l.useState(!0),d=l.useRef(!0),c=l.useRef(!1),h=l.useRef(0),f=l.useRef(0),b=l.useRef(!1);l.useEffect(()=>{d.current=u},[u]),l.useImperativeHandle(i,()=>a.current);const v=l.useCallback(()=>{const g=a.current;if(!g)return!0;const{scrollTop:w,scrollHeight:S,clientHeight:T}=g;return w+T>=S-100},[]),m=l.useCallback((g="smooth")=>{const w=a.current;w&&(b.current&&g==="instant"||(g==="smooth"&&(b.current=!0,setTimeout(()=>{b.current=!1},500)),w.scrollTo({top:w.scrollHeight,behavior:g})))},[]);l.useEffect(()=>{const g=a.current;if(!g)return;let w;const S=()=>{c.current=!0,clearTimeout(w);const T=v();p(T),d.current=T,o?.(T),w=setTimeout(()=>{c.current=!1},150)};return g.addEventListener("scroll",S,{passive:!0}),()=>{g.removeEventListener("scroll",S),clearTimeout(w)}},[v,o]),l.useEffect(()=>{const g=a.current;if(!g)return;const w=()=>{if(!d.current||c.current)return;const C=Date.now(),N=C-f.current,M=g.scrollHeight,A=M-h.current;f.current=C,h.current=M;const D=A>80&&N>150;requestAnimationFrame(()=>{m(D?"smooth":"instant"),p(!0),d.current=!0})},S=new MutationObserver(w);S.observe(g,{childList:!0,subtree:!0,characterData:!0});const T=new ResizeObserver(w);T.observe(g);for(const C of Array.from(g.children))T.observe(C);return h.current=g.scrollHeight,()=>{S.disconnect(),T.disconnect()}},[m]);const x=l.useCallback(()=>{p(!0),d.current=!0,m("smooth")},[m]);return e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsx("div",{ref:a,className:y("h-full overflow-y-auto flex flex-col",t),tabIndex:0,...r,children:e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s})}),n&&e.jsx("button",{type:"button",onClick:x,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",u?"pointer-events-none scale-0 opacity-0":"pointer-events-auto scale-100 opacity-100"),"aria-label":"Scroll to bottom",children:e.jsx(Nn,{className:"size-4"})})]})});Ns.displayName="ChatLayout.Messages";const Ss=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("bg-linear-to-t from-background to-transparent px-4 pb-4",t),...o,children:e.jsx("div",{className:"mx-auto max-w-chat",children:s})}));Ss.displayName="ChatLayout.Footer";const ea=l.forwardRef(({className:t,children:s,...o},n)=>{const{sidebarOpen:r}=ge();return r?e.jsx("div",{ref:n,className:y("border-r border-border bg-card w-64 overflow-y-auto",t),...o,children:s}):null});ea.displayName="ChatLayout.Sidebar";const Cs=l.forwardRef(({breakpoint:t="lg",className:s,children:o,...n},r)=>{const{panelSize:i}=ge(),[a,u]=l.useState(28);return l.useEffect(()=>{const p=()=>{const c=450/window.innerWidth*100;u(Math.max(c,28))};return p(),window.addEventListener("resize",p),()=>{window.removeEventListener("resize",p)}},[]),i==="hidden"?null:e.jsxs(e.Fragment,{children:[e.jsx(Yo,{withHandle:!0,className:"group-hover:opacity-100 opacity-0 transition-opacity"}),e.jsx(ys,{defaultSize:30,minSize:a,maxSize:40,className:"group",children:e.jsx("div",{ref:r,className:y("hidden h-full border-l border-border bg-card overflow-y-auto transition-all duration-300",t==="md"&&"md:block",t==="lg"&&"lg:block",t==="xl"&&"xl:block",t==="2xl"&&"2xl:block",s),...n,children:o})})]})});Cs.displayName="ChatLayout.Aside";const Qe=rn,Ke=ln,ta=l.forwardRef(({className:t,inset:s,children:o,...n},r)=>e.jsxs(gt,{ref:r,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),...n,children:[o,e.jsx(he,{className:"ml-auto h-4 w-4"})]}));ta.displayName=gt.displayName;const sa=l.forwardRef(({className:t,...s},o)=>e.jsx(ht,{ref:o,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}));sa.displayName=ht.displayName;const Ae=l.forwardRef(({className:t,sideOffset:s=4,...o},n)=>e.jsx(an,{children:e.jsx(xt,{ref:n,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),...o})}));Ae.displayName=xt.displayName;const ne=l.forwardRef(({className:t,inset:s,...o},n)=>e.jsx(bt,{ref:n,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),...o}));ne.displayName=bt.displayName;const na=l.forwardRef(({className:t,children:s,...o},n)=>e.jsxs(yt,{ref:n,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),...o,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(vt,{children:e.jsx(Ot,{className:"h-4 w-4"})})}),s]}));na.displayName=yt.displayName;const oa=l.forwardRef(({className:t,children:s,...o},n)=>e.jsxs(wt,{ref:n,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),...o,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(vt,{children:e.jsx($e,{className:"h-2 w-2 fill-current"})})}),s]}));oa.displayName=wt.displayName;const Ts=l.forwardRef(({className:t,inset:s,...o},n)=>e.jsx(jt,{ref:n,className:y("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...o}));Ts.displayName=jt.displayName;const Ie=l.forwardRef(({className:t,...s},o)=>e.jsx(Nt,{ref:o,className:y("-mx-1 my-1 h-px bg-border",t),...s}));Ie.displayName=Nt.displayName;function ks({item:t,level:s=0,onSelect:o,selectedId:n,isDropTarget:r=!1,onDownload:i,onRename:a,onDelete:u}){const[p,d]=l.useState(!0),c=n===t.id,h=()=>{t.type==="folder"&&d(!p)},f=()=>{o?.(t),t.type==="folder"&&h()},b=m=>{m.key==="Enter"||m.key===" "?(m.preventDefault(),f()):m.key==="ArrowRight"&&t.type==="folder"&&!p?(m.preventDefault(),d(!0)):m.key==="ArrowLeft"&&t.type==="folder"&&p&&(m.preventDefault(),d(!1))},v=()=>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",v(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",c&&"bg-accent",r&&["bg-accent","border border-dashed border-border-dark"]),onClick:f,onKeyDown:b,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.type==="folder"?p?e.jsx(Sn,{className:"size-4"}):e.jsx(Cn,{className:"size-4"}):e.jsx(Tn,{className:"size-4"})}),e.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:t.name}),e.jsxs(Qe,{children:[e.jsx(Ke,{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:m=>{m.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(kn,{className:"size-4"})})}),e.jsxs(Ae,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:m=>m.stopPropagation(),children:[i&&e.jsx(ne,{onClick:m=>{m.stopPropagation(),i(t)},children:"Download"}),a&&e.jsx(ne,{onClick:m=>{m.stopPropagation(),a(t)},children:"Rename"}),(i||a)&&u&&e.jsx(Ie,{}),u&&e.jsx(ne,{className:"text-destructive focus:text-destructive focus:bg-muted",onClick:m=>{m.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(ie,{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(m=>e.jsx(ks,{item:m,level:s+1,...o&&{onSelect:o},...n&&{selectedId:n},...i&&{onDownload:i},...a&&{onRename:a},...u&&{onDelete:u}},m.id))})]})}const aa=new Do;function ra({className:t,provider:s=aa,onItemSelect:o,onDownload:n,onRename:r,onDelete:i}){const[a,u]=l.useState([]),[p,d]=l.useState(),[c,h]=l.useState(!0),[f,b]=l.useState();l.useEffect(()=>{(async()=>{try{h(!0);const x=await s.getRootItems();u(x),b(void 0)}catch(x){b(x instanceof Error?x.message:"Failed to load items")}finally{h(!1)}})()},[s]);const v=m=>{d(m.id),o?.(m)};return c?e.jsx("div",{className:y("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):f?e.jsx("div",{className:y("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",f]})}):e.jsx("div",{className:y("flex flex-col",t),children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items found"}):a.map(m=>e.jsx(ks,{item:m,onSelect:v,...p&&{selectedId:p},...n&&{onDownload:n},...r&&{onRename:r},...i&&{onDelete:i}},m.id))})}const Is=l.forwardRef(({source:t,isSelected:s,className:o,...n},r)=>e.jsxs("button",{ref:r,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",o),onClick:()=>window.open(t.url,"_blank"),...n,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})]})]}));Is.displayName="SourceListItem";const Es=l.forwardRef(({todo:t,className:s,...o},n)=>{const r=t.status==="completed";return e.jsxs("div",{ref:n,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,...o,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.status==="completed"?e.jsx($t,{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($e,{className:"size-4 text-foreground"})}),e.jsx("p",{className:y("flex-1 text-foreground",r&&"line-through text-muted-foreground",t.status==="in_progress"&&"font-medium"),children:t.text})]})});Es.displayName="TodoListItem";function ia(){return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(Re,{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 Je=l.forwardRef(({client:t,todos:s,className:o,...n},r)=>{const i=s||[];return i.length===0?e.jsx("div",{ref:r,className:y("h-full",o),...n,children:e.jsx(ia,{})}):e.jsx("div",{ref:r,className:y("space-y-2 max-h-64 overflow-y-auto",o),...n,children:i.map(a=>e.jsx(Es,{todo:a},a.id))})});Je.displayName="TodoList";const Pe=l.forwardRef(({todos:t=[],className:s,...o},n)=>e.jsx("div",{ref:n,className:y("h-full",s),...o,children:e.jsx(Je,{todos:t,className:"h-full"})}));Pe.displayName="TodoTabContent";const De=l.forwardRef(({files:t=[],provider:s,onFileSelect:o,className:n,...r},i)=>{const a=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",n),...r,children:e.jsx(ra,{...s&&{provider:s},onItemSelect:d=>{d.type==="file"&&o&&o(d.path||d.name)},onDownload:a,onRename:u,onDelete:p,className:"h-full"})})});De.displayName="FilesTabContent";const Ue=l.forwardRef(({sources:t,className:s,...o},n)=>{const r=t&&t.length>0?t:Uo;return e.jsx("div",{ref:n,className:y("space-y-2",s),...o,children:r.map(i=>e.jsx(Is,{source:i},i.id))})});Ue.displayName="SourcesTabContent";const la=l.forwardRef(({data:t,className:s,...o},n)=>e.jsxs("div",{ref:n,className:y("space-y-4",s),...o,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]})]})]}));la.displayName="DatabaseTabContent";const Ye=l.forwardRef(({tools:t=[],mcps:s=[],subagents:o=[],className:n,...r},i)=>e.jsxs("div",{ref:i,className:y("space-y-6",n),...r,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(a=>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:a.prettyName||a.name}),a.description&&e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-1",children:a.description})]},a.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(a=>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:a.name}),e.jsxs("div",{className:"text-caption text-muted-foreground mt-1",children:["Transport: ",a.transport]})]},a.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"}),o.length>0?e.jsx("div",{className:"space-y-2",children:o.map(a=>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:a.name}),e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-2",children:a.description})]},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No subagents available"})]})]}));Ye.displayName="SettingsTabContent";const Xe=cn,xe=l.forwardRef(({className:t,...s},o)=>e.jsx(St,{ref:o,className:y("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));xe.displayName=St.displayName;const be=l.forwardRef(({className:t,...s},o)=>e.jsx(Ct,{ref:o,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}));be.displayName=Ct.displayName;const J=l.forwardRef(({className:t,...s},o)=>e.jsx(Tt,{ref:o,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=Tt.displayName;const ca=l.forwardRef(({client:t,todos:s,variant:o="animated",showIcons:n=!1,visibleTabs:r=["todo","files","database"],className:i,...a},u)=>{const p=s||[],[d,c]=l.useState(r[0]||"todo"),h=l.useRef(null),f=l.useRef(null);l.useEffect(()=>{const x=setTimeout(()=>{const g=h.current;if(d&&g){const w=f.current;if(w){const S=g.getBoundingClientRect(),T=w.getBoundingClientRect(),C=T.left-S.left,N=T.width,M=C/S.width*100,A=100-(C+N)/S.width*100;g.style.clipPath=`inset(0 ${A.toFixed(2)}% 0 ${M.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(x)},[d]);const v=[{id:"todo",label:o==="pills"?"To-do":"To-Do List",icon:Re},{id:"files",label:"Files",icon:Be},{id:"database",label:"Database",icon:Bt},{id:"sources",label:"Sources",icon:Ht}].filter(m=>r.includes(m.id));return e.jsx("div",{ref:u,className:y("select-none",i),...a,children:e.jsxs(Xe,{value:d,onValueChange:c,className:"w-full",children:[o==="pills"?e.jsx(xe,{className:y("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:v.map(m=>{const x=m.icon;return e.jsxs(be,{value:m.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:[n&&x&&e.jsx(x,{className:"size-4"}),m.label]},m.id)})}):e.jsxs("div",{className:"relative mb-4 border-border",children:[e.jsx(xe,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:v.map(m=>e.jsx(be,{value:m.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:m.label},m.id))}),e.jsx("div",{ref:h,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(xe,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:v.map(m=>e.jsx(be,{value:m.id,ref:d===m.id?f: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:m.label},m.id))})})]}),e.jsx(J,{value:"todo",className:o==="pills"?"mt-0":"",children:o==="pills"?e.jsx(Pe,{todos:p}):e.jsx(Je,{todos:p})}),e.jsx(J,{value:"files",className:o==="pills"?"mt-0":"",children:e.jsx(De,{})}),e.jsx(J,{value:"database",className:o==="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:o==="pills"?"mt-0":"",children:e.jsx(Ue,{})})]})})});ca.displayName="ChatSecondaryPanel";const da=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("flex h-full flex-col",t),...o,children:s}));da.displayName="ChatSidebar.Root";const ua=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("border-b border-border px-4 py-3",t),...o,children:s}));ua.displayName="ChatSidebar.Header";const pa=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("flex-1 overflow-y-auto p-4",t),...o,children:s}));pa.displayName="ChatSidebar.Content";const ma=l.forwardRef(({className:t,children:s,...o},n)=>e.jsx("div",{ref:n,className:y("border-t border-border px-4 py-3",t),...o,children:s}));ma.displayName="ChatSidebar.Footer";const fa=l.forwardRef(({children:t,className:s,...o},n)=>{const[r,i]=l.useState(t),[a,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:n,className:y("text-sm text-foreground opacity-60 transition-opacity duration-300",a?"opacity-0":"opacity-60",s),...o,children:r})});fa.displayName="ChatStatus";const re=oe("gui");function ga({children:t}){const{setPanelSize:s,setActiveTab:o,panelSize:n,activeTab:r}=ge(),i=()=>{n!=="hidden"&&r==="files"?s("hidden"):(s("small"),o("files"))},a=()=>{n!=="hidden"&&r==="settings"?s("hidden"):(s("small"),o("settings"))};return e.jsx(e.Fragment,{children:t({openFiles:i,openSettings:a})})}function ha(){const{panelSize:t,setPanelSize:s}=ge();return l.useEffect(()=>{const o=n=>{(n.metaKey||n.ctrlKey)&&n.key==="b"&&(n.preventDefault(),s(t==="hidden"?"small":"hidden"))};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t,s]),null}function xa(t){const s=new Date(t),n=new Date().getTime()-s.getTime(),r=Math.floor(n/6e4),i=Math.floor(n/36e5),a=Math.floor(n/864e5);return r<1?"Just now":r<60?`${r}m ago`:i<24?`${i}h ago`:a<7?`${a}d ago`:s.toLocaleDateString()}function Ze({agentName:t,client:s,currentSessionId:o}){const[n,r]=l.useState([]),[i,a]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async()=>{if(s){a(!0);try{const f=await s.listSessions();r(f)}catch(f){re.error("Failed to fetch sessions",{error:f})}finally{a(!1)}}},[s]);l.useEffect(()=>{u&&d()},[u,d]);const c=()=>{const f=new URL(window.location.href);f.searchParams.delete("session"),window.location.href=f.toString()},h=f=>{if(f===o){p(!1);return}const b=new URL(window.location.href);b.searchParams.set("session",f),window.location.href=b.toString()};return e.jsxs(Qe,{open:u,onOpenChange:p,children:[e.jsx(Ke,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-heading-4 text-foreground hover:text-foreground/80 transition-colors cursor-pointer",children:[t,e.jsx(ie,{className:y("size-4 text-muted-foreground transition-transform duration-200",u&&"rotate-180")})]})}),e.jsxs(Ae,{align:"start",className:"w-72",children:[e.jsxs(Ts,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Sessions"}),i&&e.jsx("span",{className:"text-caption text-muted-foreground",children:"Loading..."})]}),e.jsx(Ie,{}),e.jsxs(ne,{onClick:c,className:"gap-2",children:[e.jsx(En,{className:"size-4"}),e.jsx("span",{children:"New Session"})]}),n.length>0&&e.jsx(Ie,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto",children:n.map(f=>e.jsxs(ne,{onClick:()=>h(f.sessionId),className:y("flex flex-col items-start gap-0.5 py-2",f.sessionId===o&&"bg-muted/50 font-medium"),children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-paragraph-sm",children:f.firstUserMessage||"Empty session"}),f.sessionId===o&&e.jsx("span",{className:"shrink-0 text-caption text-primary",children:"Current"})]}),e.jsxs("span",{className:"text-caption text-muted-foreground",children:[xa(f.updatedAt)," • ",f.messageCount," ","messages"]})]},f.sessionId))}),n.length===0&&!i&&e.jsx("div",{className:"px-2 py-4 text-center text-paragraph-sm text-muted-foreground",children:"No previous sessions"})]})]})}function ba({client:t,startSession:s,placeholder:o,latestContextSize:n,currentModel:r,commandMenuItems:i}){const a=P(c=>c.input.attachedFiles),u=P(c=>c.addFileAttachment),p=P(c=>c.removeFileAttachment),d=c=>{for(const h of c)u(h)};return e.jsxs(us,{client:t,startSession:s,children:[e.jsx(bs,{commands:i}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border-b border-border",children:a.map((c,h)=>e.jsxs("div",{className:"relative group rounded-md overflow-hidden border border-border",children:[e.jsx("img",{src:`data:${c.mimeType};base64,${c.data}`,alt:c.name,className:"h-20 w-20 object-cover"}),e.jsx("button",{type:"button",onClick:()=>p(h),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(Wt,{className:"size-3"})})]},h))}),e.jsx(ps,{placeholder:o,autoFocus:!0,onFilesDropped:d}),e.jsxs(fs,{children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx(gs,{}),e.jsx(hs,{onFilesSelected:d}),n!=null&&e.jsx(As,{contextSize:n,modelContextWindow:r?.includes("claude")?2e5:128e3})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xs,{}),e.jsx(ms,{children:e.jsx(Rn,{className:"size-4"})})]})]})]})}function ya({todos:t,tools:s,mcps:o,subagents:n}){const{activeTab:r,setActiveTab:i}=ge();return e.jsxs(Xe,{value:r,onValueChange:a=>i(a),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(tt,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(J,{value:"todo",className:"flex-1 p-4 mt-0",children:e.jsx(Pe,{todos:t})}),e.jsx(J,{value:"files",className:"flex-1 p-4 mt-0",children:e.jsx(De,{})}),e.jsx(J,{value:"sources",className:"flex-1 p-4 mt-0",children:e.jsx(Ue,{})}),e.jsx(J,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(Ye,{tools:s??[],mcps:o??[],subagents:n??[]})})]})}function va({agentName:t,showHeader:s,client:o,currentSessionId:n}){const{isExpanded:r,setIsExpanded:i}=qe();return e.jsxs("div",{className:"flex lg:hidden items-center flex-1",children:[s&&e.jsx("div",{className:"flex items-center gap-2 flex-1",children:e.jsx(Ze,{agentName:t,client:o,currentSessionId:n})}),!s&&e.jsx("div",{className:"flex-1"}),e.jsx(Hs,{}),e.jsx(ye,{"aria-label":"Toggle menu",onClick:()=>i(!r),children:e.jsx(qt,{className:y("size-4 text-muted-foreground transition-transform duration-200",r?"":"rotate-180")})})]})}function wa({agentName:t,todos:s,sources:o,showHeader:n,sessionId:r,debuggerUrl:i,tools:a,mcps:u,subagents:p,client:d}){const{panelSize:c,setPanelSize:h}=ge(),f=i?r?`${i}/sessions/${r}`:i:null;return e.jsxs(is,{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:[n&&e.jsx("div",{className:"flex items-center gap-2 flex-1",children:e.jsx(Ze,{agentName:t,client:d,currentSessionId:r})}),!n&&e.jsx("div",{className:"flex-1"}),i&&e.jsx(Rs,{children:e.jsxs(_s,{children:[e.jsx(Ms,{asChild:!0,children:e.jsx(ye,{"aria-label":"View session in debugger",disabled:!f,asChild:!!f,children:f?e.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",children:e.jsx(at,{className:"size-4 text-muted-foreground"})}):e.jsx(at,{className:"size-4 text-muted-foreground"})})}),e.jsx(et,{children:e.jsx("p",{children:r?"View session in debugger":"Open debugger"})})]})}),e.jsx(Hs,{}),e.jsx(ye,{"aria-label":"Toggle sidebar",onClick:()=>{h(c==="hidden"?"small":"hidden")},children:e.jsx(In,{className:"size-4 text-muted-foreground"})})]}),e.jsx(va,{agentName:t,showHeader:n,client:d,currentSessionId:r}),e.jsx(ls,{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(Xe,{defaultValue:"todo",className:"w-full",children:[e.jsx(tt,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"default"}),e.jsx(J,{value:"todo",className:"mt-4",children:e.jsx(Pe,{todos:s})}),e.jsx(J,{value:"files",className:"mt-4",children:e.jsx(De,{})}),e.jsx(J,{value:"sources",className:"mt-4",children:e.jsx(Ue,{sources:o})}),e.jsx(J,{value:"settings",className:"mt-4",children:e.jsx(Ye,{tools:a??[],mcps:u??[],subagents:p??[]})})]})})]})}function ja({client:t,initialSessionId:s,error:o,debuggerUrl:n}){const{connectionStatus:r,connect:i,sessionId:a,startSession:u}=ro(t,s),{messages:p,sendMessage:d}=es(t,u);uo(t);const c=P(_=>_.error),h=P(_=>_.currentModel),[f,b]=l.useState("Agent"),[v,m]=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."),[x,g]=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?"]),[w,S]=l.useState([]),[T,C]=l.useState([]),[N,M]=l.useState([]),[A,D]=l.useState(typeof window<"u"?window.innerWidth>=1024:!0),[R,F]=l.useState("Type a message or / for commands..."),[$,k]=l.useState(!1);l.useEffect(()=>{re.debug("Connection status changed",{status:r}),r==="error"&&c&&re.error("Connection error occurred",{error:c})},[r,c]),l.useEffect(()=>{if(t){const _=t.getCurrentSession();_?.metadata?.agentName&&b(_.metadata.agentName);const E=t.getAgentInfo();E.displayName?b(E.displayName):E.name&&b(E.name),E.description&&m(E.description),E.suggestedPrompts&&E.suggestedPrompts.length>0&&g(E.suggestedPrompts),E.tools&&E.tools.length>0&&(S(E.tools),re.info("Agent tools loaded",{tools:E.tools})),E.mcps&&E.mcps.length>0&&(C(E.mcps),re.info("Agent MCPs loaded",{mcps:E.mcps})),E.subagents&&E.subagents.length>0&&(M(E.subagents),re.info("Agent subagents loaded",{subagents:E.subagents})),E.uiConfig?.hideTopBar&&k(!0)}},[t,a,r]),l.useEffect(()=>{const _=window.matchMedia("(min-width: 1024px)"),E=V=>{D(V.matches)};return D(_.matches),_.addEventListener("change",E),()=>{_.removeEventListener("change",E)}},[]);const H=_=>{F(_)},K=()=>{F("Type a message or / for commands...")};if(o)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:o}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})});const Q=P(oo),I=[{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"}],z=P(_=>_.latestContextSize),B=[{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx(Vt,{className:"h-4 w-4"}),category:"action",onSelect:()=>{re.info("User opened settings")}}];return e.jsxs(vs,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsx(ha,{}),e.jsxs(ws,{children:[!$&&e.jsx(wa,{agentName:f,todos:Q,sources:I,showHeader:p.length>0,sessionId:a,tools:w,mcps:T,subagents:N,client:t,...n&&{debuggerUrl:n}}),r==="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(js,{children:[e.jsx(Ns,{children:p.length===0?e.jsx(ga,{children:({openFiles:_,openSettings:E})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(as,{title:f,titleElement:e.jsx(Ze,{agentName:f,client:t,currentSessionId:a}),description:v,suggestedPrompts:x,onPromptClick:V=>{d(V),F("Type a message or / for commands..."),re.info("Prompt clicked",{prompt:V})},onPromptHover:H,onPromptLeave:K,onOpenFiles:_,onOpenSettings:E,toolsAndMcpsCount:w.length+T.length+N.length})})}):e.jsx("div",{className:"flex flex-col px-4",children:p.map((_,E)=>{const V=E===0,le=V?null:p[E-1];let W="mt-2";return V?W=_.role==="assistant"?"mt-8":"mt-2":_.role==="user"?W=(le?.role==="user","mt-4"):_.role==="assistant"&&(W=le?.role==="assistant"?"mt-2":"mt-6"),e.jsx(Ds,{message:_,className:W,isLastMessage:E===p.length-1,children:e.jsx(Fs,{message:_,thinkingDisplayStyle:"collapsible"})},_.id)})})}),e.jsx(Ss,{children:e.jsx(ba,{client:t,startSession:u,placeholder:R,latestContextSize:z,currentModel:h,commandMenuItems:B})})]})]}),A&&e.jsx(Cs,{breakpoint:"lg",children:e.jsx(ya,{todos:Q,tools:w,mcps:T,subagents:N})})]})}const Rs=dn,_s=un,Ms=pn,et=l.forwardRef(({className:t,sideOffset:s=4,...o},n)=>e.jsx(kt,{ref:n,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),...o}));et.displayName=kt.displayName;const As=l.forwardRef(({contextSize:t,modelContextWindow:s,className:o,...n},r)=>{const i=Math.max(t.totalEstimated,t.llmReportedInputTokens??0),a=i/s*100,u=`${a.toFixed(1)}%`,p=Math.min(100,Math.max(0,a)),c=(w=>w<50?"text-foreground":w<75?"text-yellow-500":"text-red-500")(a),h=w=>i===0?"0.0%":`${(w/i*100).toFixed(1)}%`,f=16,b=2,v=(f-b)/2,m=f/2,x=2*Math.PI*v,g=x-p/100*x;return e.jsx(Rs,{children:e.jsxs(_s,{children:[e.jsx(Ms,{asChild:!0,children:e.jsx(ue,{ref:r,type:"button",variant:"ghost",size:"icon",className:y("rounded-full cursor-default",c,o),...n,children:e.jsxs("svg",{width:f,height:f,viewBox:`0 0 ${f} ${f}`,className:"transform -rotate-90",children:[e.jsx("circle",{cx:m,cy:m,r:v,stroke:"currentColor",strokeWidth:b,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:m,cy:m,r:v,stroke:"currentColor",strokeWidth:b,fill:"transparent",strokeDasharray:x,strokeDashoffset:g,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:["(",h(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:["(",h(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:["(",h(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:["(",h(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:["(",h(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:["(",h(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:["(",h(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:i.toLocaleString()}),e.jsxs("span",{children:["(",u,")"]})]})})]})})]})})});As.displayName="ContextUsageButton";const Na=l.forwardRef(({autoScroll:t=!0,isStreaming:s=!1,scrollBehavior:o="smooth",scrollThreshold:n=100,showScrollButton:r=!0,scrollButton:i,className:a,children:u,...p},d)=>{const c=l.useRef(null),[h,f]=l.useState(!0),[b,v]=l.useState(!1),m=l.useRef(0);l.useImperativeHandle(d,()=>{if(!c.current)throw new Error("Container ref not initialized");return c.current});const x=l.useCallback(()=>{const w=c.current;if(!w)return;const{scrollTop:S,scrollHeight:T,clientHeight:C}=w,M=T-S-C<n;f(M),v(!M&&r),m.current=S},[n,r]),g=l.useCallback((w=o)=>{const S=c.current;S&&S.scrollTo({top:S.scrollHeight,behavior:w})},[o]);return l.useEffect(()=>{!t||!c.current||(s&&h?g("auto"):!s&&h&&g())},[t,s,h,g]),l.useEffect(()=>{const w=c.current;if(!w)return;const S=()=>{x()};return w.addEventListener("scroll",S,{passive:!0}),x(),()=>{w.removeEventListener("scroll",S)}},[x]),l.useEffect(()=>{const w=c.current;if(!w)return;const S=new ResizeObserver(()=>{h&&t&&g("auto")});return S.observe(w),()=>{S.disconnect()}},[h,t,g]),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",a),...p,children:e.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:u})}),b&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||e.jsxs("button",{type:"button",onClick:()=>g(),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"]})})]})});Na.displayName="Conversation";const Sa=mn,Ps=l.forwardRef(({className:t,...s},o)=>e.jsx(It,{ref:o,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}));Ps.displayName=It.displayName;const Ca=l.forwardRef(({className:t,children:s,...o},n)=>e.jsxs(Sa,{children:[e.jsx(Ps,{}),e.jsxs(Et,{ref:n,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),...o,children:[s,e.jsxs(fn,{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(Wt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ca.displayName=Et.displayName;const Ta=l.forwardRef(({className:t,...s},o)=>e.jsx(Rt,{ref:o,className:y("text-subheading font-semibold leading-none tracking-tight",t),...s}));Ta.displayName=Rt.displayName;const ka=l.forwardRef(({className:t,...s},o)=>e.jsx(_t,{ref:o,className:y("text-paragraph-sm text-muted-foreground",t),...s}));ka.displayName=_t.displayName;const ye=l.forwardRef(({className:t,...s},o)=>e.jsx(ue,{ref:o,variant:"ghost",size:"icon",className:y("rounded-full",t),...s}));ye.displayName="IconButton";const Ia=de("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"}}),Ea=l.forwardRef(({className:t,type:s,variant:o,...n},r)=>e.jsx("input",{type:s,className:y(Ia({variant:o,className:t})),ref:r,...n}));Ea.displayName="Input";const Ra=l.forwardRef(({className:t,...s},o)=>e.jsx(Mt,{ref:o,className:y("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));Ra.displayName=Mt.displayName;function ze({content:t,className:s}){if(!t)return null;const o={table:({node:n,...r})=>e.jsx("div",{className:"overflow-x-auto my-4",children:e.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...r})}),thead:({node:n,...r})=>e.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:n,...r})=>e.jsx("tbody",{...r}),tr:({node:n,...r})=>e.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:n,...r})=>e.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...r}),td:({node:n,...r})=>e.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:n,checked:r,...i})=>i.type==="checkbox"?e.jsx("input",{type:"checkbox",checked:r||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...i}):e.jsx("input",{...i}),code:({node:n,...r})=>r.className?.includes("language-")?e.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-code text-foreground",...r}):e.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code text-foreground",...r}),pre:({node:n,...r})=>e.jsx("pre",{className:"my-4",...r}),h1:({node:n,...r})=>e.jsx("h1",{className:"text-heading-3 mt-6 mb-4 text-foreground",...r}),h2:({node:n,...r})=>e.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground",...r}),h3:({node:n,...r})=>e.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...r}),ul:({node:n,...r})=>{const i=n?.children?.some(a=>typeof a=="object"&&a!==null&&"type"in a&&a.type==="element"&&"tagName"in a&&a.tagName==="li"&&"children"in a&&Array.isArray(a.children)&&a.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"),...r})},ol:({node:n,...r})=>e.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...r}),li:({node:n,...r})=>{const i=n?.children?.some(a=>typeof a=="object"&&a!==null&&"type"in a&&a.type==="element"&&"tagName"in a&&a.tagName==="input"&&"properties"in a&&typeof a.properties=="object"&&a.properties!==null&&"type"in a.properties&&a.properties.type==="checkbox");return e.jsx("li",{className:y("flex items-start",i?"gap-2":"ml-2"),...r})},a:({node:n,...r})=>e.jsx("a",{className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:n,...r})=>e.jsx("p",{className:"my-2 text-foreground leading-relaxed",...r}),blockquote:({node:n,...r})=>e.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2",...r})};return e.jsx("div",{className:y("markdown-content prose prose-sm max-w-none dark:prose-invert",s),children:e.jsx(Ks,{remarkPlugins:[Bn],components:o,children:t})})}const _a=de("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"}}),Ds=l.forwardRef(({message:t,role:s,layout:o,className:n,children:r,messageId:i,autoScroll:a,isLastMessage:u=!1,...p},d)=>{const c=t?t.role:s||"assistant",h=t?t.id:i,f=l.useRef(null),[b,v]=l.useState(void 0);return l.useImperativeHandle(d,()=>f.current),l.useEffect(()=>{if(!u||c!=="assistant"){v(void 0);return}const m=()=>{const g=f.current;if(!g)return;let w=g.parentElement;for(;w&&!w.classList.contains("overflow-y-auto");)w=w.parentElement;if(!w)return;const S=g.previousElementSibling;if(!S||S.getAttribute("aria-label")!=="user message"){v(void 0);return}const T=w.clientHeight,C=S.offsetHeight,M=Math.max(0,T-C-32);v(M)};m();const x=new ResizeObserver(m);if(f.current){x.observe(f.current);let g=f.current.parentElement;for(;g&&!g.classList.contains("overflow-y-auto");)g=g.parentElement;g&&x.observe(g)}return()=>x.disconnect()},[u,c]),l.useEffect(()=>{if((a!==void 0?a:c==="user")&&f.current){const x=setTimeout(()=>{f.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(x)}},[c,a]),e.jsx("article",{ref:f,"aria-label":`${c} message`,"data-message-id":h,className:y(_a({role:c,layout:o}),n),style:{minHeight:b!==void 0?`${b}px`:void 0},...p,children:r})});Ds.displayName="Message";function dt({toolCalls:t}){const s=t.map(r=>r.prettyName||r.title),o=[...new Set(s)],n=o.length<=2?o.join(", "):`${o.slice(0,2).join(", ")} +${o.length-2} more`;return e.jsxs("div",{className:"flex flex-col my-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-paragraph-sm text-muted-foreground/50",children:[e.jsx(Gt,{className:"h-3 w-3"}),e.jsx("span",{children:"Invoking parallel operation"}),e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-muted-foreground/50",children:t.length})]}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground/50 pl-4.5",children:n})]})}const ut=de("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"}}),Ma=de("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Us=l.forwardRef(({content:t,isStreaming:s=!1,mode:o="collapsible",defaultExpanded:n=!1,autoExpand:r=!1,autoCollapse:i=!0,autoCollapseDelay:a=2e3,label:u="Thinking",variant:p,className:d},c)=>{const[h,f]=l.useState(o==="inline"?!0:n),[b,v]=l.useState(!1);return l.useEffect(()=>{if(i&&!s&&t&&o==="collapsible"){const m=setTimeout(()=>{v(!0),f(!1)},a);return()=>clearTimeout(m)}},[s,t,i,a,o]),l.useEffect(()=>{r&&s&&o==="collapsible"&&!b&&f(!0)},[r,s,o,b]),!t&&!s?null:o==="inline"?e.jsxs("div",{ref:c,className:y(ut({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:()=>{f(!h),v(!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":h,"aria-label":`${h?"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"}),!h&&t&&e.jsxs("span",{className:"text-caption text-foreground opacity-50 truncate",children:[t.substring(0,60),t.length>60&&"..."]})]}),e.jsx(ie,{className:Ma({expanded:h}),"aria-hidden":"true"})]}),h&&e.jsx("div",{className:y(ut({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:"..."})]})})]})});Us.displayName="Reasoning";const Ce=l.memo(l.forwardRef(({content:t,isStreaming:s=!1,showEmpty:o=!0,emptyMessage:n="",className:r,...i},a)=>!t&&s&&o?e.jsx("div",{ref:a,className:y("opacity-70 italic text-paragraph-sm",r),...i,children:n}):t?e.jsx("div",{ref:a,...i,children:e.jsx(nn,{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",r),children:t})}):null),(t,s)=>t.content===s.content);Ce.displayName="Response";const Aa=50;function Pa({port:t,sessionId:s,host:o,parentStatus:n,agentName:r,query:i,isExpanded:a,onExpandChange:u,storedMessages:p,isReplay:d=!1}){const[c,h]=l.useState(!1),f=a??c,[b,v]=l.useState(!1),[m,x]=l.useState(!0),g=l.useRef(null),S=!d&&t!==void 0&&s!==void 0?{port:t,sessionId:s,...o!==void 0?{host:o}:{}}:null,{messages:T,isStreaming:C,error:N}=co(S),M=p&&p.length>0?p:T,A=d?!1:n==="in_progress"||n==="pending"||C,D=M[M.length-1],R=D&&(D.content||D.toolCalls&&D.toolCalls.length>0||D.contentBlocks&&D.contentBlocks.length>0),F=l.useRef(A);l.useEffect(()=>{F.current&&!A&&v(!1),F.current=A},[A]);const $=l.useCallback(()=>{const I=g.current;if(!I)return;const{scrollTop:z,scrollHeight:B,clientHeight:_}=I,E=B-z-_;x(E<Aa)},[]),k=l.useCallback(()=>{const I=g.current;I&&(I.scrollTop=I.scrollHeight)},[]);l.useEffect(()=>{m&&(A||R)&&k()},[D?.content,D?.toolCalls,m,A,R,k]),l.useEffect(()=>{const I=g.current;if(!I)return;const z=()=>$();return I.addEventListener("scroll",z,{passive:!0}),$(),()=>I.removeEventListener("scroll",z)},[$,b,f]);const H=D?.content&&D.content.split(`
8
- `).filter(Boolean).pop()||"",K=H.length>100?`${H.slice(0,100)}...`:H,Q=i?(i.split(`
9
- `)[0]??"").slice(0,100)+(i.length>100?"...":""):"";return e.jsxs("div",{children:[!f&&e.jsx("div",{className:"w-full max-w-md",children:K?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:K}):Q?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate",children:Q}):null}),f&&e.jsxs("div",{className:"space-y-3",children:[(r||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:[r&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"agentName: "}),e.jsx("span",{className:"text-foreground",children:r})]}),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:()=>v(!b),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:"Thinking"}),e.jsx(ie,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${b?"rotate-180":""}`})]}),b&&e.jsxs("div",{ref:g,className:"mt-2 rounded-md overflow-hidden bg-muted/30 border border-border/50 max-h-[200px] overflow-y-auto",children:[N&&e.jsxs("div",{className:"px-2 py-2 text-[11px] text-destructive",children:["Error: ",N]}),!N&&!R&&A&&e.jsx("div",{className:"px-2 py-2 text-[11px] text-muted-foreground",children:"Waiting for sub-agent response..."}),D&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[D.contentBlocks&&D.contentBlocks.length>0?D.contentBlocks.map((I,z)=>I.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(ze,{content:I.text})},`text-${z}`):e.jsx(Da,{toolCall:I.toolCall},I.toolCall.id)):D.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(ze,{content:D.content})}),D.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!A&&D?.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(ze,{content:D.content})})]})]})]})}function Da({toolCall:t}){const s={pending:"...",in_progress:"",completed:"",failed:""}[t.status],o={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:o,children:s}),e.jsx("span",{className:"font-medium",children:t.prettyName||t.title}),t.status==="in_progress"&&e.jsx(Qt,{className:"h-2.5 w-2.5 animate-spin"})]})}const Ua={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Ls=l.createContext(Ua);function La({children:t,defaultTheme:s="system",storageKey:o="vite-ui-theme"}){const[n,r]=l.useState(()=>localStorage.getItem(o)||s),[i,a]=l.useState("light");l.useEffect(()=>{const p=window.document.documentElement;if(p.classList.remove("light","dark"),n==="system"){const d=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";p.classList.add(d),a(d);return}p.classList.add(n),a(n)},[n]);const u={theme:n,setTheme:p=>{localStorage.setItem(o,p),r(p)},resolvedTheme:i};return e.jsx(Ls.Provider,{value:u,children:t})}const zs=()=>{const t=l.useContext(Ls);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t},pt={Globe:Ln,Image:Un,Link:Dn,Cloud:Pn,CheckSquare:Re,Search:An,FileText:Be,Edit:Mn,Wrench:_n,CircleDot:Kt};function Te({toolCall:t}){const[s,o]=l.useState(!1),[n,r]=l.useState(!1),{resolvedTheme:i}=zs(),a=t.title==="todo_write",u=!!(t.subagentPort&&t.subagentSessionId),p=!!(t.subagentMessages&&t.subagentMessages.length>0),d=u||p,c=p,h=Fe.useContext(Ge),f=Fe.useCallback(()=>{a&&h?h.panelSize!=="hidden"&&h.activeTab==="todo"?h.setPanelSize("hidden"):(h.setPanelSize("small"),h.setActiveTab("todo")):d?r(!n):o(!s)},[a,h,s,d,n]),b=t.icon&&pt[t.icon]?pt[t.icon]:Kt,v=t.prettyName||t.title,m=d&&(t.status==="in_progress"||t.status==="pending"),x=d&&t.status==="failed",g=d?x?"text-destructive":m?"text-foreground animate-pulse":"text-green-500":"text-muted-foreground",w=d?x?"Sub-agent failed":m?"Sub-agent running":"Sub-agent completed":void 0,S=t.status==="failed"||!!t.error,T=t.status==="pending"&&(!t.rawInput||Object.keys(t.rawInput).length===0),C={fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit","--w-rjv-color":i==="dark"?"#fafafa":"#09090b","--w-rjv-key-string":i==="dark"?"#fafafa":"#09090b","--w-rjv-background-color":"transparent","--w-rjv-line-color":i==="dark"?"#27272a":"#e4e4e7","--w-rjv-arrow-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-edit-color":i==="dark"?"#fafafa":"#09090b","--w-rjv-info-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-update-color":i==="dark"?"#fafafa":"#09090b","--w-rjv-copied-color":i==="dark"?"#fafafa":"#09090b","--w-rjv-copied-success-color":i==="dark"?"#22c55e":"#16a34a","--w-rjv-curlybraces-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-colon-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-brackets-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-string-color":i==="dark"?"#a1a1aa":"#71717a","--w-rjv-type-string-color":i==="dark"?"#22c55e":"#16a34a","--w-rjv-type-int-color":i==="dark"?"#f59e0b":"#d97706","--w-rjv-type-float-color":i==="dark"?"#f59e0b":"#d97706","--w-rjv-type-bigint-color":i==="dark"?"#f59e0b":"#d97706","--w-rjv-type-boolean-color":i==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-date-color":i==="dark"?"#ec4899":"#db2777","--w-rjv-type-url-color":i==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-null-color":i==="dark"?"#ef4444":"#dc2626","--w-rjv-type-nan-color":i==="dark"?"#ef4444":"#dc2626","--w-rjv-type-undefined-color":i==="dark"?"#ef4444":"#dc2626"};return T?e.jsx("div",{className:"flex flex-col my-4",children:e.jsxs("span",{className:"text-paragraph-sm text-muted-foreground/50",children:["Invoking ",v]})}):e.jsxs("div",{className:"flex flex-col my-4",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:f,"aria-expanded":a?void 0:s,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("div",{className:g,title:w,children:e.jsx(b,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:v}),S&&e.jsx(zn,{className:"h-3 w-3 text-destructive"}),a?e.jsx(he,{className:"h-3 w-3 text-muted-foreground/70"}):e.jsx(ie,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${s?"rotate-180":""}`})]}),t.subline&&e.jsx("span",{className:"text-paragraph-sm text-muted-foreground/70 pl-4.5",children:t.subline})]}),!a&&d&&e.jsx("div",{className:"pl-4.5",children:e.jsx(Pa,{port:t.subagentPort,sessionId:t.subagentSessionId,parentStatus:t.status,agentName:t.rawInput?.agentName,query:t.rawInput?.query,isExpanded:n,onExpandChange:r,storedMessages:t.subagentMessages,isReplay:c})}),!a&&!d&&s&&e.jsxs("div",{className:"mt-2 text-sm border border-border rounded-lg bg-card overflow-hidden w-full",children:[t.rawInput&&Object.keys(t.rawInput).length>0&&!t.subagentPort&&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:"Input"}),e.jsx("div",{className:"text-[11px] font-mono text-foreground",children:e.jsx(nt,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:C})})]}),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-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Files"}),e.jsx("ul",{className:"space-y-1",children:t.locations.map(N=>e.jsxs("li",{className:"font-mono text-[11px] text-foreground bg-muted px-1.5 py-0.5 rounded w-fit",children:[N.path,N.line!==null&&N.line!==void 0&&`:${N.line}`]},`${N.path}:${N.line??""}`))})]}),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-muted-foreground 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((N,M)=>{const A=()=>N.type==="diff"&&"path"in N?`diff-${N.path}-${M}`:N.type==="terminal"&&"terminalId"in N?`terminal-${N.terminalId}`:N.type==="text"&&"text"in N?`text-${N.text.substring(0,20)}-${M}`:N.type==="content"&&"content"in N?`content-${N.content.text?.substring(0,20)}-${M}`:`block-${M}`,D=(R,F)=>{try{const $=JSON.parse(R);if(typeof $=="object"&&$!==null)return e.jsx("div",{className:"text-[11px]",children:e.jsx(nt,{value:$,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:C})},F)}catch{}return e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-foreground overflow-x-auto",children:R},F)};if(N.type==="content"&&"content"in N){const R=N.content;if(R.type==="text"&&R.text)return D(R.text,A())}if(N.type==="text"&&"text"in N)return D(N.text,A());if(N.type==="image"){const R=N.alt||"Generated image";let F;if("data"in N)F=`data:${N.mimeType||"image/png"};base64,${N.data}`;else if("url"in N)F=N.url;else return null;return e.jsx("div",{className:"my-2",children:e.jsx("img",{src:F,alt:R,className:"max-w-full h-auto rounded-md border border-border"})},A())}return N.type==="diff"&&"path"in N&&"oldText"in N&&"newText"in N?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-muted-foreground border-b border-border",children:[N.path,"line"in N&&N.line!==null&&N.line!==void 0&&`:${N.line}`]}),e.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"text-red-500 dark:text-red-400",children:["- ",N.oldText]}),e.jsxs("div",{className:"text-green-500 dark:text-green-400",children:["+ ",N.newText]})]})]},A()):N.type==="terminal"&&"terminalId"in N?e.jsxs("div",{className:"bg-neutral-900 text-neutral-100 p-2 rounded text-[11px] font-mono",children:["Terminal: ",N.terminalId]},A()):null}),t.error&&e.jsxs("div",{className:"text-destructive font-mono text-[11px] mt-2",children:["Error: ",t.error]})]})]}):null,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})]}),(t.tokenUsage||t.startedAt)&&e.jsxs("div",{className:"p-2 bg-muted/50 border-t border-border flex flex-wrap gap-4 text-[10px] text-muted-foreground 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)"]})]})]})]})]})}function mt({toolCalls:t}){const[s,o]=l.useState(!1);(()=>{const u=t.map(p=>p.status);return u.some(p=>p==="failed")?"failed":u.some(p=>p==="in_progress")?"in_progress":u.every(p=>p==="completed")?"completed":"pending"})();const r=t.map(u=>u.prettyName||u.title),i=[...new Set(r)],a=i.length<=2?i.join(", "):`${i.slice(0,2).join(", ")} +${i.length-2} more`;return e.jsxs("div",{className:"flex flex-col my-4",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:()=>o(!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:"text-muted-foreground",children:e.jsx(Gt,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:"Parallel operation"}),e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-muted-foreground/70",children:t.length}),e.jsx(ie,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${s?"rotate-180":""}`})]}),!s&&e.jsx("span",{className:"text-paragraph-sm text-muted-foreground/70 pl-4.5",children:a})]}),s&&e.jsx("div",{className:"mt-1",children:t.map(u=>e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"w-2.5 h-4 border-l-2 border-b-2 border-border rounded-bl-[6px] mt-1 mr-0.5 shrink-0"}),e.jsx("div",{className:"flex-1 -mt-2",children:e.jsx(Te,{toolCall:u})})]},u.id))})]})}const za=de("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"}}),Fs=l.forwardRef(({role:t,variant:s,isStreaming:o,message:n,thinkingDisplayStyle:r="collapsible",className:i,children:a,...u},p)=>{const d=P(v=>v.streamingStartTime);P(v=>v.currentModel);const c=n&&!a,h=c?n.role:t||"assistant",f=c?n.isStreaming:o;let b=a;if(c){const v=n.metadata?.thinking,m=!!v,x=n.isStreaming&&!n.content&&n.role==="assistant";b=e.jsxs(e.Fragment,{children:[n.role==="assistant"&&m&&e.jsx(Us,{content:v,isStreaming:n.isStreaming,mode:r,autoCollapse:!0}),x&&d&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"size-2.5 rounded-full bg-foreground animate-pulse-scale"})}),n.role==="assistant"?(()=>{const g=(n.toolCalls||[]).slice().sort((k,H)=>(k.contentPosition??1/0)-(H.contentPosition??1/0)),w=k=>k.status==="pending"&&(!k.rawInput||Object.keys(k.rawInput).length===0),S=k=>{const H=[],K=new Map;let Q=[],I=[],z=null;const B=()=>{Q.length>1?H.push({type:"invoking",toolCalls:Q}):Q.length===1&&H.push(Q[0]),Q=[]},_=()=>{I.length>1?H.push({type:"batch",toolCalls:I}):I.length===1&&H.push(I[0]),I=[],z=null};for(const E of k)if(E.batchId){B(),_();const V=K.get(E.batchId);if(V)V.push(E);else{const le=[E];K.set(E.batchId,le),H.push({type:"batch",toolCalls:le})}}else w(E)?(_(),Q.push(E)):(B(),z===E.title?I.push(E):(_(),I=[E],z=E.title));return B(),_(),H},T=(k,H)=>typeof k=="object"&&"type"in k&&k.type==="batch"?e.jsx(mt,{toolCalls:k.toolCalls},`batch-${k.toolCalls[0]?.batchId||H}`):typeof k=="object"&&"type"in k&&k.type==="invoking"?e.jsx(dt,{toolCalls:k.toolCalls},`invoking-${k.toolCalls[0]?.id||H}`):e.jsx(Te,{toolCall:k},k.id);if(g.length===0||!g.some(k=>k.contentPosition!==void 0)){const k=S(g);return e.jsxs(e.Fragment,{children:[k.length>0&&e.jsx("div",{className:"flex flex-col gap-2 mb-1",children:k.map((H,K)=>T(H,K))}),e.jsx(Ce,{content:n.content,isStreaming:n.isStreaming,showEmpty:!1})]})}const C=[];let N=0,M=[],A,D;const R=()=>{M.length>1?C.push(e.jsx(mt,{toolCalls:M},`group-${A||D}-${M[0].id}`)):M.length===1&&C.push(e.jsx("div",{children:e.jsx(Te,{toolCall:M[0]})},`tool-${M[0].id}`)),M=[],A=void 0,D=void 0},F=g.filter(w),$=g.filter(k=>!w(k));if($.forEach((k,H)=>{const K=k.contentPosition??n.content.length;if(K>N){R();const Q=n.content.slice(N,K);Q&&C.push(e.jsx(Ce,{content:Q,isStreaming:!1,showEmpty:!1},`text-before-${k.id}`))}k.batchId?A===k.batchId?M.push(k):(R(),A=k.batchId,D=k.title,M=[k]):D===k.title&&!A?M.push(k):(R(),D=k.title,M=[k]),N=K,H===$.length-1&&R()}),N<n.content.length){const k=n.content.slice(N);k&&C.push(e.jsx(Ce,{content:k,isStreaming:n.isStreaming,showEmpty:!1},"text-end"))}return F.length>0&&(F.length>1?C.push(e.jsx(dt,{toolCalls:F},`invoking-group-${F[0].id}`)):C.push(e.jsx("div",{children:e.jsx(Te,{toolCall:F[0]})},`tool-${F[0].id}`))),e.jsx(e.Fragment,{children:C})})():e.jsxs("div",{className:"flex flex-col gap-2",children:[n.images&&n.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:n.images.map((g,w)=>e.jsx("img",{src:`data:${g.mimeType};base64,${g.data}`,alt:`Attachment ${w+1}`,className:"max-w-[200px] max-h-[200px] rounded-lg object-cover"},w))}),n.content&&e.jsx("div",{className:"whitespace-pre-wrap",children:n.content})]})]})}return e.jsx("div",{ref:p,className:y(za({role:h,variant:s}),f&&"animate-pulse-subtle",i),...u,children:b})});Fs.displayName="MessageContent";const tt=l.forwardRef(({showIcons:t=!0,visibleTabs:s=["todo","files"],variant:o="default",className:n,...r},i)=>{const u=[{id:"todo",label:"To-do",icon:Re},{id:"files",label:"Files",icon:Be},{id:"database",label:"Database",icon:Bt},{id:"sources",label:"Sources",icon:Ht},{id:"settings",label:"Settings",icon:Vt}].filter(d=>s.includes(d.id)),p=o==="compact"?"gap-[4px]":"gap-3";return e.jsx(xe,{ref:i,className:y("w-full justify-start bg-transparent p-0 h-auto",p,n),...r,children:u.map(d=>{const c=d.icon;return e.jsxs(be,{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)})})});tt.displayName="PanelTabsHeader";const Fa=l.forwardRef(({className:t,children:s,...o},n)=>e.jsxs(At,{ref:n,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),...o,children:[s,e.jsx(gn,{asChild:!0,children:e.jsx(Fn,{className:"h-4 w-4 opacity-50"})})]}));Fa.displayName=At.displayName;const Os=l.forwardRef(({className:t,...s},o)=>e.jsx(Pt,{ref:o,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(qt,{className:"h-4 w-4"})}));Os.displayName=Pt.displayName;const $s=l.forwardRef(({className:t,...s},o)=>e.jsx(Dt,{ref:o,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ie,{className:"h-4 w-4"})}));$s.displayName=Dt.displayName;const Oa=l.forwardRef(({className:t,children:s,position:o="popper",...n},r)=>e.jsx(hn,{children:e.jsxs(Ut,{ref:r,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",o==="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:o,...n,children:[e.jsx(Os,{}),e.jsx(xn,{className:y("p-1",o==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx($s,{})]})}));Oa.displayName=Ut.displayName;const $a=l.forwardRef(({className:t,...s},o)=>e.jsx(Lt,{ref:o,className:y("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));$a.displayName=Lt.displayName;const Ba=l.forwardRef(({className:t,children:s,...o},n)=>e.jsxs(zt,{ref:n,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),...o,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(bn,{children:e.jsx(Ot,{className:"h-4 w-4"})})}),e.jsx(yn,{children:s})]}));Ba.displayName=zt.displayName;const Ha=l.forwardRef(({className:t,...s},o)=>e.jsx(Ft,{ref:o,className:y("-mx-1 my-1 h-px bg-muted",t),...s}));Ha.displayName=Ft.displayName;const Bs=l.forwardRef(({task:t,collapsible:s=!0,defaultExpanded:o=!1,onTaskClick:n,className:r,...i},a)=>{const[u,p]=l.useState(o),d=!!(t.details||t.files&&t.files.length>0),c={pending:$e,in_progress:Qt,completed:$t}[t.status],h=()=>{switch(t.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},f=()=>{d&&s&&p(!u),n?.(t)};return e.jsxs("div",{ref:a,className:y("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",r),...i,children:[e.jsxs("button",{type:"button",onClick:f,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",h(),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(ie,{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(b=>e.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:b},b))})]})]})]})});Bs.displayName="Subagent";const Wa=l.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:o,emptyMessage:n="No subagents yet.",className:r,...i},a)=>e.jsx("div",{ref:a,className:y("space-y-2 max-h-96 overflow-y-auto",r),...i,children:t.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:n}):t.map(u=>e.jsx(Bs,{task:u,collapsible:s,...o?{onTaskClick:o}:{}},u.id))}));Wa.displayName="SubagentList";const Va=de("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"}}),qa=l.forwardRef(({className:t,autoResize:s=!1,maxHeight:o=200,variant:n,...r},i)=>{const a=l.useRef(null),u=l.useCallback(d=>{a.current=d,typeof i=="function"?i(d):i&&(i.current=d)},[i]),p=l.useCallback(()=>{const d=a.current;if(!d||!s)return;d.style.height="auto";const c=Math.min(d.scrollHeight,o);d.style.height=`${c}px`,d.scrollHeight>o?d.style.overflowY="auto":d.style.overflowY="hidden"},[s,o]);return l.useEffect(()=>{p()},[p]),e.jsx("textarea",{className:y(Va({variant:n}),s&&"overflow-y-hidden",t),ref:u,...r})});qa.displayName="Textarea";function Hs(){const{setTheme:t}=zs();return e.jsxs(Qe,{children:[e.jsx(Ke,{asChild:!0,children:e.jsxs(ye,{children:[e.jsx(On,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx($n,{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(Ae,{align:"end",children:[e.jsx(ne,{onClick:()=>t("light"),children:"Light"}),e.jsx(ne,{onClick:()=>t("dark"),children:"Dark"}),e.jsx(ne,{onClick:()=>t("system"),children:"System"})]})]})}function Ga(){return"http://localhost:3100"}const ft={agentServerUrl:Ga(),debuggerUrl:void 0};function Qa(){const{client:t,error:s,sessionId:o}=eo({serverUrl:ft.agentServerUrl});return e.jsx(La,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(ja,{client:t,initialSessionId:o,error:s,...ft.debuggerUrl})})}const Ws=document.getElementById("root");if(!Ws)throw new Error("Root element not found");Js.createRoot(Ws).render(e.jsx(Fe.StrictMode,{children:e.jsx(Qa,{})}));