@townco/gui-template 0.1.80 → 0.1.90

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