@townco/gui-template 0.1.101 → 0.1.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ import{r as i,j as e,M as da,c as Pt,h as ua}from"./react-CGZSjzY5.js";import{bb as Ee,bc as ma,bd as Qt,be as ae,bf as O,bg as w,bh as X,bi as F,bj as te,bk as ie,bl as et,bm as dt,bn as Z,bo as Me,bp as zt,bq as pa,br as fa,bs as ga,bt as ha,bu as we,bv as xa,bw as Se,am as ba,bx as ya,by as Jt}from"./vendor-GH-z_tpa.js";import{P as Xt,a as va}from"./acp-sdk-IVvHEM45.js";import{S as de,C as ys,P as wa,R as ja,T as Na,a as vs,b as ws,c as Sa,d as js,I as Ns,e as Ss,f as Cs,g as ks,L as Ts,h as Is,i as Ca,j as ka,k as Rs,l as _s,m as Ms,n as Ta,O as ft,o as Es,p as gt,q as As,r as ht,D as xt,s as Ps,t as Ds,u as Ia,v as Us,w as zs,x as Ra,y as $s,V as _a,z as Ls,A as Os,B as Ma,E as Ea,F as Fs}from"./radix-t7U-2WdS.js";import{c as qe,d as bt,e as yt,P as Aa,E as Pa,S as Bs,f as Hs,g as Da,h as $t,i as Ua,j as za,k as $a,l as La,m as le,A as Oa,n as vt,F as Fa,o as Ba,p as Ha,q as Wa,r as $e,s as wt,t as jt,G as Ws,u as Vs,v as qs,B as Zt,w as Va,x as qa,y as Ka,z as Ks,H as Ya,I as Lt,J as ut,T as Ga,K as re,N as Qa,O as Ja,Q as es,U as Xa,V as ts,W as Je,Y as Ot,_ as Za,$ as eo,a0 as to,a1 as so,a2 as no,a3 as ao,a4 as oo,a5 as ro,a6 as io,a7 as lo,a8 as co}from"./icons-CbKb46yG.js";import{A as Xe,m as ye}from"./framer-motion-hxab2SQe.js";import{g as Ys}from"./markdown-CFaOl7ku.js";import"./katex-D_C5EOCM.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 l of o)if(l.type==="childList")for(const r of l.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function a(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function n(o){if(o.ep)return;o.ep=!0;const l=a(o);fetch(o.href,l)}})();var uo={};const it=typeof process<"u"&&process.versions?.node;let mo,po=0;const Dt=new Set;function fo(t){return Dt.add(t),()=>Dt.delete(t)}function go(t){for(const s of Dt)s(t)}const ss={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},ho={trace:Ee.TRACE,debug:Ee.DEBUG,info:Ee.INFO,warn:Ee.WARN,error:Ee.ERROR,fatal:Ee.FATAL};class xo{service;minLevel;logsDir;enableConsoleOutput;constructor(s,a="debug"){this.service=s,this.minLevel=a,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&uo?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){this.logsDir}shouldLog(s){return ss[s]>=ss[this.minLevel]}log(s,a,n){if(!this.shouldLog(s))return;const o={id:`log_${++po}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:a,...n&&{metadata:n}};if(go(o),it&&this.logsDir,it&&this.logsDir){const c={timestamp:o.timestamp,level:o.level,service:o.service,message:o.message,...o.metadata&&{metadata:o.metadata}};this.writeToFile(JSON.stringify(c)).catch(()=>{})}if(it&&this.enableConsoleOutput){const c=o.timestamp,m=o.level.toUpperCase().padEnd(5),u=`[${this.service}]`,d=o.metadata?` ${JSON.stringify(o.metadata)}`:"";console.log(`${c} ${m} ${u} ${o.message}${d}`)}const l=ma.getLogger(this.service),r=Qt.trace.getSpan(Qt.context.active());l.emit({severityNumber:ho[s],severityText:s.toUpperCase(),body:a,attributes:{service:this.service,...n&&Object.fromEntries(Object.entries(n).map(([c,m])=>[`log.${c}`,typeof m=="object"?JSON.stringify(m):m])),...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 ue(t,s="debug"){return new xo(t,s)}const Gs=ae(["user","assistant","system","tool"]),bo=ae(["text","image","file","tool_call","tool_result"]),tt=O({type:bo}),yo=tt.extend({type:X("text"),text:w()}),vo=tt.extend({type:X("image"),url:w().url().optional(),source:O({type:X("base64"),media_type:ae(["image/jpeg","image/png","image/gif","image/webp"]),data:w()}).optional()}),wo=tt.extend({type:X("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:F().optional()}),jo=tt.extend({type:X("tool_call"),id:w(),name:w(),arguments:te(w(),ie())}),No=tt.extend({type:X("tool_result"),callId:w(),result:ie(),error:w().optional()}),Qs=et("type",[yo,vo,wo,jo,No]),Js=O({id:w(),role:Gs,content:Z(Qs),timestamp:dt(),metadata:te(w(),ie()).optional()}),So=O({type:X("content"),id:w(),role:Gs,contentDelta:Qs,isComplete:Me(),tokenUsage:O({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}).optional(),contextInputTokens:F().optional(),_meta:O({context_size:O({systemPromptTokens:F(),userMessagesTokens:F(),assistantMessagesTokens:F(),toolInputTokens:F(),toolResultsTokens:F(),totalEstimated:F(),llmReportedInputTokens:F().optional()}).optional()}).optional()}),Co=O({type:X("tool_call"),id:w(),toolCall:zt(),messageId:w().optional()}),ko=O({type:X("tool_call_update"),id:w(),toolCallUpdate:zt(),messageId:w().optional()}),Nt=ae(["context_size","tool_response"]),To=O({type:X("hook_triggered"),hookType:Nt,threshold:F(),currentPercentage:F(),callback:w(),triggeredAt:F().optional(),toolCallId:w().optional()}),Io=O({type:X("hook_completed"),hookType:Nt,callback:w(),metadata:O({action:w().optional(),messagesRemoved:F().optional(),tokensSaved:F().optional()}).passthrough().optional(),completedAt:F().optional(),toolCallId:w().optional()}),Ro=O({type:X("hook_error"),hookType:Nt,callback:w(),error:w(),completedAt:F().optional(),toolCallId:w().optional()}),_o=et("type",[To,Io,Ro]),Mo=O({type:X("hook_notification"),id:w(),notification:_o,messageId:w().optional()}),Eo=O({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),Ao=O({type:X("sources"),sources:Z(Eo)});et("type",[So,Co,ko,Mo,Ao]);const Po=O({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),Ft=ae(["pending","in_progress","completed","failed"]),Do=ae(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),Xs=O({path:w(),line:F().nullable().optional()}),Bt=O({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}),Ht=et("type",[O({type:X("content"),content:O({type:X("text"),text:w()})}),O({type:X("text"),text:w()}),O({type:X("image"),data:w(),mimeType:w().optional(),alt:w().optional()}),O({type:X("image"),url:w(),alt:w().optional()}),O({type:X("diff"),path:w(),oldText:w(),newText:w(),line:F().nullable().optional()}),O({type:X("terminal"),terminalId:w()})]),Zs=O({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),status:Ft,content:Z(Ht).optional()}),Uo=et("type",[O({type:X("text"),text:w()}),O({type:X("tool_call"),toolCall:Zs})]),en=O({id:w(),content:w(),toolCalls:Z(Zs).optional(),contentBlocks:Z(Uo).optional(),isStreaming:Me().optional()}),tn=O({id:w(),batchId:w().optional(),title:w(),prettyName:w().optional(),icon:w().optional(),verbiage:O({active:w(),past:w(),paramKey:w().optional()}).optional(),subline:w().optional(),kind:Do,status:Ft,contentPosition:F().optional(),locations:Z(Xs).optional(),rawInput:te(w(),ie()).optional(),rawOutput:te(w(),ie()).optional(),content:Z(Ht).optional(),error:w().optional(),startedAt:F().optional(),completedAt:F().optional(),tokenUsage:Bt.optional(),_meta:O({truncationWarning:w().optional(),compactionAction:ae(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:Z(en).optional(),subagentStreaming:Me().optional()}),zo=O({id:w(),status:Ft.optional(),title:w().optional(),prettyName:w().optional(),icon:w().optional(),batchId:w().optional(),rawInput:te(w(),ie()).optional(),locations:Z(Xs).optional(),rawOutput:te(w(),ie()).optional(),content:Z(Ht).optional(),error:w().optional(),completedAt:F().optional(),tokenUsage:Bt.optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:Z(en).optional(),_meta:O({truncationWarning:w().optional(),compactionAction:ae(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional()});function ns(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 $o=O({mimeType:w(),data:w()}),Lo=O({id:w(),hookType:Nt,callback:w(),status:ae(["triggered","completed","error"]),threshold:F().optional(),currentPercentage:F().optional(),metadata:O({action:w().optional(),messagesRemoved:F().optional(),tokensSaved:F().optional(),tokensBeforeCompaction:F().optional(),summaryTokens:F().optional(),originalTokens:F().optional(),finalTokens:F().optional(),truncationWarning:w().optional()}).passthrough().optional(),error:w().optional(),triggeredAt:F().optional(),completedAt:F().optional(),contentPosition:F().optional(),toolCallId:w().optional()}),Oo=O({id:w(),role:ae(["user","assistant","system"]),content:w(),timestamp:dt(),isStreaming:Me().default(!1),streamingStartTime:F().optional(),metadata:te(w(),ie()).optional(),toolCalls:Z(tn).optional(),hookNotifications:Z(Lo).optional(),tokenUsage:Bt.optional(),images:Z($o).optional(),sources:Z(Po).optional()}),Fo=O({value:w(),isSubmitting:Me(),attachedFiles:Z(O({name:w(),path:w(),size:F(),mimeType:w(),data:w()})),selectedPromptParameters:te(w(),w()).optional()});O({sessionId:w().nullable(),isConnected:Me(),isStreaming:Me(),messages:Z(Oo),input:Fo,error:w().nullable()});ae(["disconnected","connecting","connected","error"]);let as=0,os=0;function me(t){const s=Date.now();s!==os&&(as=0,os=s);const a=as++,n=Math.random().toString(36).substring(2,7);return`msg_${s}_${a}_${n}_${t}`}const Bo=O({baseUrl:w().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:w().optional(),timeout:F().optional(),headers:te(w(),w()).optional()}),L=ue("http-transport");class Ho{connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;fileSystemChangeCallbacks=new Map;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=Bo.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:Xt,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},a=await this.sendRpcRequest("initialize",s);if(a.agentInfo){const l=a._meta,r=l&&typeof l=="object",c=r&&"agentDescription"in l?String(l.agentDescription):void 0,m=r&&"suggestedPrompts"in l&&Array.isArray(l.suggestedPrompts)?l.suggestedPrompts:void 0,u=r&&"tools"in l&&Array.isArray(l.tools)?l.tools:void 0,d=r&&"mcps"in l&&Array.isArray(l.mcps)?l.mcps:void 0,p=r&&"subagents"in l&&Array.isArray(l.subagents)?l.subagents:void 0,g=r&&"initialMessage"in l&&l.initialMessage&&typeof l.initialMessage=="object"?l.initialMessage:void 0,h=r&&"uiConfig"in l&&l.uiConfig&&typeof l.uiConfig=="object"?l.uiConfig:void 0,x=r&&"promptParameters"in l&&Array.isArray(l.promptParameters)?l.promptParameters:void 0;this.agentInfo={name:a.agentInfo.name,...a.agentInfo.title?{displayName:a.agentInfo.title}:{},version:a.agentInfo.version,...c?{description:c}:{},...m?{suggestedPrompts:m}:{},...g?{initialMessage:g}:{},...h?{uiConfig:h}:{},...u?{tools:u}:{},...d?{mcps:d}:{},...p?{subagents:p}:{},...x?{promptParameters:x}:{}}}L.info("ACP connection initialized",{initResponse:a});const n={cwd:"/",mcpServers:[]},o=await this.sendRpcRequest("session/new",n);this.currentSessionId=o.sessionId,L.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&&(L.warn("Transport already connected, disconnecting first",{sessionId:s}),await this.disconnect());try{this.abortController=new AbortController;const a={protocolVersion:Xt,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};L.info("Loading session - initializing connection",{sessionId:s});const n=await this.sendRpcRequest("initialize",a);if(n.agentInfo){const r=n._meta,c=r&&typeof r=="object",m=c&&"agentDescription"in r?String(r.agentDescription):void 0,u=c&&"suggestedPrompts"in r&&Array.isArray(r.suggestedPrompts)?r.suggestedPrompts:void 0,d=c&&"tools"in r&&Array.isArray(r.tools)?r.tools:void 0,p=c&&"mcps"in r&&Array.isArray(r.mcps)?r.mcps:void 0,g=c&&"subagents"in r&&Array.isArray(r.subagents)?r.subagents:void 0,h=c&&"initialMessage"in r&&r.initialMessage&&typeof r.initialMessage=="object"?r.initialMessage:void 0,x=c&&"uiConfig"in r&&r.uiConfig&&typeof r.uiConfig=="object"?r.uiConfig:void 0,f=c&&"promptParameters"in r&&Array.isArray(r.promptParameters)?r.promptParameters:void 0;this.agentInfo={name:n.agentInfo.name,...n.agentInfo.title?{displayName:n.agentInfo.title}:{},version:n.agentInfo.version,...m?{description:m}:{},...u?{suggestedPrompts:u}:{},...h?{initialMessage:h}:{},...x?{uiConfig:x}:{},...d?{tools:d}:{},...p?{mcps:p}:{},...g?{subagents:g}:{},...f?{promptParameters:f}:{}}}if(!n.agentCapabilities?.loadSession)throw L.error("Agent does not support loading sessions",{capabilities:n.agentCapabilities}),new Error("Agent does not support loading sessions");L.info("ACP connection initialized, loading session",{sessionId:s,capabilities:n.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=s,await this.connectSSE();const o={sessionId:s,cwd:"/",mcpServers:[]};L.info("Sending session/load request",{loadRequest:o});const l=await this.sendRpcRequest("session/load",o);L.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:l}),this.connected=!0,this.reconnectAttempts=0}catch(a){this.connected=!1;const n=a instanceof Error?a:new Error(String(a));throw L.error("Failed to load session",{sessionId:s,error:n.message,stack:n.stack}),this.notifyError(n),n}}async listSessions(){try{const s={method:"GET"};this.options.headers&&(s.headers=this.options.headers);const 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 L.error("Failed to list sessions",{error:s}),[]}}async disconnect(){if(this.connected)try{this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.connected=!1,this.currentSessionId=null,this.messageQueue=[],this.chunkResolvers=[],this.streamComplete=!1,this.reconnecting=!1,this.reconnectAttempts=0}catch(s){const a=s instanceof Error?s:new Error(String(s));throw this.notifyError(a),a}}async send(s,a){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");this.isInReplayMode&&(L.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const n=s.content.map(c=>c.type==="text"?{type:"text",text:c.text}:c.type==="image"?"source"in c&&c.source?{type:"image",data:c.source.data,mimeType:c.source.media_type}:"data"in c&&"mimeType"in c?{type:"image",data:c.data,mimeType:c.mimeType}:c:c),o={sessionId:this.currentSessionId,prompt:n};a?.promptParameters&&(o._meta={promptParameters:a.promptParameters});const l=await this.sendRpcRequest("session/prompt",o);L.debug("Prompt sent",{promptResponse:l}),this.streamComplete=!0;const r=this.chunkResolvers.shift();r?r({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(n){this.streamComplete=!0;const o=n instanceof Error?n:new Error(String(n));throw this.notifyError(o),o}}async cancel(s){if(!this.connected){L.warn("Cannot cancel: transport not connected");return}const a=s||this.currentSessionId;if(!a){L.warn("Cannot cancel: no session ID");return}L.info("Cancelling session",{sessionId:a}),this.streamComplete=!0,this.messageQueue.length=0,await this.sendNotification("session/cancel",{sessionId:a});const n={type:"content",id:a,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0};for(;this.chunkResolvers.length>0;){const o=this.chunkResolvers.shift();o&&o(n)}}async editAndResend(s,a,n){if(!this.connected)throw new Error("Transport not connected");const o=s||this.currentSessionId;if(!o)throw new Error("No session ID available");this.isInReplayMode&&(L.info("Exiting replay mode - user edited a message"),this.isInReplayMode=!1),this.streamComplete=!1,this.messageQueue=[],L.info("Edit and resend",{sessionId:o,messageIndex:a});const l={"Content-Type":"application/json",...this.options.headers},r=this.options.timeout??600*1e3,c=new AbortController,m=setTimeout(()=>c.abort(),r);try{const u=await fetch(`${this.options.baseUrl}/sessions/${o}/edit-and-resend`,{method:"POST",headers:l,body:JSON.stringify({messageIndex:a,prompt:n}),signal:c.signal});if(clearTimeout(m),!u.ok){const p=await u.text();throw new Error(`HTTP ${u.status}: ${p}`)}this.streamComplete=!0;const d=this.chunkResolvers.shift();d?d({type:"content",id:o,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:o,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(u){throw clearTimeout(m),this.streamComplete=!0,u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${r}ms`):u}}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)}}onFileSystemChange(s,a){return L.debug("Registering file system change callback",{sessionId:s}),this.fileSystemChangeCallbacks.set(s,a),()=>{L.debug("Unregistering file system change callback",{sessionId:s}),this.fileSystemChangeCallbacks.delete(s)}}notifyFileSystemChange(s){const a=this.fileSystemChangeCallbacks.get(s.sessionId);L.debug("notifyFileSystemChange",{sessionId:s.sessionId,hasCallback:!!a,callbackCount:this.fileSystemChangeCallbacks.size}),a&&a(s)}getAgentInfo(){return this.agentInfo||{}}async sendNotification(s,a){const n={jsonrpc:"2.0",method:s,params:a};L.debug("Sending notification",{method:s,params:a});const o={"Content-Type":"application/json",...this.options.headers};try{const l=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:o,body:JSON.stringify(n)});if(!l.ok){const r=await l.text();L.error("Notification failed",{status:l.status,errorText:r})}}catch(l){L.error("Error sending notification",{error:l})}}async sendRpcRequest(s,a){const o={jsonrpc:"2.0",id:this.generateRequestId(),method:s,params:a};L.debug("Sending RPC request",{method:s,params:a,request:o});const l={"Content-Type":"application/json",...this.options.headers},r=this.options.timeout??600*1e3,c=new AbortController,m=setTimeout(()=>c.abort(),r);try{const u=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:l,body:JSON.stringify(o),signal:c.signal});if(clearTimeout(m),!u.ok){const p=await u.text();throw new Error(`HTTP ${u.status}: ${p}`)}const d=await u.json();if(d.error)throw new Error(`ACP error: ${d.error.message||JSON.stringify(d.error)}`);return d.result||d}catch(u){throw clearTimeout(m),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${r}ms`):u}}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");L.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const o=n.body.getReader(),l=new TextDecoder;let r="";(async()=>{try{for(;;){const{done:c,value:m}=await o.read();if(c){L.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}r+=l.decode(m,{stream:!0});const u=r.split(`
2
+ `);r=u.pop()||"";let d={event:"message",data:""};for(const p of u)p.startsWith("event:")?d.event=p.substring(6).trim():p.startsWith("data:")?d.data=p.substring(5).trim():p===""&&(d.event==="message"&&d.data&&this.handleSSEMessage(d.data),d={event:"message",data:""})}}catch(c){if(c instanceof Error&&c.name==="AbortError"){L.debug("SSE stream aborted");return}L.error("Error reading SSE stream",{error:c}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(n){throw L.error("SSE connection error",{error:n}),n}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const 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);L.debug("SSE reconnecting",{delay:s,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(a=>setTimeout(a,s));try{await this.connectSSE(),L.info("SSE reconnected successfully"),this.reconnecting=!1}catch(a){L.error("SSE reconnection failed",{error:a}),this.reconnecting=!1}}handleSSEMessage(s){try{const a=JSON.parse(s);L.debug("Received SSE message",{message:a});const n=va.safeParse(a);if(!n.success){L.error("Invalid ACP message from SSE",{issues:n.error.issues});return}const o=n.data;L.debug("Parsed ACP message",{method:"method"in o?o.method:"(no method)"}),"method"in o&&o.method==="session/update"&&(L.debug("Received session/update notification"),"params"in o&&o.params&&(L.debug("Calling handleSessionNotification",{params:o.params}),this.handleSessionNotification(o.params)))}catch(a){L.error("Error parsing SSE message",{error:a}),this.notifyError(a instanceof Error?a:new Error(String(a)))}}handleSessionNotification(s){if(this.streamComplete){L.debug("Skipping session notification - stream complete/cancelled");return}L.debug("handleSessionNotification called",{params:s});const n=s.update,o=this.currentSessionId||s.sessionId;if(L.debug("Update session type",{sessionUpdate:n?.sessionUpdate}),n?.sessionUpdate==="sandbox_files_changed"){const r=n;r._meta?.isReplay===!0||(L.debug("Sandbox files changed",{paths:r.paths,source:r._meta?.source}),this.notifyFileSystemChange({sessionId:o,...r.paths&&{paths:r.paths},...r._meta?.source&&{source:r._meta.source}}));return}if(n?.sessionUpdate==="tool_call"){L.debug("Tool call notification",{tokenUsage:n.tokenUsage});const r=n._meta&&typeof n._meta=="object"&&"messageId"in n._meta?String(n._meta.messageId):void 0,c=n._meta&&typeof n._meta=="object"&&"prettyName"in n._meta&&typeof n._meta.prettyName=="string"?n._meta.prettyName:void 0,m=n._meta&&typeof n._meta=="object"&&"icon"in n._meta&&typeof n._meta.icon=="string"?n._meta.icon:void 0,u=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,p=n._meta&&typeof n._meta=="object"&&"subagentPort"in n._meta&&typeof n._meta.subagentPort=="number"?n._meta.subagentPort:void 0,g=n._meta&&typeof n._meta=="object"&&"subagentSessionId"in n._meta&&typeof n._meta.subagentSessionId=="string"?n._meta.subagentSessionId:void 0,h=n._meta&&typeof n._meta=="object"&&"subagentMessages"in n._meta&&Array.isArray(n._meta.subagentMessages)?n._meta.subagentMessages:void 0,x=n._meta&&typeof n._meta=="object"&&"compactionAction"in n._meta&&typeof n._meta.compactionAction=="string"?n._meta.compactionAction:void 0,f=n._meta&&typeof n._meta=="object"&&"originalTokens"in n._meta&&typeof n._meta.originalTokens=="number"?n._meta.originalTokens:void 0,y=n._meta&&typeof n._meta=="object"&&"finalTokens"in n._meta&&typeof n._meta.finalTokens=="number"?n._meta.finalTokens:void 0,j=n._meta&&typeof n._meta=="object"&&"originalContentPreview"in n._meta&&typeof n._meta.originalContentPreview=="string"?n._meta.originalContentPreview:void 0,v=n._meta&&typeof n._meta=="object"&&"originalContentPath"in n._meta&&typeof n._meta.originalContentPath=="string"?n._meta.originalContentPath:void 0,k={id:n.toolCallId??"",batchId:d,title:n.title??"",prettyName:c,icon:m,subline:u,kind:n.kind||"other",status:n.status||"pending",locations:n.locations,rawInput:n.rawInput,tokenUsage:n.tokenUsage,content:n.content?.map(z=>{if(typeof z!="object"||z===null)return{type:"text",text:""};const C=z;if(C.type==="content"&&typeof C.content=="object"&&C.content!==null){const A=C.content;if(A.type==="text")return{type:"content",content:{type:"text",text:typeof A.text=="string"?A.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:p,subagentSessionId:g,subagentMessages:h,_meta:x||f||y||j||v?{compactionAction:x,originalTokens:f,finalTokens:y,originalContentPreview:j,originalContentPath:v}:void 0},U={type:"tool_call",sessionId:o,status:"active",toolCall:k,messageId:r},E=n._meta&&typeof n._meta=="object"&&"isReplay"in n._meta&&n._meta.isReplay===!0;if(L.info("Creating tool_call session update",{toolCallId:k.id,title:k.title,hasSubagentPort:!!p,hasSubagentSessionId:!!g,hasSubagentMessages:!!h,subagentMessagesCount:h?.length,isReplay:E,isInReplayMode:this.isInReplayMode}),E||this.isInReplayMode)this.notifySessionUpdate(U);else{const z={type:"tool_call",id:o,toolCall:k,messageId:r},C=this.chunkResolvers.shift();C?C(z):this.messageQueue.push(z)}}else if(n?.sessionUpdate==="tool_call_update"){const r=n._meta&&typeof n._meta=="object"&&"messageId"in n._meta?String(n._meta.messageId):void 0,c=n._meta&&typeof n._meta=="object"&&"prettyName"in n._meta&&typeof n._meta.prettyName=="string"?n._meta.prettyName:void 0,m=n._meta&&typeof n._meta=="object"&&"icon"in n._meta&&typeof n._meta.icon=="string"?n._meta.icon:void 0,u=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,p=n._meta&&typeof n._meta=="object"&&"subagentSessionId"in n._meta&&typeof n._meta.subagentSessionId=="string"?n._meta.subagentSessionId:void 0,g=n._meta&&typeof n._meta=="object"&&"subagentMessages"in n._meta&&Array.isArray(n._meta.subagentMessages)?n._meta.subagentMessages:void 0;(d||p||g)&&L.info("Extracted subagent info from tool_call_update",{toolCallId:n.toolCallId,subagentPort:d,subagentSessionId:p,subagentMessagesCount:g?.length});const 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,f=n._meta&&typeof n._meta=="object"&&"finalTokens"in n._meta&&typeof n._meta.finalTokens=="number"?n._meta.finalTokens:void 0,y=n._meta&&typeof n._meta=="object"&&"originalContentPreview"in n._meta&&typeof n._meta.originalContentPreview=="string"?n._meta.originalContentPreview:void 0,j=n._meta&&typeof n._meta=="object"&&"originalContentPath"in n._meta&&typeof n._meta.originalContentPath=="string"?n._meta.originalContentPath:void 0,v={id:n.toolCallId??"",status:n.status,title:n.title,prettyName:c,icon:m,batchId:u,rawInput:n.rawInput,locations:n.locations,rawOutput:n.rawOutput,tokenUsage:n.tokenUsage,content:n.content?.map(U=>{if(typeof U!="object"||U===null)return{type:"text",text:""};const E=U;if(E.type==="content"&&typeof E.content=="object"&&E.content!==null){const z=E.content;if(z.type==="text")return{type:"content",content:{type:"text",text:typeof z.text=="string"?z.text:""}}}return E.type==="text"?{type:"text",text:typeof E.text=="string"?E.text:""}:E.type==="diff"?{type:"diff",path:typeof E.path=="string"?E.path:"",oldText:typeof E.oldText=="string"?E.oldText:"",newText:typeof E.newText=="string"?E.newText:"",line:typeof E.line=="number"?E.line:null}:E.type==="terminal"?{type:"terminal",terminalId:typeof E.terminalId=="string"?E.terminalId:""}:{type:"text",text:""}}),error:n.error,completedAt:n.status==="completed"||n.status==="failed"?Date.now():void 0,subagentPort:d,subagentSessionId:p,subagentMessages:g,_meta:h||x||f||y||j?{compactionAction:h,originalTokens:x,finalTokens:f,originalContentPreview:y,originalContentPath:j}:void 0},k={type:"tool_call_update",sessionId:o,status:"active",toolCallUpdate:v,messageId:r};if(this.isInReplayMode)this.notifySessionUpdate(k);else{const U={type:"tool_call_update",id:o,toolCallUpdate:v,messageId:r},E=this.chunkResolvers.shift();E?E(U):this.messageQueue.push(U)}L.debug("Processed tool_call_update",{sessionUpdate:k,isReplay:this.isInReplayMode})}else if(n&&"sessionUpdate"in n&&n.sessionUpdate==="hook_notification"){const r=n;L.debug("Received hook_notification",{id:r.id,notificationType:r.notification.type,hookType:r.notification.hookType});const c={type:"hook_notification",id:r.id,notification:r.notification,messageId:r.messageId},m=this.chunkResolvers.shift();m?m(c):this.messageQueue.push(c)}else if(n&&"sessionUpdate"in n&&n.sessionUpdate==="tool_output"){const r=n,c=r._meta&&typeof r._meta=="object"&&"messageId"in r._meta?String(r._meta.messageId):void 0,m={id:r.toolCallId??"",rawOutput:r.rawOutput,content:r.content?.map(d=>{if(typeof d!="object"||d===null)return{type:"text",text:""};const p=d;if(p.type==="content"&&typeof p.content=="object"&&p.content!==null){const g=p.content;if(g.type==="text")return{type:"content",content:{type:"text",text:typeof g.text=="string"?g.text:""}}}return p.type==="text"?{type:"text",text:typeof p.text=="string"?p.text:""}:p.type==="diff"?{type:"diff",path:typeof p.path=="string"?p.path:"",oldText:typeof p.oldText=="string"?p.oldText:"",newText:typeof p.newText=="string"?p.newText:"",line:typeof p.line=="number"?p.line:null}:p.type==="terminal"?{type:"terminal",terminalId:typeof p.terminalId=="string"?p.terminalId:""}:p.type==="image"?{type:"image",data:typeof p.data=="string"?p.data:"",mimeType:typeof p.mimeType=="string"?p.mimeType:"image/png",alt:typeof p.alt=="string"?p.alt:void 0}:{type:"text",text:""}})},u={type:"tool_call_update",sessionId:o,status:"active",toolCallUpdate:m,messageId:c};if(this.isInReplayMode)this.notifySessionUpdate(u);else{const d={type:"tool_call_update",id:o,toolCallUpdate:m,messageId:c},p=this.chunkResolvers.shift();p?p(d):this.messageQueue.push(d)}L.debug("Queued tool_output as tool_call_update chunk",{sessionUpdate:u})}else if(n&&"sessionUpdate"in n&&n.sessionUpdate==="sources"){const r=n;L.debug("Received sources notification",{sourcesCount:r.sources.length});const c={type:"sources",sources:r.sources},m=this.chunkResolvers.shift();m?m(c):this.messageQueue.push(c)}else if(n?.sessionUpdate==="agent_message_chunk"){const r=n._meta&&typeof n._meta=="object"&&"isReplay"in n._meta&&n._meta.isReplay===!0;if(this.isInReplayMode&&!r)return;const c=n._meta&&typeof n._meta=="object"&&"tokenUsage"in n._meta?n._meta.tokenUsage:void 0,m=n._meta&&typeof n._meta=="object"&&"contextInputTokens"in n._meta&&typeof n._meta.contextInputTokens=="number"?n._meta.contextInputTokens:void 0,u=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},p=n.content;if(p&&typeof p=="object"){const h=p;let x=null;if(h.type==="text"&&typeof h.text=="string"&&(x={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:h.text},tokenUsage:c,contextInputTokens:m,_meta:u?{context_size:u}:void 0,isComplete:!1}),x&&!r){const f=this.chunkResolvers.shift();f?f(x):this.messageQueue.push(x)}if(x&&typeof h.text=="string"&&(r||!this.isReceivingMessages)){const f={type:"generic",sessionId:o,status:"active",message:{id:me("assistant"),role:"assistant",content:[{type:"text",text:h.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(f)}}const g=d._meta&&"context_size"in d._meta;(!r||g)&&this.notifySessionUpdate(d)}else if(n?.sessionUpdate==="user_message_chunk"){L.debug("Received user_message_chunk",{update:n});const r=n.content;if(r&&typeof r=="object"){const c=r;if(c.type==="text"&&typeof c.text=="string"){const m={type:"generic",sessionId:o,status:"active",message:{id:me("user"),role:"user",content:[{type:"text",text:c.text}],timestamp:new Date().toISOString()}};L.debug("Notifying session update for user message"),this.notifySessionUpdate(m)}}}else{const r={type:"generic",sessionId:o,status:"active"};this.notifySessionUpdate(r)}}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){L.error("Error in session update callback",{error:n})}}notifyError(s){for(const a of this.errorCallbacks)try{a(s)}catch(n){L.error("Error in error callback",{error:n})}}}class Wo{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 Vo{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.")}async cancel(s){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 Ae=ue("acp-client","debug");class qo{constructor(s){this.config=s,this.transport=this.createTransport(),this.setupTransportListeners(),s.autoConnect&&this.connect().catch(a=>{Ae.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 c=new Date().toISOString(),m=this.transport.getAgentInfo?.()?.name,u={id:a,status:"connected",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:c,agentName:m}};return this.sessions.set(a,u),this.currentSessionId=a,a}const n=this.generateSessionId(),o=new Date().toISOString(),l=this.transport.getAgentInfo?.()?.name,r={id:n,status:"connecting",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o,agentName:l}};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 l=this.transport.getAgentInfo();l.name&&o.metadata&&(o.metadata.agentName=l.name)}return this.updateSessionStatus(s,"connected"),s}async listSessions(){return this.transport.listSessions?this.transport.listSessions():[]}async sendMessage(s,a,n,o){const l=a||this.currentSessionId;if(!l)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const r=this.sessions.get(l);if(!r)throw new Error(`Session ${l} not found`);const c=[];if(n&&n.length>0)for(const u of n)u.mimeType.startsWith("image/")&&c.push({type:"image",source:{type:"base64",media_type:u.mimeType,data:u.data}});c.push({type:"text",text:s});const m={id:me("user"),role:"user",content:c,timestamp:new Date().toISOString()};r.messages.push(m),this.updateSessionStatus(l,"active"),await this.transport.send(m,o?{promptParameters:o}:void 0)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}async cancel(s){const a=s||this.currentSessionId;if(!a){Ae.warn("Cannot cancel: no session ID");return}Ae.info("Cancelling session",{sessionId:a}),await this.transport.cancel(a)}async editAndResend(s,a,n,o){const l=n||this.currentSessionId;if(!l)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");if(!this.transport.editAndResend)throw new Error("Transport does not support edit and resend");const r=[];if(o&&o.length>0)for(const c of o)c.mimeType.startsWith("image/")&&r.push({type:"image",data:c.data,mimeType:c.mimeType});r.push({type:"text",text:a}),Ae.info("Edit and resend",{sessionId:l,messageIndex:s}),await this.transport.editAndResend(l,s,r)}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)}}onFileSystemChange(s,a){return this.transport&&"onFileSystemChange"in this.transport?this.transport.onFileSystemChange(s,a):()=>{}}getAgentInfo(){return this.transport.getAgentInfo?.()||{}}getBaseUrl(){if(this.config.type==="http")return this.config.options.baseUrl}createTransport(){switch(this.config.type){case"stdio":return new Wo(this.config.options);case"http":return new Ho(this.config.options);case"websocket":return new Vo(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){Ae.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){Ae.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)}`}}const Pe=ue("acp-client-hook");function Ko(t){const[s,a]=i.useState(null),[n,o]=i.useState(null),[l,r]=i.useState(null);return i.useEffect(()=>{const m=new URLSearchParams(window.location.search).get("session");m&&(Pe.info("Session ID found in URL",{sessionId:m}),r(m));try{Pe.info("Initializing ACP client",{serverUrl:t.serverUrl});const u=new qo({type:"http",options:{baseUrl:t.serverUrl}});return a(u),Pe.info("ACP client initialized successfully"),()=>{Pe.debug("Disconnecting ACP client"),u.disconnect().catch(d=>{Pe.error("Failed to disconnect ACP client",{error:d instanceof Error?d.message:String(d)})})}}catch(u){const d=u instanceof Error?u.message:"Failed to initialize ACP client";o(d),Pe.error("Failed to initialize ACP client",{error:u instanceof Error?u.message:String(u),stack:u instanceof Error?u.stack:void 0});return}},[t.serverUrl]),{client:s,error:n,sessionId:l}}const oe=ue("chat-store","debug"),ct=[];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 lt={sessionId:null,toolCallId:null,todos:ct};const Yo=t=>{const s=t.sessionId;if(!s)return ct;const n=(t.toolCalls[s]||[]).filter(r=>r.title==="todo_write").sort((r,c)=>(c.startedAt||0)-(r.startedAt||0));if(n.length===0)return ct;const o=n[0];if(!o?.rawInput?.todos||!Array.isArray(o.rawInput.todos))return ct;if(lt.sessionId===s&&lt.toolCallId===o.id)return lt.todos;const l=o.rawInput.todos.map((r,c)=>({id:`${o.id}-${c}`,text:r.status==="in_progress"?r.activeForm:r.content,status:r.status}));return lt={sessionId:s,toolCallId:o.id,todos:l},l},$=pa(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(u=>u.id===s);let l=n.totalBilled,r=n.currentContext,c=a;if(a.tokenUsage){const u=o?.tokenUsage;oe.debug("updateMessage: incoming tokenUsage",{incoming:a.tokenUsage,existing:u});const d={inputTokens:Math.max(a.tokenUsage.inputTokens??0,u?.inputTokens??0),outputTokens:Math.max(a.tokenUsage.outputTokens??0,u?.outputTokens??0),totalTokens:Math.max(a.tokenUsage.inputTokens??0,u?.inputTokens??0)+Math.max(a.tokenUsage.outputTokens??0,u?.outputTokens??0)};oe.debug("updateMessage: merged tokenUsage",{merged:d}),c={...a,tokenUsage:d};const p=d.inputTokens-(u?.inputTokens??0),g=d.outputTokens-(u?.outputTokens??0),h=d.totalTokens-(u?.totalTokens??0);l={inputTokens:n.totalBilled.inputTokens+p,outputTokens:n.totalBilled.outputTokens+g,totalTokens:n.totalBilled.totalTokens+h},r={inputTokens:d.inputTokens,outputTokens:n.currentContext.outputTokens+g,totalTokens:d.totalTokens}}const m=n.messages.map(u=>u.id===s?{...u,...c}:u);if(a.tokenUsage&&c.tokenUsage){const u=o?.tokenUsage,d=c.tokenUsage,p=(d.inputTokens??0)-(u?.inputTokens??0),g=(d.outputTokens??0)-(u?.outputTokens??0),h=(d.totalTokens??0)-(u?.totalTokens??0),x=m.filter(j=>j.tokenUsage).map(j=>({id:j.id,role:j.role,tokens:j.tokenUsage})),f=m.reduce((j,v)=>({inputTokens:j.inputTokens+(v.tokenUsage?.inputTokens??0),outputTokens:j.outputTokens+(v.tokenUsage?.outputTokens??0),totalTokens:j.totalTokens+(v.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),y=f.inputTokens===l.inputTokens&&f.outputTokens===l.outputTokens&&f.totalTokens===l.totalTokens;oe.debug("updateMessage: tokenUsage update",{messageId:s,updates:a.tokenUsage,existing:u,messageMax:d,delta:{inputDelta:p,outputDelta:g,totalDelta:h},totalBilled:l,currentContext:r,actualSum:f,billedCorrect:y?"✅":"❌",messageCount:m.length,messagesWithTokens:x.length,breakdown:x})}return{messages:m,totalBilled:l,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(m=>m.role==="assistant");if(n===-1){oe.debug("No assistant message found, creating one for tool call at position 0");const m={id:me("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,toolCalls:[{...s,contentPosition:0}]};return{messages:[...a.messages,m]}}const o=[...a.messages],l=o[n];if(!l)return a;const r=l.content.length,c={...s,contentPosition:r};return o[n]={...l,toolCalls:[...l.toolCalls||[],c]},{messages:o}}),updateToolCallInCurrentMessage:s=>t(a=>{const n=a.messages.findLastIndex(d=>d.role==="assistant");if(n===-1)return oe.warn("No assistant message found to update tool call in"),a;const o=[...a.messages],l=o[n];if(!l)return a;const r=l.toolCalls||[],c=r.findIndex(d=>d.id===s.id);if(c===-1)return oe.warn(`Tool call ${s.id} not found in message`),a;const m=r[c];if(!m)return a;const u=[...r];return u[c]=ns(m,s),o[n]={...l,toolCalls:u},{messages:o}}),addHookNotificationToCurrentMessage:s=>t(a=>{const n=a.messages.findLastIndex(d=>d.role==="assistant");if(n===-1){oe.debug("No assistant message found, creating one for hook notification");const d={...Rt(s),contentPosition:0},p={id:me("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,hookNotifications:[d]};return{messages:[...a.messages,p]}}const o=[...a.messages],l=o[n];if(!l)return a;const r=l.hookNotifications||[],c=l.content.length;if(s.type==="hook_triggered"){oe.debug("Adding hook_triggered notification for loading state",{hookType:s.hookType,callback:s.callback,contentPosition:c});const d={...Rt(s),contentPosition:c},p=[...r,d];return o[n]={...l,hookNotifications:p},{messages:o}}let m;const u=r.findIndex(d=>d.hookType===s.hookType&&d.callback===s.callback&&d.status==="triggered");if(u!==-1){const d=r[u];m=[...r];const p=s.type==="hook_completed"||s.type==="hook_error"?s.completedAt??Date.now():Date.now();m[u]={...d,status:s.type==="hook_completed"?"completed":"error",completedAt:p,...s.type==="hook_completed"&&s.metadata?{metadata:s.metadata}:{},...s.type==="hook_error"?{error:s.error}:{}},oe.debug("Merged hook notification with triggered state",{hookType:s.hookType,status:m[u]?.status})}else{const d={...Rt(s),contentPosition:c};m=[...r,d],oe.debug("Added hook notification without prior triggered state",{hookType:s.hookType,callback:s.callback,contentPosition:c})}return o[n]={...l,hookNotifications:m},{messages:o}}),addSourcesToCurrentMessage:s=>t(a=>{const n=a.messages.findLastIndex(r=>r.role==="assistant");if(n===-1){oe.debug("No assistant message found, creating one for sources");const r={id:me("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,sources:s};return{messages:[...a.messages,r]}}const o=[...a.messages],l=o[n];return l?(o[n]={...l,sources:[...l.sources||[],...s]},oe.debug("Added sources to current message",{sourcesCount:s.length,totalSources:(l.sources?.length||0)+s.length}),{messages:o}):a}),updateToolCall:(s,a)=>t(n=>{const o=n.toolCalls[s]||[],l=o.findIndex(m=>m.id===a.id);if(l===-1)return n;const r=o[l];if(!r)return n;const c=[...o];return c[l]=ns(r,a),{toolCalls:{...n.toolCalls,[s]:c}}}),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)}})),setSelectedPromptParameters:s=>t(a=>({input:{...a.input,selectedPromptParameters:s}})),clearInput:()=>t(s=>({input:{value:"",isSubmitting:!1,attachedFiles:[],selectedPromptParameters:void 0}})),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,l=a[o];return l?{tokenDisplayMode:l}:s}),addLog:s=>t(a=>({logs:[...a.logs,s]})),clearLogs:()=>t({logs:[]}),setActiveTab:s=>t({activeTab:s}),truncateMessagesFrom:s=>t(a=>({messages:a.messages.slice(0,s),totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}))})),Q=ue("use-chat-messages","debug");function sn(t,s){const a=$(C=>C.messages),n=$(C=>C.isStreaming),o=$(C=>C.sessionId),l=$(C=>C.setIsStreaming),r=$(C=>C.setStreamingStartTime),c=$(C=>C.addMessage),m=$(C=>C.updateMessage),u=$(C=>C.setError),d=$(C=>C.setLatestContextSize),p=$(C=>C.addToolCall),g=$(C=>C.updateToolCall),h=$(C=>C.addToolCallToCurrentMessage),x=$(C=>C.updateToolCallInCurrentMessage),f=$(C=>C.addHookNotificationToCurrentMessage),y=$(C=>C.addSourcesToCurrentMessage),j=$(C=>C.truncateMessagesFrom),v=i.useRef(null),k=i.useRef(!1),U=i.useCallback(async(C,A,Y)=>{if(Q.debug("[sendMessage] Called with",{contentLength:C.length,attachmentsCount:A?.length||0,hasAttachments:!!A&&A.length>0,hasPromptParameters:!!Y,promptParameters:Y}),!t){Q.error("No client available"),u("No client available");return}let H=o;if(!H){Q.info("Creating new session before sending first message");const K=await s();if(!K){Q.error("Failed to create session"),u("Failed to create session");return}H=K,Q.info("Session created successfully",{sessionId:K})}const W=me("assistant");try{const K=Date.now();l(!0),r(K);const D={id:me("user"),role:"user",content:C,timestamp:new Date().toISOString(),isStreaming:!1,...A&&A.length>0?{images:A.filter(S=>S.mimeType.startsWith("image/")).map(S=>({mimeType:S.mimeType,data:S.data}))}:{}};c(D);const R={id:W,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:K};c(R),v.current=W,k.current=!1;const N=t.receiveMessages();t.sendMessage(C,H,A,Y).catch(S=>{const M=S instanceof Error?S.message:String(S);u(M),l(!1),r(null)});let _="",T=!1;for await(const S of N){if(k.current){Q.info("Stream cancelled, exiting loop");break}if(S.type==="content"){const M=S._meta,I=M?.context_size||S.context_size;if(I!=null){const V=I;Q.info("✅ Received context_size from backend",{context_size:V,totalEstimated:V.totalEstimated,source:M?.context_size?"_meta":"direct"}),d(V)}else Q.debug("Chunk does not have context_size",{hasContextSize:"context_size"in S,hasMeta:"_meta"in S,metaKeys:M?Object.keys(M):null});if(S.tokenUsage&&Q.debug("Received tokenUsage from backend",{tokenUsage:S.tokenUsage}),S.isComplete){m(W,{content:_,isStreaming:!1,streamingStartTime:void 0,...S.tokenUsage?{tokenUsage:S.tokenUsage}:{}}),l(!1),r(null),v.current=null,T=!0;break}else S.contentDelta.type==="text"&&(_+=S.contentDelta.text,m(W,{content:_,...S.tokenUsage?{tokenUsage:S.tokenUsage}:{}}),document.hidden||await new Promise(V=>setTimeout(V,16)))}else S.type==="tool_call"?(Q.debug("Received tool_call chunk",{chunk:S}),p(H,S.toolCall),h(S.toolCall)):S.type==="tool_call_update"?(Q.debug("Received tool_call_update chunk",{chunk:S}),g(H,S.toolCallUpdate),x(S.toolCallUpdate)):S.type==="hook_notification"?(Q.debug("Received hook_notification chunk",{chunk:S}),f(S.notification)):S.type==="sources"&&(Q.debug("Received sources chunk",{chunk:S}),y(S.sources))}T||(k.current?(Q.info("Stream cancelled by user"),m(W,{content:`${_}
3
+
4
+ [Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Q.warn("Stream ended without isComplete flag"),m(W,{isStreaming:!1,streamingStartTime:void 0})),l(!1),r(null),v.current=null)}catch(K){const D=K instanceof Error?K.message:String(K);u(D),l(!1),r(null),v.current=null,m(W,{isStreaming:!1,streamingStartTime:void 0})}},[t,o,s,c,m,l,r,u,d,p,g,h,x,f,y]),E=i.useCallback(async()=>{if(!t||!n){Q.debug("Cannot cancel: not streaming or no client");return}Q.info("Cancelling current turn"),k.current=!0;try{await t.cancel(o||void 0)}catch(C){Q.error("Error cancelling turn",{error:C})}},[t,n,o]),z=i.useCallback(async(C,A,Y)=>{if(Q.debug("[editAndResend] Called with",{userMessageIndex:C,contentLength:A.length,attachmentsCount:Y?.length||0}),!t){Q.error("No client available"),u("No client available");return}if(!o){Q.error("No session available"),u("No session available");return}let H=0,W=-1;for(let R=0;R<a.length;R++)if(a[R]?.role==="user"){if(H===C){W=R;break}H++}if(W===-1){Q.error("User message not found",{userMessageIndex:C,totalUserMessages:H}),u("User message not found");return}const K=a[W];Q.debug("[editAndResend] Found target message",{userMessageIndex:C,targetArrayIndex:W,messageRole:K?.role});const D=me("assistant");try{const R=Date.now();l(!0),r(R),j(W);const N={id:me("user"),role:"user",content:A,timestamp:new Date().toISOString(),isStreaming:!1,...Y&&Y.length>0?{images:Y.filter(I=>I.mimeType.startsWith("image/")).map(I=>({mimeType:I.mimeType,data:I.data}))}:{}};c(N);const _={id:D,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:R};c(_),v.current=D,k.current=!1;const T=t.receiveMessages();t.editAndResend(C,A,o,Y).catch(I=>{const V=I instanceof Error?I.message:String(I);u(V),l(!1),r(null)});let S="",M=!1;for await(const I of T){if(k.current){Q.info("Stream cancelled, exiting loop");break}if(I.type==="content"){const J=I._meta?.context_size||I.context_size;if(J!=null){const B=J;Q.info("✅ Received context_size from backend",{context_size:B,totalEstimated:B.totalEstimated}),d(B)}if(I.isComplete){m(D,{content:S,isStreaming:!1,streamingStartTime:void 0,...I.tokenUsage?{tokenUsage:I.tokenUsage}:{}}),l(!1),r(null),v.current=null,M=!0;break}else I.contentDelta.type==="text"&&(S+=I.contentDelta.text,m(D,{content:S,...I.tokenUsage?{tokenUsage:I.tokenUsage}:{}}),document.hidden||await new Promise(B=>setTimeout(B,16)))}else I.type==="tool_call"?(Q.debug("Received tool_call chunk",{chunk:I}),p(o,I.toolCall),h(I.toolCall)):I.type==="tool_call_update"?(Q.debug("Received tool_call_update chunk",{chunk:I}),g(o,I.toolCallUpdate),x(I.toolCallUpdate)):I.type==="hook_notification"?(Q.debug("Received hook_notification chunk",{chunk:I}),f(I.notification)):I.type==="sources"&&(Q.debug("Received sources chunk",{chunk:I}),y(I.sources))}M||(k.current?(Q.info("Stream cancelled by user"),m(D,{content:`${S}
5
+
6
+ [Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Q.warn("Stream ended without isComplete flag"),m(D,{isStreaming:!1,streamingStartTime:void 0})),l(!1),r(null),v.current=null)}catch(R){const N=R instanceof Error?R.message:String(R);u(N),l(!1),r(null),v.current=null,m(D,{isStreaming:!1,streamingStartTime:void 0})}},[t,o,a,j,c,m,l,r,u,d,p,g,h,x,f,y]);return{messages:a,isStreaming:n,sendMessage:U,editAndResend:z,cancel:E}}const rs=ue("use-chat-input","debug");function Go(t,s){const a=$(g=>g.input),n=$(g=>g.setInputValue),o=$(g=>g.setInputSubmitting),l=$(g=>g.addFileAttachment),r=$(g=>g.removeFileAttachment),{sendMessage:c}=sn(t,s),m=i.useCallback(g=>{n(g)},[n]),u=i.useCallback(async()=>{const g=$.getState().input;if(!g.value.trim()||g.isSubmitting)return;const h=g.value,x=g.attachedFiles,f=g.selectedPromptParameters;rs.debug("Submitting message with attachments",{messageLength:h.length,attachmentCount:x.length,hasAttachments:x.length>0,hasPromptParameters:!!f&&Object.keys(f).length>0,promptParameters:f}),n(""),o(!0);try{await c(h,x.length>0?x:void 0,f&&Object.keys(f).length>0?f:void 0),$.setState(y=>({input:{...y.input,attachedFiles:[]}}))}catch(y){rs.error("Failed to send message",{error:y instanceof Error?y.message:String(y)})}finally{o(!1)}},[n,o,c]),d=i.useCallback(g=>{l(g)},[l]),p=i.useCallback(g=>{r(g)},[r]);return{value:a.value,isSubmitting:a.isSubmitting,attachedFiles:a.attachedFiles,onChange:m,onSubmit:u,onAttachFile:d,onRemoveFile:p}}const Ne=ue("use-chat-session","debug");function Qo(t,s){const a=$(f=>f.connectionStatus),n=$(f=>f.sessionId),o=$(f=>f.setConnectionStatus),l=$(f=>f.setSessionId),r=$(f=>f.setError),c=$(f=>f.clearMessages),m=$(f=>f.resetTokens),u=$(f=>f.addMessage),d=$(f=>f.setLatestContextSize);i.useEffect(()=>t?t.onSessionUpdate(y=>{const j=y._meta,v=j?.context_size||y.context_size;if(v!=null){const k=v;Ne.info("✅ Received context_size from session update",{context_size:k,totalEstimated:k.totalEstimated,isReplay:j?.isReplay}),d(k)}if(y.message&&(Ne.debug("Session update with message",{message:y.message}),y.message.role!=="tool")){const k=y.message.content.map(C=>C.type==="text"?C.text:"").join(""),U=[];for(const C of y.message.content)if(C.type==="image"){const A=C;A.source?.data?U.push({mimeType:A.source.media_type||"image/png",data:A.source.data}):A.data&&U.push({mimeType:A.mimeType||"image/png",data:A.data})}const E=$.getState().messages,z=E[E.length-1];if(y.message.role==="assistant"&&z?.role==="assistant"&&z.content===""&&k)Ne.debug("Appending text to existing assistant message"),$.getState().updateMessage(z.id,{content:z.content+k});else{const C={id:y.message.id,role:y.message.role,content:k,timestamp:y.message.timestamp,isStreaming:!1,...U.length>0?{images:U}:{}};u(C)}}}):void 0,[t,u,d]);const p=i.useCallback(async()=>{if(!t){r("No client available");return}try{o("connecting"),r(null),await t.connect();const f=t.getCurrentSession();if(f?.id&&(l(f.id),typeof window<"u")){const y=new URL(window.location.href);y.searchParams.set("session",f.id),window.history.replaceState({},"",y.toString())}o("connected")}catch(f){Ne.error("Failed to connect",{error:f instanceof Error?f.message:String(f)});const y=f instanceof Error?f.message:String(f);r(y),o("error")}},[t,o,l,r]),g=i.useCallback(async f=>{if(!t){r("No client available");return}try{o("connecting"),r(null),c(),m();const y=await t.loadSession(f);l(y),o("connected"),Ne.info("Session loaded successfully",{sessionId:y})}catch(y){Ne.warn("Failed to load session, creating new one instead",{sessionId:f,error:y instanceof Error?y.message:String(y)});try{await p();const j=await t.startSession();if(l(j),c(),m(),typeof window<"u"){const v=new URL(window.location.href);v.searchParams.set("session",j),window.history.replaceState({},"",v.toString())}Ne.info("Created new session after failed load",{sessionId:j})}catch(j){const v=j instanceof Error?j.message:String(j);r(`Failed to load or create session: ${v}`),o("error")}}},[t,o,l,r,c,m,p]),h=i.useCallback(async()=>{if(!t)return r("No client available"),null;try{const f=await t.startSession();if(l(f),$.getState().messages.length===0&&(c(),m()),typeof window<"u"){const j=new URL(window.location.href);j.searchParams.set("session",f),window.history.pushState({},"",j.toString())}return f}catch(f){const y=f instanceof Error?f.message:String(f);return r(y),null}},[t,l,r,c,m]),x=i.useCallback(async()=>{if(t)try{await t.disconnect(),o("disconnected"),l(null)}catch(f){const y=f instanceof Error?f.message:String(f);r(y)}},[t,o,l,r]);return i.useEffect(()=>{!t||a!=="disconnected"||(s?(Ne.info("Loading initial session from URL",{sessionId:s}),g(s)):p())},[t,a,s,p,g]),{connectionStatus:a,sessionId:n,connect:p,loadSession:g,startSession:h,disconnect:x}}const is="town-message-history",Jo=100;function Xo(){const[t,s]=i.useState(-1),[a,n]=i.useState(""),o=i.useCallback(()=>{try{const d=localStorage.getItem(is);return d?JSON.parse(d):[]}catch{return[]}},[]),l=i.useCallback(d=>{const p=d.trim();if(p){try{const g=o();if(g[0]===p)return;const h=[p,...g].slice(0,Jo);localStorage.setItem(is,JSON.stringify(h))}catch{}s(-1),n("")}},[o]),r=i.useCallback(d=>{const p=o();if(p.length===0)return null;t===-1&&n(d);const g=Math.min(t+1,p.length-1);if(g===t)return null;const h=p[g];return h===void 0?null:(s(g),h)},[t,o]),c=i.useCallback(()=>{if(t===-1)return null;const d=o();if(t===0){s(-1);const h=a;return n(""),h}const p=t-1,g=d[p];return g===void 0?null:(s(p),g)},[t,a,o]),m=i.useCallback(()=>{t!==-1&&(s(-1),n(""))},[t]);return{addToHistory:l,navigatePrevious:r,navigateNext:c,resetNavigation:m,isBrowsingHistory:t!==-1,historyIndex:t}}const ls=ue("use-tool-calls","debug");function Zo(t){const s=$(r=>r.toolCalls),a=$(r=>r.addToolCall),n=$(r=>r.updateToolCall),o=$(r=>r.addToolCallToCurrentMessage),l=$(r=>r.updateToolCallInCurrentMessage);return i.useEffect(()=>{if(!t)return;const r=t.onSessionUpdate(c=>{c.type==="tool_call"?(a(c.sessionId,c.toolCall),o(c.toolCall)):c.type==="tool_call_update"&&(ls.info("[SUBAGENT] Frontend received tool_call_update",{sessionId:c.sessionId,toolCallId:c.toolCallUpdate.id,status:c.toolCallUpdate.status,hasSubagentMessages:!!c.toolCallUpdate.subagentMessages,subagentMessageCount:c.toolCallUpdate.subagentMessages?.length||0}),n(c.sessionId,c.toolCallUpdate),l(c.toolCallUpdate),ls.info("[SUBAGENT] Successfully updated tool call state",{sessionId:c.sessionId,toolCallId:c.toolCallUpdate.id}))});return()=>{r()}},[t,a,n,o,l]),{toolCalls:s,getToolCallsForSession:r=>{const c=s[r];return c&&c.length>0?c:Object.values(s).flat()}}}const er=O({name:w(),description:w().optional(),parameters:te(w(),ie()).optional()}),tr=O({name:w(),description:w(),parameters:te(w(),ie()),required:Z(w()).optional()}),sr=O({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:Z(er).optional(),tools:Z(tr).optional(),supportedFormats:Z(w()).optional()}),nr=ae(["initializing","ready","busy","error","terminated"]);O({status:nr,info:sr.optional(),pid:F().optional(),error:w().optional(),uptime:F().optional()});const nn=ae(["idle","connecting","connected","active","streaming","error","disconnected"]),ar=O({agentPath:w(),agentArgs:Z(w()).optional(),environment:te(w(),w()).optional(),workingDirectory:w().optional(),timeout:F().optional()}),or=O({agentName:w().optional(),agentVersion:w().optional(),capabilities:Z(w()).optional(),startedAt:dt(),lastActivityAt:dt().optional()});O({id:w(),status:nn,config:ar,metadata:or.optional(),messages:Z(Js),error:w().optional()});const St=O({sessionId:w(),status:nn.optional(),message:Js.optional(),error:w().optional(),_meta:te(w(),ie()).optional()}),rr=St.extend({type:X("tool_call"),toolCall:tn,messageId:w().optional()}),ir=St.extend({type:X("tool_call_update"),toolCallUpdate:zo,messageId:w().optional()}),lr=St.extend({type:X("tool_output"),toolOutput:O({id:w(),content:Z(zt()).optional(),rawOutput:te(w(),ie()).optional()}),messageId:w().optional()}),cr=St.extend({type:X("generic").optional()});fa([rr,ir,lr,cr]);const dr=[{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 ur{data;constructor(s=dr){this.data=s}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(s){const a=o=>{for(const l of o){if(l.id===s)return l;if(l.children){const r=a(l.children);if(r)return r}}},n=a(this.data);return Promise.resolve(n?.children||[])}async getItemDetails(s){const a=o=>{for(const l of o){if(l.id===s)return l;if(l.children){const r=a(l.children);if(r)return r}}},n=a(this.data);if(!n)throw new Error(`Item with id ${s} not found`);return Promise.resolve(n)}}function b(...t){return ga(ha(t))}const mr=we("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"}}),ne=i.forwardRef(({className:t,variant:s,size:a,asChild:n=!1,...o},l)=>{const r=n?de:"button";return e.jsx(r,{className:b(mr({variant:s,size:a,className:t})),ref:l,...o})});ne.displayName="Button";const fe=wa,ge=ja,he=Na,ce=i.forwardRef(({className:t,sideOffset:s=4,...a},n)=>e.jsx(ys,{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}));ce.displayName=ys.displayName;const an=({className:t,children:s,...a})=>e.jsx("div",{className:b("flex items-center gap-1",t),...a,children:s}),mt=({tooltip:t,children:s,label:a,className:n,variant:o="ghost",size:l="sm",...r})=>{const c=e.jsxs(ne,{className:b("relative size-7 p-1.5 text-muted-foreground hover:text-foreground",n),size:l,type:"button",variant:o,...r,children:[s,e.jsx("span",{className:"sr-only",children:a||t})]});return t?e.jsx(fe,{children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:c}),e.jsx(ce,{children:e.jsx("p",{children:t})})]})}):c},Ce=i.forwardRef(({className:t,...s},a)=>e.jsx(ne,{ref:a,variant:"ghost",size:"icon",className:b("rounded-full",t),...s}));Ce.displayName="IconButton";const st=Ca,nt=ka,pr=i.forwardRef(({className:t,inset:s,children:a,...n},o)=>e.jsxs(vs,{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(qe,{className:"ml-auto h-4 w-4"})]}));pr.displayName=vs.displayName;const fr=i.forwardRef(({className:t,...s},a)=>e.jsx(ws,{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}));fr.displayName=ws.displayName;const Le=i.forwardRef(({className:t,sideOffset:s=4,...a},n)=>e.jsx(Sa,{children:e.jsx(js,{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})}));Le.displayName=js.displayName;const pe=i.forwardRef(({className:t,inset:s,...a},n)=>e.jsx(Ns,{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}));pe.displayName=Ns.displayName;const gr=i.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(Ss,{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(Cs,{children:e.jsx(bt,{className:"h-4 w-4"})})}),s]}));gr.displayName=Ss.displayName;const hr=i.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(ks,{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(Cs,{children:e.jsx(yt,{className:"h-2 w-2 fill-current"})})}),s]}));hr.displayName=ks.displayName;const xr=i.forwardRef(({className:t,inset:s,...a},n)=>e.jsx(Ts,{ref:n,className:b("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...a}));xr.displayName=Ts.displayName;const on=i.forwardRef(({className:t,...s},a)=>e.jsx(Is,{ref:a,className:b("-mx-1 my-1 h-px bg-border",t),...s}));on.displayName=Is.displayName;const br=256,yr="calc(100vw - 104px)",rn=450,cs=250,ds=800,vr=720,wr=56,jr=wr*2;function ln(t){i.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 _t=768;function cn(){const[t,s]=i.useState(void 0);return i.useEffect(()=>{const a=window.matchMedia(`(max-width: ${_t-1}px)`),n=()=>{s(window.innerWidth<_t)};return a.addEventListener("change",n),s(window.innerWidth<_t),()=>a.removeEventListener("change",n)},[]),!!t}const at={smooth:[.25,.1,.25,1]},Nr={duration:.25,ease:at.smooth},us={duration:.15,ease:at.smooth},Sr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},Cr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},ms={initial:{opacity:0,x:-20},animate:{opacity:1,x:0}},ps={duration:.25,ease:at.smooth,delay:.1},kr={initial:{opacity:0},animate:{opacity:1},exit:{opacity:0}},Tr={initial:{x:"100%"},animate:{x:0},exit:{x:"100%"}},Ir={initial:{opacity:0,x:20},animate:{opacity:1,x:0}},Rr={duration:.25,ease:at.smooth,delay:.1},_r={duration:.15,ease:at.smooth},Mr=we("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"}}),dn=i.forwardRef(({className:t,type:s,variant:a,...n},o)=>e.jsx("input",{type:s,className:b(Mr({variant:a,className:t})),ref:o,...n}));dn.displayName="Input";const Er="sidebar_state",Ar=3600*24*7,Pr="s",un=i.createContext(null);function ke(){const t=i.useContext(un);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const mn=i.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:a,className:n,style:o,children:l,...r},c)=>{const m=cn(),[u,d]=i.useState(!1),[p,g]=i.useState(t),h=s??p,x=i.useCallback(v=>{const k=typeof v=="function"?v(h):v;a?a(k):g(k),document.cookie=`${Er}=${k}; path=/; max-age=${Ar}`},[a,h]),f=i.useCallback(()=>m?d(v=>!v):x(v=>!v),[m,x]);i.useEffect(()=>{const v=k=>{k.key.toLowerCase()===Pr&&k.shiftKey&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),f())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[f]);const y=h?"expanded":"collapsed",j=i.useMemo(()=>({state:y,open:h,setOpen:x,isMobile:m,openMobile:u,setOpenMobile:d,toggleSidebar:f}),[y,h,x,m,u,f]);return e.jsx(un.Provider,{value:j,children:e.jsx(fe,{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:c,style:o,...r,children:l})})})});mn.displayName="SidebarProvider";const pn=i.forwardRef(({className:t,children:s},a)=>{const{isMobile:n,open:o,openMobile:l,setOpenMobile:r}=ke();return ln(n&&l),n?e.jsx(Xe,{initial:!1,children:l&&e.jsxs(e.Fragment,{children:[e.jsx(ye.div,{className:"fixed inset-0 z-40 bg-background/80",variants:kr,initial:"initial",animate:"animate",exit:"exit",transition:us,onClick:()=>r(!1),"aria-label":"Close sidebar"}),e.jsx(ye.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:yr},variants:Cr,initial:"initial",animate:"animate",exit:"exit",transition:us,"data-sidebar":"sidebar","data-mobile":"true",children:e.jsx(ye.div,{className:"flex flex-col h-full overflow-y-auto",variants:ms,initial:"initial",animate:"animate",transition:ps,children:s})})]})}):e.jsx("div",{className:"group peer hidden md:block","data-state":o?"expanded":"collapsed","data-side":"left",ref:a,children:e.jsx(Xe,{initial:!1,mode:"wait",children:o&&e.jsx(ye.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:br},variants:Sr,initial:"initial",animate:"animate",exit:"exit",transition:Nr,"data-sidebar":"sidebar",children:e.jsx(ye.div,{className:"flex flex-col h-full overflow-y-auto",variants:ms,initial:"initial",animate:"animate",transition:ps,children:s})})})})});pn.displayName="Sidebar";const Dr=i.forwardRef(({className:t,onClick:s,...a},n)=>{const{toggleSidebar:o}=ke();return e.jsxs(ne,{className:b("h-7 w-7",t),"data-sidebar":"trigger",onClick:l=>{s?.(l),o()},ref:n,size:"icon",variant:"ghost",...a,children:[e.jsx(Aa,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Dr.displayName="SidebarTrigger";const Ur=i.forwardRef(({className:t,...s},a)=>{const{toggleSidebar:n}=ke();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})});Ur.displayName="SidebarRail";const fn=i.forwardRef(({className:t,children:s,...a},n)=>{const{isMobile:o,open:l}=ke();return e.jsx("main",{className:b("relative flex w-full flex-1 flex-col bg-background transition-all duration-250",!o&&l&&"md:pl-64",t),ref:n,...a,children:s})});fn.displayName="SidebarInset";const zr=i.forwardRef(({className:t,...s},a)=>e.jsx(dn,{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}));zr.displayName="SidebarInput";const gn=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{className:b("flex flex-col gap-2 p-2",t),"data-sidebar":"header",ref:a,...s}));gn.displayName="SidebarHeader";const hn=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{className:b("flex flex-col gap-2 p-2",t),"data-sidebar":"footer",ref:a,...s}));hn.displayName="SidebarFooter";const $r=i.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}));$r.displayName="SidebarSeparator";const xn=i.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}));xn.displayName="SidebarContent";const We=i.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}));We.displayName="SidebarGroup";const bn=i.forwardRef(({className:t,asChild:s=!1,...a},n)=>{const o=s?de:"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})});bn.displayName="SidebarGroupLabel";const Lr=i.forwardRef(({className:t,asChild:s=!1,...a},n)=>{const o=s?de:"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})});Lr.displayName="SidebarGroupAction";const Ve=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{className:b("w-full text-sm",t),"data-sidebar":"group-content",ref:a,...s}));Ve.displayName="SidebarGroupContent";const yn=i.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}));yn.displayName="SidebarMenu";const vn=i.forwardRef(({className:t,...s},a)=>e.jsx("li",{className:b("group/menu-item relative",t),"data-sidebar":"menu-item",ref:a,...s}));vn.displayName="SidebarMenuItem";const Or=we("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"}}),wn=i.forwardRef(({asChild:t=!1,isActive:s=!1,variant:a="default",size:n="default",tooltip:o,className:l,...r},c)=>{const m=t?de:"button",{isMobile:u,state:d}=ke(),p=e.jsx(m,{className:b(Or({variant:a,size:n}),l),"data-active":s,"data-sidebar":"menu-button","data-size":n,ref:c,type:t?void 0:"button",...r});return o?(typeof o=="string"&&(o={children:o}),e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:p}),e.jsx(ce,{align:"center",hidden:d!=="collapsed"||u,side:"right",...o})]})):p});wn.displayName="SidebarMenuButton";const jn=i.forwardRef(({className:t,asChild:s=!1,showOnHover:a=!1,...n},o)=>{const l=s?de:"button";return e.jsx(l,{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})});jn.displayName="SidebarMenuAction";const Fr=i.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}));Fr.displayName="SidebarMenuBadge";const Br=i.forwardRef(({className:t,showIcon:s=!1,...a},n)=>{const o=i.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}})]})});Br.displayName="SidebarMenuSkeleton";const Hr=i.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}));Hr.displayName="SidebarMenuSub";const Wr=i.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));Wr.displayName="SidebarMenuSubItem";const Vr=i.forwardRef(({asChild:t=!1,size:s="md",isActive:a,className:n,...o},l)=>{const r=t?de:"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:l,...o})});Vr.displayName="SidebarMenuSubButton";const qr=({session:t,isActive:s,onSelect:a,onRename:n,onArchive:o,onDelete:l,setOpenMobile:r})=>e.jsxs(vn,{children:[e.jsx(wn,{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(st,{modal:!0,children:[e.jsx(nt,{asChild:!0,children:e.jsxs(jn,{className:"mr-0.5 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",showOnHover:!s,children:[e.jsx(Pa,{}),e.jsx("span",{className:"sr-only",children:"More"})]})}),e.jsxs(Le,{align:"end",side:"bottom",children:[e.jsx(pe,{className:"cursor-pointer",disabled:!n,onSelect:()=>n?.(t.sessionId),children:"Rename"}),e.jsx(pe,{className:"cursor-pointer",disabled:!o,onSelect:()=>o?.(t.sessionId),children:"Archive"}),e.jsx(on,{}),e.jsx(pe,{className:b("cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive"),disabled:!l,onSelect:()=>l?.(t.sessionId),children:"Delete"})]})]})]}),Fe=i.memo(qr,(t,s)=>!(t.isActive!==s.isActive||t.session.sessionId!==s.session.sessionId||t.session.firstUserMessage!==s.session.firstUserMessage)),Kr=ue("session-history"),Yr=t=>{const s=new Date;return t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},Gr=t=>{const s=new Date;return s.setDate(s.getDate()-1),t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},Qr=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,l)=>{const r=new Date(l.updatedAt);return Yr(r)?o.today.push(l):Gr(r)?o.yesterday.push(l):r>a?o.lastWeek.push(l):r>n?o.lastMonth.push(l):o.older.push(l),o},{today:[],yesterday:[],lastWeek:[],lastMonth:[],older:[]})};function Jr({client:t,currentSessionId:s,onSessionSelect:a,onRenameSession:n,onArchiveSession:o,onDeleteSession:l}){const{setOpenMobile:r}=ke(),[c,m]=i.useState([]),[u,d]=i.useState(!1),p=i.useCallback(async()=>{if(t){d(!0);try{const x=await t.listSessions();m(x)}catch(x){Kr.error("Failed to fetch sessions",{error:x})}finally{d(!1)}}},[t]);i.useEffect(()=>{p()},[p]);const g=x=>{if(x!==s)if(a)a(x);else{const f=new URL(window.location.href);f.searchParams.set("session",x),window.location.href=f.toString()}};if(!t)return e.jsx(We,{children:e.jsx(Ve,{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(u)return e.jsxs(We,{children:[e.jsx(bn,{children:"Today"}),e.jsx(Ve,{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(c.length===0)return e.jsx(We,{children:e.jsx(Ve,{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=Qr(c);return e.jsx(We,{children:e.jsx(Ve,{children:e.jsx(yn,{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(Fe,{session:x,isActive:x.sessionId===s,onSelect:g,onRename:n,onArchive:o,onDelete:l,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(Fe,{session:x,isActive:x.sessionId===s,onSelect:g,onRename:n,onArchive:o,onDelete:l,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(Fe,{session:x,isActive:x.sessionId===s,onSelect:g,onRename:n,onArchive:o,onDelete:l,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(Fe,{session:x,isActive:x.sessionId===s,onSelect:g,onRename:n,onArchive:o,onDelete:l,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(Fe,{session:x,isActive:x.sessionId===s,onSelect:g,onRename:n,onArchive:o,onDelete:l,setOpenMobile:r},x.sessionId))]})]})})})})}const Xr={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Nn=i.createContext(Xr);function Zr({children:t,defaultTheme:s="system",storageKey:a="vite-ui-theme"}){const[n,o]=i.useState(()=>localStorage.getItem(a)||s),[l,r]=i.useState("light");i.useEffect(()=>{const m=window.document.documentElement;if(m.classList.remove("light","dark"),n==="system"){const u=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";m.classList.add(u),r(u);return}m.classList.add(n),r(n)},[n]);const c={theme:n,setTheme:m=>{localStorage.setItem(a,m),o(m)},resolvedTheme:l};return e.jsx(Nn.Provider,{value:c,children:t})}const Wt=()=>{const t=i.useContext(Nn);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function ei(){const{setTheme:t}=Wt();return e.jsxs(st,{children:[e.jsx(nt,{asChild:!0,children:e.jsxs(Ce,{children:[e.jsx(Bs,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Hs,{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(Le,{align:"end",children:[e.jsx(pe,{onClick:()=>t("light"),children:"Light"}),e.jsx(pe,{onClick:()=>t("dark"),children:"Dark"}),e.jsx(pe,{onClick:()=>t("system"),children:"System"})]})]})}function ti({client:t,currentSessionId:s,onSessionSelect:a,onNewSession:n,onRenameSession:o,onArchiveSession:l,onDeleteSession:r,className:c}){const{setOpenMobile:m}=ke(),u=()=>{if(n)n();else{const d=new URL(window.location.href);d.searchParams.delete("session"),window.location.href=d.toString()}m(!1)};return e.jsxs(pn,{className:b("group-data-[side=left]:border-r-0",c),children:[e.jsx(gn,{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(Ce,{onClick:u,"aria-label":"New Chat",variant:"default",children:e.jsx(Da,{className:"size-4"})})]})}),e.jsx(xn,{className:"gap-6",children:e.jsx(Jr,{client:t,currentSessionId:s,onSessionSelect:a,onRenameSession:o,onArchiveSession:l,onDeleteSession:r})}),e.jsx(hn,{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(ei,{}),e.jsx(Ce,{"aria-label":"Settings",children:e.jsx($t,{className:"size-4 text-muted-foreground"})})]})})]})}const si=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:b("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));si.displayName="Card";const ni=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:b("flex flex-col space-y-1.5 p-6",t),...s}));ni.displayName="CardHeader";const ai=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:b("text-2xl font-semibold leading-none tracking-tight",t),...s}));ai.displayName="CardTitle";const oi=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:b("text-sm text-muted-foreground",t),...s}));oi.displayName="CardDescription";const ri=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:b("p-6 pt-0",t),...s}));ri.displayName="CardContent";const ii=i.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:b("flex items-center p-6 pt-0",t),...s}));ii.displayName="CardFooter";const Sn=i.forwardRef(({title:t,titleElement:s,description:a,guideUrl:n,guideText:o="Guide",suggestedPrompts:l=[],onPromptClick:r,onGuideClick:c,onOpenFiles:m,onOpenSettings:u,toolsAndMcpsCount:d,onPromptHover:p,onPromptLeave:g,className:h,...x},f)=>{const y=k=>{r?.(k)},j=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),c?.()},v=[];for(let k=0;k<l.length;k+=2)v.push(l.slice(k,k+2));return e.jsxs("div",{ref:f,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}),(m||u)&&e.jsxs("div",{className:"flex items-center gap-1 -ml-3 mb-6",children:[m&&e.jsxs("button",{type:"button",onClick:m,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(qe,{className:"size-4 text-foreground shrink-0"})]}),u&&e.jsxs("button",{type:"button",onClick:u,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",d!==void 0&&d>0&&e.jsxs("span",{className:"ml-1",children:["(",d,")"]})]}),e.jsx(qe,{className:"size-4 text-foreground shrink-0"})]})]}),(n||c)&&e.jsxs("button",{type:"button",onClick:j,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(qe,{className:"size-4 text-foreground shrink-0"})]}),l.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:v.map(k=>e.jsx("div",{className:"flex gap-2.5 items-center",children:k.map(U=>e.jsx("button",{type:"button",onClick:()=>y(U),onMouseEnter:()=>p?.(U),onMouseLeave:()=>g?.(),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:U})},U))},k.join("-")))})]})]})});Sn.displayName="ChatEmptyState";const Cn=i.forwardRef(({className:t,children:s,...a},n)=>e.jsx("div",{ref:n,className:b("flex items-center justify-between",t),...a,children:s}));Cn.displayName="ChatHeader.Root";const li=i.forwardRef(({className:t,children:s,...a},n)=>e.jsx("h1",{ref:n,className:b("m-0 text-subheading font-semibold",t),...a,children:s}));li.displayName="ChatHeader.Title";const ci=i.forwardRef(({className:t,children:s,...a},n)=>e.jsx("div",{ref:n,className:b("flex items-center gap-3",t),...a,children:s}));ci.displayName="ChatHeader.Actions";const kn=i.forwardRef(({commands:t=[],showCommandMenu:s,commandMenuQuery:a,selectedMenuIndex:n,setSelectedMenuIndex:o,setMenuItemCount:l,triggerCounter:r,onChange:c,onClose:m,className:u,...d},p)=>{const g=i.useCallback((f,y)=>{const j=f.toLowerCase(),v=y.toLowerCase();if(!y)return 1;if(j.includes(v))return 1-v.length/j.length;let k=0;for(let U=0;U<j.length&&k<v.length;U++)j[U]===v[k]&&k++;return k===v.length?.5-k/j.length:0},[]),h=i.useMemo(()=>t.map(f=>({...f,score:Math.max(g(f.label,a),f.description?g(f.description,a):0)})).filter(f=>f.score>0).sort((f,y)=>y.score-f.score),[t,a,g]);i.useEffect(()=>{l(h.length)},[h.length,l]),i.useEffect(()=>{o(0)},[o]);const x=i.useRef(0);return i.useEffect(()=>{r>0&&r!==x.current&&h[n]&&(x.current=r,h[n].onSelect(),c(""),m?.())},[r,h,n,c,m]),!s||h.length===0?null:e.jsxs("div",{ref:p,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",u),...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:h.map((f,y)=>e.jsxs("button",{type:"button",onClick:()=>{f.onSelect(),c(""),m?.()},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",y===n&&"bg-muted"),children:[f.icon&&e.jsx("span",{className:"shrink-0 mt-0.5",children:f.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:f.label}),f.description&&e.jsx("div",{className:"text-caption text-muted-foreground truncate",children:f.description})]})]},f.id))})]})});kn.displayName="ChatInputCommandMenu";const Tn=i.createContext(void 0),ot=()=>{const t=i.useContext(Tn);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},In=i.forwardRef(({client:t,startSession:s,value:a,onChange:n,onSubmit:o,onCancel:l,disabled:r=!1,isSubmitting:c,submitOnEnter:m=!0,className:u,children:d,...p},g)=>{const h=i.useRef(null),x=i.useCallback(async()=>Promise.resolve(null),[]),f=Go(t??null,s??x),y=$(P=>P.isStreaming),{addToHistory:j,navigatePrevious:v,navigateNext:k,resetNavigation:U}=Xo(),E=t&&s,z=E?f.value:a||"",C=E?f.onChange:n||(()=>{}),A=E?f.onSubmit:o||(async()=>{}),Y=E?f.isSubmitting||y:c||!1,H=i.useCallback(async()=>{const P=z.trim();P&&j(P),await A()},[z,j,A]),[W,K]=i.useState(!1),[D,R]=i.useState(""),[N,_]=i.useState(0),[T,S]=i.useState(0),[M,I]=i.useState(0),V=i.useCallback(()=>{I(P=>P+1)},[]),J=async P=>{P.preventDefault(),z.trim()&&!Y&&!r&&(await H(),setTimeout(()=>{h.current?.focus()},0))},B=P=>{const G=P.target;!(G.tagName==="BUTTON"||G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.closest("button"))&&h.current&&h.current.focus()},q=P=>{const G=P.target;!(G.tagName==="BUTTON"||G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.closest("button"))&&P.key===" "&&(P.preventDefault(),h.current&&h.current.focus())};return i.useEffect(()=>{const P=document.querySelector('textarea[name="chat-input"]');P&&h.current!==P&&(h.current=P)},[]),i.useEffect(()=>{!z&&h.current&&(h.current.style.height="auto",h.current.style.overflowY="hidden")},[z]),e.jsx(Tn.Provider,{value:{value:z,onChange:C,onSubmit:H,onCancel:l,disabled:r,isSubmitting:Y,submitOnEnter:m,showCommandMenu:W,setShowCommandMenu:K,commandMenuQuery:D,setCommandMenuQuery:R,selectedMenuIndex:N,setSelectedMenuIndex:_,menuItemCount:T,setMenuItemCount:S,triggerMenuSelect:V,triggerCounter:M,navigateHistoryPrevious:v,navigateHistoryNext:k,resetHistoryNavigation:U},children:e.jsx("form",{ref:g,onSubmit:J,onClick:B,onKeyDown:q,className:b("relative w-full divide-y rounded-xl border bg-background shadow-md",u),...p,children:d})})});In.displayName="ChatInput.Root";const Rn=i.forwardRef(({asChild:t=!1,className:s,onKeyDown:a,onFilesDropped:n,children:o,...l},r)=>{const{value:c,onChange:m,onSubmit:u,disabled:d,isSubmitting:p,submitOnEnter:g,showCommandMenu:h,setShowCommandMenu:x,setCommandMenuQuery:f,setSelectedMenuIndex:y,menuItemCount:j,triggerMenuSelect:v,navigateHistoryPrevious:k,navigateHistoryNext:U,resetHistoryNavigation:E}=ot(),z=i.useRef(null),[C,A]=i.useState(!1),Y=i.useCallback(T=>{z.current=T,typeof r=="function"?r(T):r&&(r.current=T)},[r]),H=T=>new Promise((S,M)=>{const I=new FileReader;I.readAsDataURL(T),I.onload=()=>{const V=I.result.split(",")[1];S(V||"")},I.onerror=V=>M(V)}),_={ref:Y,name:"chat-input",value:c,onChange:T=>{const S=T.target.value;if(m(S),E(),S.startsWith("/")&&!S.includes(`
7
+ `)){x(!0);const V=S.slice(1);f(V)}else x(!1),f("");const M=z.current;if(!M)return;M.style.height="auto";const I=Math.min(M.scrollHeight,164);M.style.height=`${I}px`,M.scrollHeight>164?M.style.overflowY="auto":M.style.overflowY="hidden"},onKeyDown:T=>{if(h&&j>0){if(T.key==="ArrowDown"){T.preventDefault(),y(S=>(S+1)%j);return}else if(T.key==="ArrowUp"){T.preventDefault(),y(S=>(S-1+j)%j);return}else if(T.key==="Enter"&&!T.shiftKey){T.preventDefault(),v();return}else if(T.key==="Escape"){T.preventDefault(),x(!1),f("");return}}if(!h){const S=z.current,M=S?.selectionStart===0&&S?.selectionEnd===0,I=S?.selectionStart===c.length&&S?.selectionEnd===c.length,V=c.includes(`
8
+ `);if(T.key==="ArrowUp"&&(M||!c||!V)){const J=k(c);if(J!==null){T.preventDefault(),m(J),setTimeout(()=>{z.current&&(z.current.selectionStart=J.length,z.current.selectionEnd=J.length)},0);return}}else if(T.key==="ArrowDown"&&(I||!c||!V)){const J=U();if(J!==null){T.preventDefault(),m(J),setTimeout(()=>{z.current&&(z.current.selectionStart=J.length,z.current.selectionEnd=J.length)},0);return}}}g&&T.key==="Enter"&&!T.shiftKey&&(c.trim()&&!p&&!d?(T.preventDefault(),u()):(p||d)&&T.preventDefault()),a?.(T)},onDrop:async T=>{T.preventDefault(),A(!1);const S=T.dataTransfer.files;if(!S||S.length===0||!n)return;const M=[];for(const I of Array.from(S))if(I.type.startsWith("image/"))try{const V=await H(I);M.push({name:I.name,path:I.name,size:I.size,mimeType:I.type,data:V})}catch(V){console.error("Failed to process dropped file:",I.name,V)}M.length>0&&n(M)},onDragOver:T=>{T.preventDefault(),A(!0)},onDragLeave:T=>{T.preventDefault(),A(!1)},disabled:d,...l};return t&&i.isValidElement(o)?i.cloneElement(o,_):e.jsx("textarea",{..._,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",C&&"ring-2 ring-primary ring-offset-2",s)})});Rn.displayName="ChatInput.Field";const _n=i.forwardRef(({asChild:t=!1,className:s,disabled:a,children:n,...o},l)=>{const{value:r,disabled:c,isSubmitting:m}=ot();if(m)return null;const u=a||c||!r.trim(),d=t?de:ne;return e.jsx(d,{ref:l,type:"submit",disabled:u,variant:t?void 0:"default",size:"icon",className:b(!t&&"gap-1.5 rounded-full",s),...o,children:n})});_n.displayName="ChatInput.Submit";const Mn=i.forwardRef(({asChild:t=!1,className:s,children:a,...n},o)=>{const{onCancel:l,isSubmitting:r}=ot(),c=t?de:ne;return r?e.jsx(c,{ref:o,type:"button",onClick:()=>l?.(),variant:t?void 0:"default",size:"icon",className:b(!t&&"gap-1.5 rounded-full",s),...n,children:a||e.jsx(Ua,{className:"size-4 fill-current"})}):null});Mn.displayName="ChatInput.Stop";const En=i.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 An=i.forwardRef(({asChild:t=!1,className:s,children:a,onClick:n,...o},l)=>{const{value:r,onChange:c,setShowCommandMenu:m,setCommandMenuQuery:u}=ot(),d=g=>{r.startsWith("/")||(c("/"),m(!0),u("")),n?.(g)},p=t?de:ne;return e.jsx(p,{ref:l,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),onClick:d,...o,children:a||e.jsx(za,{className:"size-4"})})});An.displayName="ChatInput.Actions";const Pn=i.forwardRef(({asChild:t=!1,className:s,children:a,onFilesSelected:n,...o},l)=>{const r=i.useRef(null),c=p=>new Promise((g,h)=>{const x=new FileReader;x.readAsDataURL(p),x.onload=()=>{const f=x.result.split(",")[1];g(f||"")},x.onerror=f=>h(f)}),m=async p=>{const g=p.target.files;if(!g||g.length===0)return;const h=[];for(const x of Array.from(g))if(x.type.startsWith("image/"))try{const f=await c(x);h.push({name:x.name,path:x.name,size:x.size,mimeType:x.type,data:f})}catch(f){console.error("Failed to process file:",x.name,f)}h.length>0&&n&&n(h),r.current&&(r.current.value="")},u=p=>{p.preventDefault(),r.current?.click()},d=t?de:ne;return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:r,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:m}),e.jsx(d,{ref:l,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),onClick:u,...o,children:a||e.jsx($a,{className:"size-4"})})]})});Pn.displayName="ChatInput.Attachment";const Dn=i.forwardRef(({asChild:t=!1,className:s,children:a,...n},o)=>{const l=t?de:ne;return e.jsx(l,{ref:o,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),...n,children:a||e.jsx(La,{className:"size-4"})})});Dn.displayName="ChatInput.VoiceInput";const Un=i.forwardRef(({commands:t=[],className:s,onChange:a,...n},o)=>{const{showCommandMenu:l,commandMenuQuery:r,selectedMenuIndex:c,setSelectedMenuIndex:m,setMenuItemCount:u,triggerCounter:d,onChange:p,setShowCommandMenu:g,setCommandMenuQuery:h}=ot();return e.jsx(kn,{ref:o,commands:t,showCommandMenu:l,commandMenuQuery:r,selectedMenuIndex:c,setSelectedMenuIndex:m,setMenuItemCount:u,triggerCounter:d,onChange:p,onClose:()=>{g(!1),h("")},className:s,...n})});Un.displayName="ChatInput.CommandMenu";function di({parameters:t,className:s}){const a=$(c=>c.input.selectedPromptParameters),n=$(c=>c.setSelectedPromptParameters),o=i.useCallback(c=>c.defaultOptionId??c.options[0]?.id??"",[]);i.useEffect(()=>{if(!a||Object.keys(a).length===0){const c={};for(const m of t)c[m.id]=o(m);Object.keys(c).length>0&&n(c)}},[t,a,n,o]);const l=i.useCallback((c,m)=>{const u={...a,[c]:m};n(u)},[a,n]);if(t.length===0)return null;const r=t.map(c=>{const m=a?.[c.id],u=o(c),d=c.options.find(g=>g.id===m);return{param:c,selectedOption:d,isNonDefault:m&&m!==u}}).filter(c=>c.selectedOption);return e.jsx("div",{className:b("flex items-center gap-1",s),children:r.map(({param:c,selectedOption:m,isNonDefault:u})=>e.jsxs(st,{children:[e.jsx(nt,{asChild:!0,children:e.jsxs("button",{type:"button",className:b("inline-flex h-10 items-center gap-1.5 rounded-full px-3","text-sm font-medium transition-colors","focus:outline-none focus-visible:ring-1 focus-visible:ring-ring",u?"bg-accent text-accent-foreground hover:bg-accent/80":"bg-muted/50 text-muted-foreground hover:bg-muted"),children:[e.jsx("span",{className:"truncate max-w-[140px]",children:m?.label}),e.jsx(le,{className:"h-4 w-4 opacity-50"})]})}),e.jsx(Le,{align:"start",className:"min-w-[160px]",children:c.options.map(d=>e.jsx(pe,{onClick:()=>l(c.id,d.id),className:b(a?.[c.id]===d.id&&"bg-accent"),children:d.label},d.id))})]},c.id))})}function ui(t){const[s,a]=i.useState({width:0,height:0});return i.useEffect(()=>{const n=t.current;if(!n)return;const o=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const c=r[0];if(!c)return;const{width:m,height:u}=c.contentRect;a({width:m,height:u})});o.observe(n);const l=n.getBoundingClientRect();return a({width:l.width,height:l.height}),()=>{o.disconnect()}},[t]),s}function mi(){const t=i.useRef(null),s=i.useRef(null),[a,n]=i.useState(!0),o=i.useRef(!0),l=i.useRef(!1),[r,c]=i.useState(!1),[m,u]=i.useState(!1),[d,p]=i.useState(0),[g,h]=i.useState(0),x=i.useRef(-1),f=i.useRef(!1),y=i.useRef(null);i.useEffect(()=>{o.current=a},[a]);const j=i.useCallback(()=>{if(!t.current)return!0;const{scrollTop:D,scrollHeight:R,clientHeight:N}=t.current;return D+N>=R-100},[]),v=i.useCallback(()=>{if(!t.current)return[];const D=t.current.querySelectorAll('[aria-label="user message"]');return Array.from(D)},[]),k=i.useCallback(()=>{const D=t.current;if(!D)return[];const R=D.getBoundingClientRect();return v().map((_,T)=>{const M=_.getBoundingClientRect().bottom<R.top+50,I=_.textContent||"",V=I.slice(0,100)+(I.length>100?"...":"");return{index:T,preview:V,element:_,isAboveFold:M}}).filter(({isAboveFold:_})=>_).map(({index:_,preview:T,element:S})=>({index:_,preview:T,element:S}))},[v]),U=i.useCallback((D,R="smooth")=>{const N=v();if(D<0||D>=N.length)return;const _=N[D];if(_){f.current=!0,y.current&&clearTimeout(y.current),_.scrollIntoView({behavior:R,block:"start"}),x.current=D,p(D);const T=N.length-1-D;h(T),u(T>0),y.current=setTimeout(()=>{f.current=!1},500)}},[v]),E=i.useCallback(()=>{const D=t.current;if(!D)return[];const R=D.getBoundingClientRect();return v().filter(_=>_.getBoundingClientRect().bottom<R.top+50)},[v]);i.useCallback(()=>E().length>0,[E]);const z=i.useCallback(()=>{const D=t.current;if(!D)return-1;const R=D.getBoundingClientRect(),N=v();for(let _=0;_<N.length;_++){const T=N[_]?.getBoundingClientRect();if(T&&(T.top>=R.top-50&&T.top<R.top+150||T.top<R.top&&T.bottom>R.top+50))return _}for(let _=N.length-1;_>=0;_--){const T=N[_]?.getBoundingClientRect();if(T&&T.bottom<R.top+50)return _}return-1},[v]);i.useCallback(()=>{const D=v(),R=x.current!==-1?x.current:z();return R===-1?!1:R<D.length-1},[v,z]);const C=i.useCallback((D="smooth")=>{t.current&&(t.current.scrollTo({top:t.current.scrollHeight,behavior:D}),x.current=-1)},[]),A=i.useCallback((D="smooth")=>{const R=t.current;if(!R)return;const N=v();if(N.length===0)return;const _=R.getBoundingClientRect(),T=[];for(let M=0;M<N.length;M++){const I=N[M]?.getBoundingClientRect();I&&I.bottom<_.top+50&&T.push(M)}if(T.length===0)return;let S;if(x.current===-1){const M=T[T.length-1];if(M===void 0)return;S=M}else{const M=T.filter(I=>I<x.current);if(M.length>0){const I=M[M.length-1];if(I===void 0)return;S=I}else{const I=T[0];if(I===void 0)return;S=I}}if(S>=0&&S<N.length){const M=N[S];if(M){f.current=!0,y.current&&clearTimeout(y.current),M.scrollIntoView({behavior:D,block:"start"}),x.current=S,p(S);const I=N.length-1-S;h(I),u(I>0),y.current=setTimeout(()=>{f.current=!1},500)}}},[v]),Y=i.useCallback((D="smooth")=>{if(!t.current)return;const N=v();if(N.length!==0&&x.current!==-1){const _=x.current+1;if(_<N.length){const T=N[_];if(T){f.current=!0,y.current&&clearTimeout(y.current),T.scrollIntoView({behavior:D,block:"start"}),x.current=_,p(_);const S=N.length-1-_;h(S),u(S>0),y.current=setTimeout(()=>{f.current=!1},500)}}}},[v]);i.useCallback(()=>x.current>0?!0:E().length>0,[E]),i.useCallback(()=>{const D=v();return x.current===-1?!1:x.current<D.length-1},[v]);const H=i.useCallback(()=>{x.current=-1},[]);i.useEffect(()=>{const D=t.current;if(!D)return;let R;const N=()=>{l.current=!0,clearTimeout(R);const _=j();n(_),o.current=_;const T=E(),S=T.length>0;if(c(S),!f.current){const M=z();M!==-1&&(x.current=M);const I=v();p(T.length);const V=x.current!==-1?x.current:M,J=V!==-1&&V<I.length-1?I.length-1-V:0;h(J),u(J>0)}R=setTimeout(()=>{l.current=!1},150)};return D.addEventListener("scroll",N,{passive:!0}),()=>{D.removeEventListener("scroll",N),clearTimeout(R)}},[j,z,v,E]),i.useEffect(()=>{const D=t.current;if(!D)return;const R=()=>{o.current&&!l.current&&requestAnimationFrame(()=>{D.scrollTo({top:D.scrollHeight,behavior:"instant"}),n(!0),o.current=!0})},N=new MutationObserver(R);N.observe(D,{childList:!0,subtree:!0,characterData:!0});const _=new ResizeObserver(R);return _.observe(D),Array.from(D.children).forEach(T=>{_.observe(T)}),()=>{N.disconnect(),_.disconnect()}},[]);function W(){n(!0),o.current=!0}function K(){n(!1),o.current=!1}return{containerRef:t,endRef:s,isAtBottom:a,scrollToBottom:C,onViewportEnter:W,onViewportLeave:K,isUserMessageAboveFold:r,hasMoreUserMessagesBelow:m,userMessagesAboveCount:d,userMessagesBelowCount:g,scrollToPreviousUserMessage:A,scrollToNextUserMessage:Y,scrollToUserMessageByIndex:U,getUserMessagePreviews:k,resetUserMessageCycle:H}}const pi=({...t})=>e.jsx(xa,{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}),Vt=i.createContext(void 0),Te=()=>{const t=i.useContext(Vt);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},zn=i.forwardRef(({defaultSidebarOpen:t=!1,defaultPanelSize:s="hidden",defaultActiveTab:a="todo",className:n,children:o,...l},r)=>{const[c,m]=i.useState(t),[u,d]=i.useState(s),[p,g]=i.useState(a),h=i.useMemo(()=>u!=="hidden",[u]),x=i.useRef(!1),[f,y]=i.useState(!1),[j,v]=i.useState(rn),[k,U]=i.useState(0),E=i.useCallback(()=>{x.current||(x.current=!0,d(C=>C==="hidden"?"large":"hidden"),setTimeout(()=>{x.current=!1},350))},[]),z=i.useCallback(C=>{d(C?"large":"hidden")},[]);return i.useEffect(()=>{const C=A=>{A.key.toLowerCase()==="b"&&(A.metaKey||A.ctrlKey)&&!A.shiftKey&&(A.preventDefault(),E())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[E]),e.jsx(Vt.Provider,{value:{sidebarOpen:c,setSidebarOpen:m,panelSize:u,setPanelSize:C=>{d(C),z(C!=="hidden")},activeTab:p,setActiveTab:g,panelOpen:h,setPanelOpen:z,togglePanel:E,isDraggingAside:f,setIsDraggingAside:y,asideWidth:j,setAsideWidth:v,mainWidth:k,setMainWidth:U},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),...l,children:o})})});zn.displayName="ChatLayout.Root";const fi=i.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}));fi.displayName="ChatLayout.Header";const $n=i.forwardRef(({className:t,children:s},a)=>{const{panelOpen:n,isDraggingAside:o,asideWidth:l,setMainWidth:r}=Te(),c=i.useRef(null),{width:m}=ui(c);return i.useEffect(()=>{r(m)},[m,r]),i.useImperativeHandle(a,()=>c.current),e.jsx("div",{ref:c,className:b("flex flex-1 flex-col overflow-hidden h-full min-w-0",!o&&"transition-[padding] duration-250",t),style:{paddingRight:n?l:0},children:s})});$n.displayName="ChatLayout.Main";const Ln=i.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(pi,{})]}));Ln.displayName="ChatLayout.Body";const On=i.forwardRef(({className:t,children:s,onScrollChange:a,showScrollToBottom:n=!0,initialScrollToBottom:o=!0,...l},r)=>{const{mainWidth:c}=Te(),{containerRef:m,endRef:u,isAtBottom:d,scrollToBottom:p,userMessagesAboveCount:g,scrollToUserMessageByIndex:h}=mi(),x=i.useMemo(()=>({hidden:{opacity:0,x:-8},visible:{opacity:1,x:0,transition:{duration:.2,ease:[.4,0,.2,1]}},exit:{opacity:0,x:-8,transition:{duration:.15}}}),[]),f=i.useMemo(()=>({hidden:{opacity:0,x:-12,scale:.95,transition:{duration:.15}},visible:{opacity:1,x:0,scale:1,transition:{duration:.15,ease:[.4,0,.2,1]}},exit:{opacity:0,x:-8,scale:.98,transition:{duration:.15}}}),[]),[y,j]=i.useState(!1),[v,k]=i.useState([]),[U,E]=i.useState(null),[z,C]=i.useState(0),A=i.useRef(null),Y=i.useRef(null),H=i.useRef(null),W=i.useRef(0),K=i.useCallback(()=>{const B=m.current;if(!B)return[];const q=B.querySelectorAll('[aria-label="user message"]');return Array.from(q).map((P,G)=>{const se=P.textContent||"",je=se.slice(0,100)+(se.length>100?"...":"");return{index:G,preview:je}})},[m]);i.useEffect(()=>{const B=m.current;if(!B)return;const q=()=>{const G=K();k(G)};q();const P=new MutationObserver(q);return P.observe(B,{childList:!0,subtree:!0}),()=>{P.disconnect()}},[m,K]),i.useEffect(()=>()=>{A.current&&clearTimeout(A.current),Y.current&&clearTimeout(Y.current),H.current!==null&&cancelAnimationFrame(H.current)},[]);const D=c>vr+jr,R=v.length>1&&D,N=i.useCallback(B=>{const P=B.currentTarget.getBoundingClientRect(),G=B.clientY-P.top;W.current=G,H.current===null&&(H.current=requestAnimationFrame(()=>{C(W.current),H.current=null}))},[]),_=i.useCallback(()=>{Y.current&&(clearTimeout(Y.current),Y.current=null),A.current=setTimeout(()=>{j(!0)},1500)},[]),T=i.useCallback(()=>{A.current&&(clearTimeout(A.current),A.current=null),Y.current=setTimeout(()=>{j(!1),E(null)},500)},[]),S=i.useCallback(B=>{E(B)},[]),M=i.useCallback(()=>{E(null)},[]),I=i.useCallback(B=>{h(B,"smooth")},[h]),V=i.useRef(!1);i.useImperativeHandle(r,()=>m.current),i.useEffect(()=>{a?.(d)},[d,a]),i.useEffect(()=>{if(!o)return;const B=m.current;if(B&&!V.current){const q=setTimeout(()=>{B.scrollTop=B.scrollHeight,V.current=!0},100);return()=>clearTimeout(q)}},[o,m]);const J=!d&&n;return e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsxs("div",{ref:m,className:b("h-full overflow-y-auto flex flex-col",t),...l,children:[e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s}),e.jsx("div",{ref:u,className:"shrink-0"})]}),e.jsx(Xe,{mode:"wait",children:R&&e.jsxs(ye.nav,{variants:x,initial:"hidden",animate:"visible",exit:"exit",className:"absolute p-4 left-0 top-1/2 -translate-y-1/2 z-10",onMouseEnter:_,onMouseMove:N,onMouseLeave:T,"aria-label":"User message navigation",children:[e.jsx("div",{className:"flex flex-col",children:v.map(({index:B})=>{const q=B===g,P=U===B;return e.jsx("button",{type:"button",onClick:()=>I(B),onMouseEnter:()=>S(B),onMouseLeave:M,className:"py-2 px-1 group","aria-label":`Go to user message ${B+1}`,children:e.jsx("div",{className:b("w-4 h-[2px] rounded-full bg-primary transition-opacity duration-200",q?"opacity-80":"opacity-10",P&&"opacity-60",!P&&"group-hover:opacity-60")})},B)})}),e.jsx(Xe,{children:y&&v.length>0&&U!==null&&(()=>{const P=40*Math.min(3,v.length)+10,G=40,se=40*U,je=G-se,kt=0,Tt=P-40*v.length-10,It=Math.max(Tt,Math.min(kt,je));return e.jsx(ye.div,{variants:f,initial:"hidden",animate:"visible",exit:"exit",className:b("absolute left-12 pointer-events-none","w-72 overflow-hidden","bg-card border border-border rounded-lg shadow-xl"),style:{top:`${z}px`,y:"-50%",height:`${P}px`,willChange:"transform"},children:e.jsx("div",{className:"p-1",style:{transform:`translateY(${It}px)`,transition:"transform 0.15s cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:v.map(({index:ee,preview:Oe})=>{const xe=ee===U;return e.jsx("div",{className:b("w-full text-left px-3 py-2 rounded-md","text-sm text-muted-foreground","transition-colors duration-100","truncate",xe&&"bg-accent text-foreground"),style:{height:"40px"},children:Oe},ee)})})},"hover-menu")})()})]},"toc")}),J&&e.jsx("button",{type:"button",onClick:()=>p("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(Oa,{className:"size-4"})})]})});On.displayName="ChatLayout.Messages";const Fn=i.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})}));Fn.displayName="ChatLayout.Footer";const gi=i.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});gi.displayName="ChatLayout.Sidebar";const Bn=i.forwardRef(({breakpoint:t="md",onClose:s,className:a,children:n},o)=>{const{panelSize:l,togglePanel:r,setIsDraggingAside:c,setAsideWidth:m}=Te(),[u,d]=i.useState(rn),[p,g]=i.useState(u),[h,x]=i.useState(!1),f=i.useRef(0),y=i.useRef(u),j=l!=="hidden",[v,k]=i.useState(!1);i.useEffect(()=>{if(!j){k(!1);return}const H=requestAnimationFrame(()=>{k(!0)});return()=>cancelAnimationFrame(H)},[j]);const U=cn();ln(U&&j),i.useEffect(()=>{g(u)},[u]),i.useEffect(()=>{j&&m(h?p:u)},[j,h,p,u,m]);const E=i.useCallback(H=>{H.preventDefault(),x(!0),c(!0),f.current=H.clientX,y.current=u,H.target.setPointerCapture(H.pointerId)},[u,c]),z=i.useCallback(H=>{if(!h)return;const W=H.clientX-f.current,K=Math.max(cs,Math.min(ds,y.current-W));g(K)},[h]),C=i.useCallback(H=>{if(!h)return;const W=H.clientX-f.current,K=Math.max(cs,Math.min(ds,y.current-W));d(K),g(K),x(!1),c(!1),H.target.releasePointerCapture(H.pointerId)},[h,c]),A=j&&U,Y=j&&!U;return e.jsxs(Xe,{initial:!1,children:[A&&e.jsx(ye.aside,{variants:Tr,initial:"initial",animate:"animate",exit:"exit",transition:_r,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(ye.div,{className:"flex flex-col h-full",variants:Ir,initial:"initial",animate:"animate",transition:Rr,children:[e.jsx("div",{className:"flex justify-end px-4 pt-3 shrink-0",children:e.jsx(Ce,{onClick:()=>{s?.(),r()},"aria-label":"Close panel",children:e.jsx(vt,{className:"size-4"})})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:n})]})},"aside-mobile"),Y&&e.jsx("aside",{ref:o,style:{width:h?p:v?u:0,transition:h?"none":"width 0.25s cubic-bezier(0.25, 0.1, 0.25, 1)"},className:b("fixed inset-y-0 right-0 z-40","hidden h-full border-l border-border bg-card overflow-hidden",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("div",{className:"flex flex-col h-full",children:[e.jsx("div",{onPointerDown:E,onPointerMove:z,onPointerUp:C,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",h&&"bg-primary/10")}),e.jsx("div",{className:b("h-full overflow-y-auto",h?"w-full":void 0),style:h?void 0:{width:`${u}px`},children:n})]})},"aside-desktop")]})});Bn.displayName="ChatLayout.Aside";class hi{constructor(s){this.connection=s}async getRootItems(){try{const s=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=/home/user`);if(!s.ok)return console.error("Failed to fetch sandbox files:",await s.text()),[];const{files:a}=await s.json();return a.map(this.toFileSystemItem)}catch(s){return console.error("Error fetching sandbox root items:",s),[]}}async getItemChildren(s){try{const a=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=${encodeURIComponent(s)}`);if(!a.ok)return console.error("Failed to fetch sandbox directory:",await a.text()),[];const{files:n}=await a.json();return n.map(this.toFileSystemItem)}catch(a){return console.error("Error fetching sandbox item children:",a),[]}}async getItemDetails(s){try{const a=s.substring(0,s.lastIndexOf("/")),n=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=${encodeURIComponent(a||"/")}`);if(!n.ok)throw new Error(`Failed to fetch file details: ${await n.text()}`);const{files:o}=await n.json(),l=o.find(r=>r.path===s);if(!l)throw new Error(`File not found: ${s}`);return this.toFileSystemItem(l)}catch(a){throw console.error("Error fetching sandbox item details:",a),a}}toFileSystemItem=s=>{const a=s.type==="file"&&s.name.includes(".")?s.name.split(".").pop():void 0;return{id:s.path,name:s.name,type:s.type==="dir"?"folder":"file",path:s.path,size:s.size,lastModified:new Date(s.lastModified),...a!==void 0&&{extension:a}}}}function Hn({item:t,level:s=0,onSelect:a,selectedId:n,isDropTarget:o=!1,onDownload:l}){const[r,c]=i.useState(!0),m=n===t.id,u=()=>{t.type==="folder"&&c(!r)},d=()=>{a?.(t),t.type==="folder"&&u()},p=h=>{h.key==="Enter"||h.key===" "?(h.preventDefault(),d()):h.key==="ArrowRight"&&t.type==="folder"&&!r?(h.preventDefault(),c(!0)):h.key==="ArrowLeft"&&t.type==="folder"&&r&&(h.preventDefault(),c(!1))},g=()=>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"?r:void 0,className:b("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",g(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",m&&"bg-accent",o&&["bg-accent","border border-dashed border-border-dark"]),onClick:d,onKeyDown:p,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.type==="folder"?r?e.jsx(Fa,{className:"size-4"}):e.jsx(Ba,{className:"size-4"}):e.jsx(Ha,{className:"size-4"})}),e.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:t.name}),e.jsxs(st,{children:[e.jsx(nt,{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:h=>{h.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(Wa,{className:"size-4"})})}),e.jsx(Le,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:h=>h.stopPropagation(),children:l&&e.jsx(pe,{onClick:h=>{h.stopPropagation(),l(t)},children:"Download"})})]}),t.type==="folder"&&e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-muted-foreground",children:e.jsx(le,{className:b("size-4 transition-transform",!r&&"-rotate-90")})})]}),t.type==="folder"&&r&&t.children&&e.jsx("div",{className:"flex flex-col",children:t.children.map(h=>e.jsx(Hn,{item:h,level:s+1,...a&&{onSelect:a},...n&&{selectedId:n},...l&&{onDownload:l}},h.id))})]})}const xi=new ur;function bi({className:t,provider:s=xi,onItemSelect:a,onDownload:n}){const[o,l]=i.useState([]),[r,c]=i.useState(),[m,u]=i.useState(!0),[d,p]=i.useState(),[g,h]=i.useState(0);i.useEffect(()=>{const f=setInterval(()=>{h(y=>y+1)},6e4);return()=>clearInterval(f)},[]),i.useEffect(()=>{(async()=>{try{u(!0);const y=await s.getRootItems();l(y),p(void 0)}catch(y){p(y instanceof Error?y.message:"Failed to load items")}finally{u(!1)}})()},[s]);const x=f=>{c(f.id),a?.(f)};return m?e.jsx("div",{className:b("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):d?e.jsx("div",{className:b("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",d]})}):o.length===0?e.jsxs("div",{className:b("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",t),children:[e.jsx($e,{className:"size-8 text-muted-foreground opacity-50 mb-3"}),e.jsx("p",{className:"text-paragraph text-muted-foreground",children:"No files yet"}),e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 mt-1",children:"Files will appear when your agent writes to the sandbox."})]}):e.jsx("div",{className:b("flex flex-col",t),children:o.map(f=>e.jsx(Hn,{item:f,onSelect:x,...r&&{selectedId:r},...n&&{onDownload:n}},f.id))})}const Wn=i.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 truncate",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 break-all",children:t.snippet})]})]}));Wn.displayName="SourceListItem";const Vn=i.forwardRef(({todo:t,className:s,...a},n)=>{const o=t.status==="completed";return e.jsxs("div",{ref:n,className:b("group flex items-start 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 flex items-center justify-center w-4 h-5 mt-0.5",children:t.status==="completed"?e.jsx(wt,{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(yt,{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})]})});Vn.displayName="TodoListItem";function yi(){return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",children:[e.jsx(jt,{className:"size-8 text-muted-foreground opacity-50 mb-3"}),e.jsx("p",{className:"text-paragraph text-muted-foreground",children:"To-do list is empty"}),e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 mt-1",children:"Your agent will create tasks as it works through requests."})]})}const qt=i.forwardRef(({client:t,todos:s,className:a,...n},o)=>{const l=s||[];return l.length===0?e.jsx("div",{ref:o,className:b("h-full",a),...n,children:e.jsx(yi,{})}):e.jsx("div",{ref:o,className:b("space-y-2 overflow-y-auto",a),...n,children:l.map(r=>e.jsx(Vn,{todo:r},r.id))})});qt.displayName="TodoList";const Kt=i.forwardRef(({todos:t=[],className:s,...a},n)=>e.jsx("div",{ref:n,className:b("h-full",s),...a,children:e.jsx(qt,{todos:t,className:"h-full"})}));Kt.displayName="TodoTabContent";const Yt=i.forwardRef(({files:t=[],provider:s,sessionId:a,agentApiUrl:n,client:o,onFileSelect:l,className:r,...c},m)=>{const[u,d]=i.useState(0),p=i.useRef(void 0),g=i.useCallback(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{d(f=>f+1)},300)},[]);i.useEffect(()=>!a||!o?void 0:o.onFileSystemChange(a,y=>{console.log("Files changed:",y),g()}),[a,o,g]);const h=i.useMemo(()=>{if(s)return s;if(a&&n)return new hi({sessionId:a,apiUrl:n})},[s,a,n]),x=i.useCallback(async f=>{if(f.type==="folder"){console.warn("Cannot download folders");return}if(!a||!n){console.error("Cannot download: missing sessionId or agentApiUrl");return}try{const y=`${n}/sandbox/download?sessionId=${encodeURIComponent(a)}&path=${encodeURIComponent(f.path||f.name)}`,j=document.createElement("a");j.href=y,j.download=f.name,document.body.appendChild(j),j.click(),document.body.removeChild(j)}catch(y){console.error("Failed to download file:",y)}},[a,n]);return e.jsx("div",{ref:m,className:b("h-full",r),...c,children:e.jsx(bi,{...h&&{provider:h},onItemSelect:f=>{f.type==="file"&&l&&l(f.path||f.name)},onDownload:x,className:"h-full"},u)})});Yt.displayName="FilesTabContent";const Gt=i.forwardRef(({sources:t=[],highlightedSourceId:s,className:a,...n},o)=>t.length===0?e.jsxs("div",{ref:o,className:b("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",a),...n,children:[e.jsx(Ws,{className:"size-8 text-muted-foreground opacity-50 mb-3"}),e.jsx("p",{className:"text-paragraph text-muted-foreground",children:"No sources yet"}),e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 mt-1",children:"Sources will appear when your agent searches the web or fetches data."})]}):e.jsx("div",{ref:o,className:b("space-y-2",a),...n,children:t.map(l=>e.jsx(Wn,{source:l,isSelected:l.id===s},l.id))}));Gt.displayName="SourcesTabContent";const vi=i.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]})]})]}));vi.displayName="DatabaseTabContent";const wi=({tool:t})=>{const s=t.children&&t.children.length>0;return 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:t.prettyName||t.name}),t.description&&!s&&e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-1",children:t.description}),s&&e.jsxs("div",{className:"text-caption text-muted-foreground mt-1",children:["Built-in tools:"," ",t.children?.map(a=>a.prettyName||a.name).join(", ")]})]})},qn=i.forwardRef(({tools:t=[],mcps:s=[],subagents:a=[],className:n,...o},l)=>e.jsxs("div",{ref:l,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.jsx(wi,{tool:r},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"})]})]}));qn.displayName="SettingsTabContent";const Kn=Ta,Ke=i.forwardRef(({className:t,...s},a)=>e.jsx(Rs,{ref:a,className:b("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));Ke.displayName=Rs.displayName;const Ye=i.forwardRef(({className:t,...s},a)=>e.jsx(_s,{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}));Ye.displayName=_s.displayName;const ve=i.forwardRef(({className:t,...s},a)=>e.jsx(Ms,{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}));ve.displayName=Ms.displayName;const ji=i.forwardRef(({client:t,todos:s,variant:a="animated",showIcons:n=!1,visibleTabs:o=["todo","files","database"],className:l,...r},c)=>{const m=s||[],[u,d]=i.useState(o[0]||"todo"),p=i.useRef(null),g=i.useRef(null);i.useEffect(()=>{const y=setTimeout(()=>{const j=p.current;if(u&&j){const v=g.current;if(v){const k=j.getBoundingClientRect(),U=v.getBoundingClientRect(),E=U.left-k.left,z=U.width,C=E/k.width*100,A=100-(E+z)/k.width*100;j.style.clipPath=`inset(0 ${A.toFixed(2)}% 0 ${C.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(y)},[u]);const x=[{id:"todo",label:a==="pills"?"To-do":"To-Do List",icon:jt},{id:"files",label:"Files",icon:$e},{id:"database",label:"Database",icon:Vs},{id:"sources",label:"Sources",icon:qs}].filter(f=>o.includes(f.id));return e.jsx("div",{ref:c,className:b("select-none",l),...r,children:e.jsxs(Kn,{value:u,onValueChange:d,className:"w-full",children:[a==="pills"?e.jsx(Ke,{className:b("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:x.map(f=>{const y=f.icon;return e.jsxs(Ye,{value:f.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&&y&&e.jsx(y,{className:"size-4"}),f.label]},f.id)})}):e.jsxs("div",{className:"relative mb-4 border-border",children:[e.jsx(Ke,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:x.map(f=>e.jsx(Ye,{value:f.id,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:f.label},f.id))}),e.jsx("div",{ref:p,className:"absolute top-0 left-0 w-full overflow-hidden z-10 pointer-events-none",style:{clipPath:"inset(0 100% 0 0% round 999px)",transition:"clip-path 0.25s ease-out"},children:e.jsx(Ke,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:x.map(f=>e.jsx(Ye,{value:f.id,ref:u===f.id?g:null,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:f.label},f.id))})})]}),e.jsx(ve,{value:"todo",className:a==="pills"?"mt-0":"",children:a==="pills"?e.jsx(Kt,{todos:m}):e.jsx(qt,{todos:m})}),e.jsx(ve,{value:"files",className:a==="pills"?"mt-0":"",children:e.jsx(Yt,{})}),e.jsx(ve,{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(ve,{value:"sources",className:a==="pills"?"mt-0":"",children:e.jsx(Gt,{})})]})})});ji.displayName="ChatSecondaryPanel";const Ni=i.forwardRef(({className:t,children:s,...a},n)=>e.jsx("div",{ref:n,className:b("flex h-full flex-col",t),...a,children:s}));Ni.displayName="ChatSidebar.Root";const Si=i.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}));Si.displayName="ChatSidebar.Header";const Ci=i.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}));Ci.displayName="ChatSidebar.Content";const ki=i.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}));ki.displayName="ChatSidebar.Footer";const Ti=i.forwardRef(({children:t,className:s,...a},n)=>{const[o,l]=i.useState(t),[r,c]=i.useState(!1),m=i.useRef(t),u=i.useRef(!0);return i.useEffect(()=>{if(u.current){u.current=!1,m.current=t;return}if(m.current===t)return;c(!0);const d=setTimeout(()=>{l(t),m.current=t,requestAnimationFrame(()=>{c(!1)})},150);return()=>{clearTimeout(d)}},[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})});Ti.displayName="ChatStatus";let fs=!1,Ge=null;const Ze=[];let Qe=null;const Be={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),debug:console.debug.bind(console)},Ie=ue("gui-console");function He(t){return t.map(s=>{if(typeof s=="string")return s;if(s instanceof Error)return`${s.name}: ${s.message}`;try{return JSON.stringify(s)}catch{return String(s)}}).join(" ")}function Ii(t){if(Ze.push(t),t.level==="error"||t.level==="fatal"){gs();return}Qe||(Qe=setTimeout(()=>{Qe=null,gs()},500))}async function gs(){if(Ze.length===0||!Ge)return;const t=Ze.splice(0);try{await fetch(`${Ge}/logs/browser`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({logs:t})})}catch{}}function Ri(t){fs||(fs=!0,Ge=t,console.log=(...s)=>{Be.log(...s),Ie.info(He(s))},console.info=(...s)=>{Be.info(...s),Ie.info(He(s))},console.warn=(...s)=>{Be.warn(...s),Ie.warn(He(s))},console.error=(...s)=>{Be.error(...s),Ie.error(He(s))},console.debug=(...s)=>{Be.debug(...s),Ie.debug(He(s))},window.onerror=(s,a,n,o,l)=>(Ie.error(String(s),{source:a,line:n,col:o,stack:l?.stack}),!1),window.onunhandledrejection=s=>{const a=s.reason instanceof Error?`${s.reason.name}: ${s.reason.message}`:String(s.reason);Ie.error(`Unhandled rejection: ${a}`,{stack:s.reason?.stack})},fo(s=>{s.service==="gui-console"&&Ii(s)}),window.addEventListener("beforeunload",()=>{Qe&&clearTimeout(Qe),Ze.length>0&&Ge&&navigator.sendBeacon(`${Ge}/logs/browser`,JSON.stringify({logs:Ze}))}))}const _i=500;function Mi(t){const s=$(o=>o.isStreaming),a=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{t&&!s&&(document.title=t)},[t,s]),i.useEffect(()=>{if(!t)return;const o=()=>{const l=".".repeat(n.current);document.title=`${t}${l}`,n.current=(n.current+1)%4};if(s)return n.current=0,o(),a.current=setInterval(o,_i),()=>{a.current&&(clearInterval(a.current),a.current=null),document.title=t}},[s,t])}const be=ue("gui");function Ei({children:t}){const{setPanelSize:s,setActiveTab:a,panelSize:n,activeTab:o}=Te(),l=()=>{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:l,openSettings:r})})}function Ai({client:t,startSession:s,placeholder:a,commandMenuItems:n,onCancel:o,promptParameters:l}){const r=$(d=>d.input.attachedFiles),c=$(d=>d.addFileAttachment),m=$(d=>d.removeFileAttachment),u=d=>{for(const p of d)c(p)};return e.jsxs(In,{client:t,startSession:s,onCancel:o,children:[e.jsx(Un,{commands:n}),r.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border-b border-border",children:r.map((d,p)=>e.jsxs("div",{className:"relative group rounded-md overflow-hidden border border-border",children:[e.jsx("img",{src:`data:${d.mimeType};base64,${d.data}`,alt:d.name,className:"h-20 w-20 object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(p),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(vt,{className:"size-3"})})]},`attached-${d.name}-${d.data.slice(0,20)}`))}),e.jsx(Rn,{placeholder:a,autoFocus:!0,onFilesDropped:u}),e.jsxs(En,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(An,{}),e.jsx(Pn,{onFilesSelected:u}),l&&l.length>0&&e.jsx(di,{parameters:l})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Dn,{}),e.jsx(Mn,{}),e.jsx(_n,{children:e.jsx(qa,{className:"size-4"})})]})]})]})}function Pi({todos:t,sources:s,tools:a,mcps:n,subagents:o,sessionId:l,agentApiUrl:r,client:c}){const{activeTab:m,setActiveTab:u}=Te();return e.jsxs(Kn,{value:m,onValueChange:d=>u(d),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","sticky top-0 z-10 shrink-0"),children:e.jsx(aa,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(ve,{value:"todo",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(Kt,{todos:t})}),e.jsx(ve,{value:"files",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(Yt,{sessionId:l,agentApiUrl:r,client:c})}),e.jsx(ve,{value:"sources",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(Gt,{sources:s})}),e.jsx(ve,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(qn,{tools:a??[],mcps:n??[],subagents:o??[]})})]})}function Di({agentName:t,showHeader:s,sessionId:a,debuggerUrl:n}){const{togglePanel:o,panelOpen:l}=Te(),r=n?a?`${n}/sessions/${a}`:n:null;return e.jsx(Cn,{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(El,{}),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(Gn,{}),n&&e.jsx(fe,{children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx(Ce,{"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(Zt,{className:"size-4 text-muted-foreground"})}):e.jsx(Zt,{className:"size-4 text-muted-foreground"})})}),e.jsx(ce,{children:e.jsx("p",{children:a?"View session in debugger":"Open debugger"})})]})}),e.jsx(Ce,{"aria-label":"Toggle panel",onClick:o,"data-state":l?"open":"closed",children:e.jsx(Va,{className:"size-4 text-muted-foreground"})})]})]})})}function Ui({client:t,initialSessionId:s,error:a,debuggerUrl:n}){const{connectionStatus:o,connect:l,sessionId:r,startSession:c}=Qo(t,s),{messages:m,sendMessage:u,editAndResend:d,cancel:p}=sn(t,c);Zo(t);const g=$(q=>q.error),[h,x]=i.useState(void 0),[f,y]=i.useState(void 0),[j,v]=i.useState(void 0),[k,U]=i.useState([]),[E,z]=i.useState([]),[C,A]=i.useState([]),[Y,H]=i.useState([]),[W,K]=i.useState("Type a message or / for commands..."),[D,R]=i.useState(!1),[N,_]=i.useState(null),T=$(Yo);$(q=>q.latestContextSize);const{resolvedTheme:S,setTheme:M}=Wt(),I=i.useMemo(()=>{const q=[];for(const P of m)if(P.sources)for(const G of P.sources)q.push({id:G.id,title:G.title,url:G.url,snippet:G.snippet||"",sourceName:G.sourceName||"",favicon:G.favicon||""});return q},[m]);Mi(h),i.useEffect(()=>{if(t){const q=t.getBaseUrl();q&&Ri(q)}},[t]),i.useEffect(()=>{be.debug("Connection status changed",{status:o}),o==="error"&&g&&be.error("Connection error occurred",{error:g})},[o,g]),i.useEffect(()=>{if(t&&o==="connected"){const q=t.getCurrentSession();q?.metadata?.agentName&&x(q.metadata.agentName);const P=t.getAgentInfo();P.displayName?x(P.displayName):P.name&&x(P.name),y(P.description||"Start a conversation below to begin working with this agent."),P.suggestedPrompts&&P.suggestedPrompts.length>0?v(P.suggestedPrompts):v([]),P.tools&&P.tools.length>0&&(U(P.tools),be.info("Agent tools loaded",{tools:P.tools})),P.mcps&&P.mcps.length>0&&(z(P.mcps),be.info("Agent MCPs loaded",{mcps:P.mcps})),P.subagents&&P.subagents.length>0&&(A(P.subagents),be.info("Agent subagents loaded",{subagents:P.subagents})),P.promptParameters&&P.promptParameters.length>0&&(H(P.promptParameters),be.info("Agent prompt parameters loaded",{promptParameters:P.promptParameters})),P.uiConfig?.hideTopBar&&R(!0)}},[t,o]);const V=q=>{K(q)},J=()=>{K("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 B=[{id:"dark-mode",label:S==="dark"?"Light Mode":"Dark Mode",description:`Switch to ${S==="dark"?"light":"dark"} theme`,icon:S==="dark"?e.jsx(Bs,{className:"h-4 w-4"}):e.jsx(Hs,{className:"h-4 w-4"}),category:"action",onSelect:()=>{M(S==="dark"?"light":"dark"),be.info("User toggled theme",{newTheme:S==="dark"?"light":"dark"})}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx($t,{className:"h-4 w-4"}),category:"action",onSelect:()=>{be.info("User opened settings")}}];return e.jsxs(mn,{defaultOpen:!1,children:[e.jsx(ti,{client:t,currentSessionId:r}),e.jsx(fn,{children:e.jsxs(zn,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsxs($n,{children:[!D&&e.jsx(Di,{agentName:h,showHeader:m.length>0,sessionId:r,...n&&{debuggerUrl:n}}),o==="error"&&g&&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:g})]}),e.jsx("button",{type:"button",onClick:l,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(On,{children:m.length===0?h!==void 0?e.jsx(Ei,{children:({openFiles:q,openSettings:P})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Sn,{title:h,description:f??"",suggestedPrompts:j??[],onPromptClick:G=>{const se=$.getState().input.selectedPromptParameters;u(G,void 0,se&&Object.keys(se).length>0?se:void 0),K("Type a message or / for commands..."),be.info("Prompt clicked",{prompt:G})},onPromptHover:V,onPromptLeave:J,onOpenFiles:q,onOpenSettings:P,toolsAndMcpsCount:k.length+E.length+C.length})})}):null:e.jsx("div",{className:"flex flex-col px-4",children:m.map((q,P)=>{const G=P===0,se=G?null:m[P-1];let je="mt-2";G?je=q.role==="assistant"?"mt-8":"mt-2":q.role==="user"?je=(se?.role==="user","mt-4"):q.role==="assistant"&&(je=se?.role==="assistant"?"mt-2":"mt-6");const kt=m.some(ee=>ee.isStreaming),Tt=q.role==="user"?m.slice(0,P+1).filter(ee=>ee.role==="user").length-1:-1,It=N!==null&&P>N;return e.jsx(Jn,{message:q,className:b(je,"group",It&&"opacity-50"),isLastMessage:P===m.length-1,children:e.jsx("div",{className:"flex flex-col w-full",children:q.role==="user"?e.jsx(Vi,{message:q,messageIndex:Tt,isStreaming:kt,onEditAndResend:d,sticky:!0,onEditingChange:ee=>{_(ee?P:null)}}):e.jsxs(e.Fragment,{children:[e.jsx(na,{message:q,thinkingDisplayStyle:"collapsible"}),e.jsx(Xi,{message:q,isStreaming:q.isStreaming,onSendMessage:u,isLastAssistantMessage:P===m.findLastIndex(ee=>ee.role==="assistant"),onRedo:()=>{let ee=null,Oe=-1;for(let xe=P-1;xe>=0;xe--)if(m[xe]?.role==="user"){ee=m[xe],Oe=m.slice(0,xe+1).filter(rt=>rt.role==="user").length-1;break}if(ee?.content&&Oe>=0){const xe=ee.images?.map((rt,ca)=>({name:`image-${ca}`,path:"",size:0,mimeType:rt.mimeType,data:rt.data}));d(Oe,ee.content,xe)}}})]})})},q.id)})})}),e.jsx(Fn,{children:e.jsx(Ai,{client:t,startSession:c,placeholder:W,commandMenuItems:B,onCancel:p,promptParameters:Y})})]})]}),e.jsx(Bn,{breakpoint:"md",children:e.jsx(Pi,{todos:T,sources:I,tools:k,mcps:E,subagents:C,sessionId:r,agentApiUrl:t?.getBaseUrl(),client:t})})]})})]})}const Yn=i.forwardRef(({sourceId:t,sources:s,className:a},n)=>{const o=s.find(m=>m.id===t);let l=null;try{l=Te()}catch{}const r=i.useCallback(m=>{m.preventDefault(),m.stopPropagation(),l&&(l.setPanelSize("small"),l.setActiveTab("sources")),o?.url&&window.open(o.url,"_blank","noopener,noreferrer")},[l,o?.url]);if(!o)return e.jsxs("span",{ref:n,className:b("inline-flex items-center px-1.5 py-0.5 text-xs font-medium","bg-muted text-muted-foreground rounded-md","cursor-default",a),children:["[",t,"]"]});const c=o.sourceName||zi(o.url);return e.jsx(fe,{delayDuration:200,children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsxs("span",{ref:n,role:"button",tabIndex:0,onClick:r,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&r(m)},className:b("inline-flex items-center gap-1 px-1.5 py-0.5","text-xs font-medium rounded-md","bg-accent/50 text-accent-foreground","hover:bg-accent cursor-pointer transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",a),children:[o.favicon&&e.jsx("img",{src:o.favicon,alt:"",className:"size-3 rounded-sm",onError:m=>{m.target.style.display="none"}}),e.jsx("span",{children:c})]})}),e.jsx(ce,{side:"top",align:"start",className:"max-w-xs p-0 overflow-hidden",children:e.jsxs("div",{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.favicon&&e.jsx("img",{src:o.favicon,alt:"",className:"size-4 rounded-sm"}),e.jsx("span",{className:"font-medium text-sm",children:c})]}),e.jsx("h4",{className:"font-medium text-sm text-foreground line-clamp-2 mb-1",children:o.title}),o.snippet&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3 mb-2",children:o.snippet}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ka,{className:"size-3"}),e.jsx("span",{children:"Click to open"})]})]})})]})})});Yn.displayName="CitationChip";function zi(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}const $i=2e5,Gn=i.forwardRef(({className:t,...s},a)=>{const n=$(k=>k.latestContextSize);if(n==null)return null;const o=n,l=Math.max(o.totalEstimated,o.llmReportedInputTokens??0),r=o.modelContextWindow??$i,c=l/r*100,m=`${c.toFixed(1)}%`,u=Math.min(100,Math.max(0,c)),p=(k=>k<50?"text-foreground":k<75?"text-yellow-500":"text-red-500")(c),g=k=>l===0?"0.0%":`${(k/l*100).toFixed(1)}%`,h=16,x=2,f=(h-x)/2,y=h/2,j=2*Math.PI*f,v=j-u/100*j;return e.jsx(fe,{children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx(ne,{ref:a,type:"button",variant:"ghost",size:"icon",className:b("rounded-full cursor-default",p,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:y,cy:y,r:f,stroke:"currentColor",strokeWidth:x,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:y,cy:y,r:f,stroke:"currentColor",strokeWidth:x,fill:"transparent",strokeDasharray:j,strokeDashoffset:v,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(ce,{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:["(",g(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:["(",g(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:["(",g(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:["(",g(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:["(",g(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:["(",g(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:["(",g(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",p),children:[e.jsx("span",{children:l.toLocaleString()}),e.jsxs("span",{children:["(",m,")"]})]})})]})})]})})});Gn.displayName="ContextUsageButton";const Li=i.forwardRef(({autoScroll:t=!0,isStreaming:s=!1,scrollBehavior:a="smooth",scrollThreshold:n=100,showScrollButton:o=!0,scrollButton:l,className:r,children:c,...m},u)=>{const d=i.useRef(null),[p,g]=i.useState(!0),[h,x]=i.useState(!1),f=i.useRef(0);i.useImperativeHandle(u,()=>{if(!d.current)throw new Error("Container ref not initialized");return d.current});const y=i.useCallback(()=>{const v=d.current;if(!v)return;const{scrollTop:k,scrollHeight:U,clientHeight:E}=v,C=U-k-E<n;g(C),x(!C&&o),f.current=k},[n,o]),j=i.useCallback((v=a)=>{const k=d.current;k&&k.scrollTo({top:k.scrollHeight,behavior:v})},[a]);return i.useEffect(()=>{!t||!d.current||(s&&p?j("auto"):!s&&p&&j())},[t,s,p,j]),i.useEffect(()=>{const v=d.current;if(!v)return;const k=()=>{y()};return v.addEventListener("scroll",k,{passive:!0}),y(),()=>{v.removeEventListener("scroll",k)}},[y]),i.useEffect(()=>{const v=d.current;if(!v)return;const k=new ResizeObserver(()=>{p&&t&&j("auto")});return k.observe(v),()=>{k.disconnect()}},[p,t,j]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx("div",{ref:d,className:b("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",r),...m,children:e.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:c})}),h&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:l||e.jsxs("button",{type:"button",onClick:()=>j(),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"]})})]})});Li.displayName="Conversation";const Oi=Es,Qn=i.forwardRef(({className:t,...s},a)=>e.jsx(ft,{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}));Qn.displayName=ft.displayName;const Fi=i.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(Oi,{children:[e.jsx(Qn,{}),e.jsxs(gt,{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(As,{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(vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fi.displayName=gt.displayName;const Bi=i.forwardRef(({className:t,...s},a)=>e.jsx(ht,{ref:a,className:b("text-subheading font-semibold leading-none tracking-tight",t),...s}));Bi.displayName=ht.displayName;const Hi=i.forwardRef(({className:t,...s},a)=>e.jsx(xt,{ref:a,className:b("text-paragraph-sm text-muted-foreground",t),...s}));Hi.displayName=xt.displayName;function Wi({message:t,messageIndex:s,isStreaming:a,onEditAndResend:n,sticky:o=!1,onEditingChange:l}){const[r,c]=i.useState(!1),[m,u]=i.useState(!1),d=i.useRef(null),p=i.useRef(null);i.useEffect(()=>{l?.(r)},[r,l]);const g=i.useCallback(()=>{if(!o||!d.current)return;let v=d.current.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(v){d.current.getBoundingClientRect(),v.getBoundingClientRect();const k=d.current.offsetTop;v.scrollTo({top:k-16,behavior:"smooth"})}},[o]),h=i.useCallback(async()=>{if(!t.content){Se.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),u(!0),Se.success("Copied to clipboard!"),setTimeout(()=>{u(!1)},2e3)}catch{Se.error("Failed to copy to clipboard")}},[t.content]),x=i.useCallback(()=>{c(!0)},[]);i.useEffect(()=>{if(r&&p.current){p.current.focus();const v=document.createRange(),k=window.getSelection();v.selectNodeContents(p.current),v.collapse(!1),k?.removeAllRanges(),k?.addRange(v)}},[r]);const f=i.useCallback(()=>{c(!1),p.current&&(p.current.textContent=t.content||"")},[t.content]),y=i.useCallback(()=>{const v=p.current?.textContent||"";if(!v.trim())return;const k=t.images?.map((U,E)=>({name:`image-${E}`,path:"",size:0,mimeType:U.mimeType,data:U.data}));n(s,v.trim(),k),c(!1)},[s,t.images,n]),j=i.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),y()),v.key==="Escape"&&(v.preventDefault(),f())},[y,f]);return e.jsxs("div",{ref:d,className:"w-full group/user-message",children:[e.jsx("div",{className:b("w-full rounded-2xl bg-secondary px-4 py-4 transition-colors",o&&"sticky top-0 z-10 bg-secondary cursor-pointer",r&&"ring-2 ring-primary/20 focus-within:ring-primary/40 transition-all bg-transparent"),onClick:o&&!r?g:void 0,onKeyDown:o&&!r?v=>{(v.key==="Enter"||v.key===" ")&&g()}:void 0,role:o&&!r?"button":void 0,tabIndex:o&&!r?0:void 0,children:e.jsxs("div",{className:"flex flex-col gap-2",children:[t.images&&t.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:t.images.map((v,k)=>e.jsx("img",{src:`data:${v.mimeType};base64,${v.data}`,alt:`Attachment ${k+1}`,className:b("max-w-[200px] max-h-[200px] rounded-lg object-cover",r&&"opacity-50")},`image-${v.mimeType}-${v.data.slice(0,20)}`))}),t.content&&e.jsx("div",{ref:p,role:"textbox",tabIndex:r?0:-1,contentEditable:r,onKeyDown:r?j:void 0,suppressContentEditableWarning:!0,className:b("whitespace-pre-wrap text-foreground leading-relaxed outline-none",r&&"cursor-text",!r&&"cursor-default"),children:t.content})]})}),!a&&t.content&&e.jsx(an,{className:b("mt-2 transition-opacity justify-end",r?"opacity-100":"opacity-0 group-hover/user-message:opacity-100"),children:r?e.jsxs(e.Fragment,{children:[e.jsx(ne,{variant:"ghost",size:"sm",onClick:f,className:"h-7 px-2 text-xs text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsx(ne,{size:"sm",onClick:y,className:"h-7 px-3 text-xs",children:"Send"})]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{onClick:h,tooltip:m?"Copied!":"Copy",children:m?e.jsx(bt,{className:"size-4"}):e.jsx(Ks,{className:"size-4"})}),e.jsx(mt,{onClick:x,tooltip:"Edit",children:e.jsx(Ya,{className:"size-4"})})]})})]})}const Vi=i.memo(Wi,(t,s)=>t.isStreaming===s.isStreaming&&t.message.id===s.message.id&&t.message.content===s.message.content&&t.messageIndex===s.messageIndex&&t.sticky===s.sticky&&t.onEditingChange===s.onEditingChange);function qi(t,s,a,n,o){const l=a==="triggered",r=n==="no_action_needed";return t==="context_size"?l?{icon:re,title:"Compacting Context..."}:{icon:re,title:r?"Context Check":"Context Compacted"}:t==="tool_response"?s==="mid_turn_compaction"||o===!0?l?{icon:re,title:"Compacting Context..."}:{icon:re,title:r?"Context Check":"Context Compacted"}:l?{icon:re,title:"Compacting Response..."}:{icon:re,title:r?"Response Check":"Tool Response Compacted"}:{icon:re,title:l?"Running Hook...":"Hook Executed"}}function Re(t){return t.toLocaleString()}function Ki(t){if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/3600),a=Math.floor(t%3600/60),n=Math.floor(t%60);return s>0?`${s}h ${a}m ${n}s`:`${a}m ${n}s`}function Mt({notification:t}){const[s,a]=i.useState(!1),[n,o]=i.useState(0),{icon:l,title:r}=qi(t.hookType,t.callback,t.status,t.metadata?.action,t.metadata?.midTurn),c=t.status==="triggered",m=t.status==="completed",u=t.status==="error";i.useEffect(()=>{if(!c||!t.triggeredAt)return;const h=()=>{const f=(Date.now()-t.triggeredAt)/1e3;o(f)};h();const x=setInterval(h,100);return()=>clearInterval(x)},[c,t.triggeredAt]);const d=t.callback==="mid_turn_compaction"||t.metadata?.midTurn===!0;let p="";if(c&&t.currentPercentage!==void 0)p=`Context at ${t.currentPercentage.toFixed(1)}% (threshold: ${t.threshold}%)`;else if(m&&t.metadata?.tokensSaved!==void 0){const{tokensSaved:h,originalTokens:x,messagesRemoved:f}=t.metadata;if(d)p=`${f!==void 0?`${Re(f)} messages summarized, `:""}${Re(h??0)} tokens saved`;else if(x!==void 0&&x>0)p=`${((h??0)/x*100).toFixed(0)}% reduced`;else if(t.currentPercentage!==void 0&&t.currentPercentage>0){const j=t.currentPercentage/100*2e5;p=`${((h??0)/j*100).toFixed(1)}% context freed`}else p=`${Re(h)} tokens saved`}else u&&t.error&&(p=t.error);const g=t.metadata?.truncationWarning;return e.jsxs("div",{className:"flex flex-col my-3",children:[e.jsxs("button",{type:"button",className:"flex flex-col items-start gap-0.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>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:u?"text-destructive":"text-muted-foreground",children:e.jsx(l,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:r}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Lt,{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"]})]}),m&&e.jsx(wt,{className:"h-3 w-3 text-green-500"}),u&&e.jsx(ut,{className:"h-3 w-3 text-destructive"}),!c&&e.jsx(le,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${s?"rotate-180":""}`})]}),p&&e.jsx("span",{className:`text-paragraph-sm pl-4.5 ${u?"text-destructive/70":"text-muted-foreground/70"}`,children:p})]}),s&&!c&&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:Re(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:Re(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:[Re(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:[Re(t.metadata.finalTokens)," tokens"]})]})]})]}),g&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0 bg-yellow-500/5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-bold text-yellow-600 dark:text-yellow-500 uppercase tracking-wider mb-1.5 font-sans",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Warning"]}),e.jsx("div",{className:"text-[11px] text-yellow-700 dark:text-yellow-400",children:g})]}),t.error&&e.jsxs("div",{className:"p-3 border-b border-border last:border-0",children:[e.jsx("div",{className:"text-[10px] font-bold text-destructive uppercase tracking-wider mb-1.5 font-sans",children:"Error"}),e.jsx("div",{className:"text-[11px] text-destructive font-mono",children:t.error})]}),e.jsx("div",{className:"p-2 bg-muted/50 border-t border-border text-[10px] text-muted-foreground font-sans",children:t.triggeredAt&&e.jsxs("div",{className:"flex gap-3 justify-end",children:[e.jsxs("span",{children:["Started:"," ",new Date(t.triggeredAt).toLocaleTimeString()]}),t.completedAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"-"}),e.jsxs("span",{children:["Completed:"," ",new Date(t.completedAt).toLocaleTimeString()]}),e.jsx("span",{children:"-"}),e.jsxs("span",{children:["Duration:"," ",Ki((t.completedAt-t.triggeredAt)/1e3)]})]})]})})]})]})}const Yi=i.forwardRef(({className:t,...s},a)=>e.jsx(Ps,{ref:a,className:b("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));Yi.displayName=Ps.displayName;function Et({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,...l})=>l.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",...l}):e.jsx("input",{...l}),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 l=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(c=>typeof c=="object"&&c!==null&&"type"in c&&c.type==="element"&&"tagName"in c&&c.tagName==="input"&&"properties"in c&&typeof c.properties=="object"&&c.properties!==null&&"type"in c.properties&&c.properties.type==="checkbox"));return e.jsx("ul",{className:b("my-2 space-y-1 text-foreground",l?"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 l=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",l?"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(da,{remarkPlugins:[Ys],components:a,children:t})})}const Gi=we("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"}}),Jn=i.forwardRef(({message:t,role:s,layout:a,className:n,children:o,messageId:l,autoScroll:r,isLastMessage:c=!1,...m},u)=>{const d=t?t.role:s||"assistant",p=t?t.id:l,g=i.useRef(null),[h,x]=i.useState(void 0);return i.useImperativeHandle(u,()=>g.current),i.useEffect(()=>{if(!c||d!=="assistant"){x(void 0);return}const f=()=>{const j=g.current;if(!j)return;let v=j.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(!v)return;const k=j.previousElementSibling;if(!k||k.getAttribute("aria-label")!=="user message"){x(void 0);return}const U=v.clientHeight,E=k.offsetHeight,C=Math.max(0,U-E-32);x(C)};f();const y=new ResizeObserver(f);if(g.current){y.observe(g.current);let j=g.current.parentElement;for(;j&&!j.classList.contains("overflow-y-auto");)j=j.parentElement;j&&y.observe(j)}return()=>y.disconnect()},[c,d]),i.useEffect(()=>{if((r!==void 0?r:d==="user")&&g.current){const y=setTimeout(()=>{g.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(y)}},[d,r]),e.jsx("article",{ref:g,"aria-label":`${d} message`,"data-message-id":p,className:b(Gi({role:d,layout:a}),n),style:{minHeight:h!==void 0?`${h}px`:void 0},...m,children:o})});Jn.displayName="Message";const Qi=[{id:"pdf",label:"PDF",icon:$e},{id:"excel",label:"Excel",icon:es},{id:"csv",label:"CSV",icon:es},{id:"text",label:"Text",icon:Xa},{id:"markdown",label:"Markdown",icon:$e}];function Ji({message:t,isStreaming:s,onRedo:a,onSendMessage:n,isLastAssistantMessage:o=!1}){const[l,r]=i.useState(!1);if(s||t.role!=="assistant"||!t.content)return null;const c=o?"":"opacity-0 group-hover:opacity-100 transition-opacity",m=async()=>{if(!t.content){Se.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),r(!0),Se.success("Copied to clipboard!"),setTimeout(()=>{r(!1)},2e3)}catch{Se.error("Failed to copy to clipboard")}},u=()=>{a?a():Se.info("Regenerate not available")},d=p=>{n?n(`produce an artifact as ${p} for this session`):Se.info("Export not available")};return e.jsxs(an,{className:b("mt-2 mb-10",c),children:[e.jsx(mt,{onClick:m,tooltip:l?"Copied!":"Copy",children:l?e.jsx(bt,{className:"size-4"}):e.jsx(Ks,{className:"size-4"})}),e.jsx(mt,{onClick:u,tooltip:"Redo",children:e.jsx(Qa,{className:"size-4"})}),e.jsxs(st,{children:[e.jsx(fe,{children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx(nt,{asChild:!0,children:e.jsxs(ne,{className:b("relative size-7 p-1.5 text-muted-foreground hover:text-foreground"),size:"sm",type:"button",variant:"ghost",children:[e.jsx(Ja,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Export"})]})})}),e.jsx(ce,{children:e.jsx("p",{children:"Export"})})]})}),e.jsx(Le,{align:"start",children:Qi.map(p=>e.jsxs(pe,{onClick:()=>d(p.label),children:[e.jsx(p.icon,{className:"size-4 mr-2"}),p.label]},p.id))})]})]})}const Xi=i.memo(Ji,(t,s)=>!(t.isStreaming!==s.isStreaming||t.message.id!==s.message.id||t.message.content!==s.message.content||t.onRedo!==s.onRedo||t.onSendMessage!==s.onSendMessage||t.isLastAssistantMessage!==s.isLastAssistantMessage)),Zi={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 el(t,s){if(!s||!t.rawInput)return null;const a=t.rawInput[s];return typeof a=="string"?a:null}function tl(t,s){let a=t;for(const[n,o]of Object.entries(s))a=a.replace(`{${n}}`,o);return a}function sl(t,s){return t.length<=s?t:`${t.substring(0,s-1)}…`}function pt(t,s){const a=t.verbiage||Zi[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=el(t,a.paramKey);if(o){const l=sl(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"),tl(n,{[r]:l})}}if(t.subline){const o=n.split("{")[0];return o?`${o.trim()} ${t.subline}`:t.subline}return n.replace(/\s*\{[^}]+\}/g,"")}function nl(t){return t.prettyName||t.title}function ze(t){return t.status==="pending"&&(!t.rawInput||Object.keys(t.rawInput).length===0)}function Ct(t){return t.status==="failed"||t.error?"failed":t.status==="completed"?"completed":ze(t)?"selecting":(t.status==="pending"||t.status==="in_progress","executing")}function Xn(t){switch(Ct(t)){case"selecting":return`Selecting ${t.prettyName||t.title}`;case"executing":return pt(t,"active");case"completed":return pt(t,"past");case"failed":return`Failed to use ${t.prettyName||t.title}`;default:return t.prettyName||t.title}}function al(t){return t.every(s=>Ct(s)==="completed")}function ol(t){return t.some(s=>Ct(s)==="failed")}function rl(t){return ol(t)?"failed":al(t)?"completed":t.every(s=>ze(s))?"selecting":"executing"}const hs=we("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"}}),il=we("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Zn=i.forwardRef(({content:t,isStreaming:s=!1,mode:a="collapsible",defaultExpanded:n=!1,autoExpand:o=!1,autoCollapse:l=!0,autoCollapseDelay:r=2e3,label:c="Thinking",variant:m,className:u},d)=>{const[p,g]=i.useState(a==="inline"?!0:n),[h,x]=i.useState(!1);return i.useEffect(()=>{if(l&&!s&&t&&a==="collapsible"){const f=setTimeout(()=>{x(!0),g(!1)},r);return()=>clearTimeout(f)}},[s,t,l,r,a]),i.useEffect(()=>{o&&s&&a==="collapsible"&&!h&&g(!0)},[o,s,a,h]),!t&&!s?null:a==="inline"?e.jsxs("div",{ref:d,className:b(hs({variant:m}),"p-3",u),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:c}),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:d,className:b("mb-3",u),children:[e.jsxs("button",{type:"button",onClick:()=>{g(!p),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":p,"aria-label":`${p?"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:c}),s&&e.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!p&&t&&e.jsxs("span",{className:"text-caption text-foreground opacity-50 truncate",children:[t.substring(0,60),t.length>60&&"..."]})]}),e.jsx(le,{className:il({expanded:p}),"aria-hidden":"true"})]}),p&&e.jsx("div",{className:b(hs({variant:m}),"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:"..."})]})})]})});Zn.displayName="Reasoning";function ll(){return t=>{ba(t,"text",(s,a,n)=>{if(!n||a===void 0)return;const o=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g,l=s.value;if(!o.test(l))return;o.lastIndex=0;const r=[];let c=0,m;for(;(m=o.exec(l))!==null;){m.index>c&&r.push({type:"text",value:l.slice(c,m.index)});const u=m[1]??m[2]??"";r.push({type:"citation",data:{hName:"span",hProperties:{"data-citation-id":u,className:"citation-marker"}},sourceId:u}),c=m.index+m[0].length}c<l.length&&r.push({type:"text",value:l.slice(c)}),r.length>0&&n.children.splice(a,1,...r)})}}const De=i.memo(i.forwardRef(({content:t,isStreaming:s=!1,showEmpty:a=!0,emptyMessage:n="",sources:o=[],className:l,...r},c)=>{const m=i.useMemo(()=>[Ys,ll],[]),u=i.useMemo(()=>({span:d=>{const{className:p,class:g,"data-citation-id":h,children:x,...f}=d,y=p||g;return y==="citation-marker"&&h?e.jsx(Yn,{sourceId:h,sources:o}):e.jsx("span",{className:y,...f,children:x})}}),[o]);return!t&&s&&a?e.jsx("div",{ref:c,className:b("opacity-70 italic text-paragraph-sm",l),...r,children:n}):t?e.jsx("div",{ref:c,...r,children:e.jsx(ya,{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",l),remarkPlugins:m,components:u,children:t})}):null}),(t,s)=>t.content===s.content&&t.sources===s.sources);De.displayName="Response";function cl(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 Ut(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 dl(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(l=>l.startsWith(`${n}/`))?n:null}function ul(t,s){if(t.length===0)return"";if(t.length===1)return pt(t[0],s);const a=t[0],n=a.title,o=t.map(cl).filter(u=>u!==null);if((n==="Read"||n==="Write"||n==="read_file"||n==="write"||n==="search_replace"||n==="delete_file")&&o.length>0){const u=dl(o);if(u){const p=s==="active"?"working on":"worked on";return`${p.charAt(0).toUpperCase()+p.slice(1)} ${o.length} files in ${u}`}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"} ${Ut(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"} ${Ut(o)}`;const c=nl(a);return`${s==="active"?"Using":"Used"} ${c} ${t.length} times`}function ml(t,s){if(t.length===0)return"";if(t.length===1)return pt(t[0],s);if([...new Set(t.map(l=>l.title))].length===1)return ul(t,s);const n=t.map(l=>l.prettyName||l.title).filter((l,r,c)=>c.indexOf(l)===r);return`${s==="active"?"Running":"Ran"} ${Ut(n)}`}const pl=50;function ea({parentStatus:t,agentName:s,query:a,isExpanded:n,onExpandChange:o,storedMessages:l}){const[r,c]=i.useState(!1),m=n??r,[u,d]=i.useState(!0),[p,g]=i.useState(!0),h=i.useRef(null),x=l||[];i.useEffect(()=>{console.log("[SUBAGENT] SubAgentDetails received messages update",{agentName:s,messageCount:x.length,parentStatus:t,hasMessages:x.length>0,contentPreview:x[0]?.content?.substring(0,100),toolCallCount:x[0]?.toolCalls?.length||0,contentBlockCount:x[0]?.contentBlocks?.length||0})},[x,s,t]);const f=t==="in_progress"||t==="pending",y=x[x.length-1],j=y&&(y.content||y.toolCalls&&y.toolCalls.length>0||y.contentBlocks&&y.contentBlocks.length>0);console.log("[SUBAGENT] SubAgentDetails render state",{agentName:s,messageCount:x.length,hasContent:j,isRunning:f,parentStatus:t});const v=i.useRef(f);i.useEffect(()=>{v.current&&!f&&d(!1),v.current=f},[f]);const k=i.useCallback(()=>{const A=h.current;if(!A)return;const{scrollTop:Y,scrollHeight:H,clientHeight:W}=A,K=H-Y-W;g(K<pl)},[]),U=i.useCallback(()=>{const A=h.current;A&&(A.scrollTop=A.scrollHeight)},[]);i.useEffect(()=>{p&&(f||j)&&U()},[p,f,j,U]),i.useEffect(()=>{const A=h.current;if(!A)return;const Y=()=>k();return A.addEventListener("scroll",Y,{passive:!0}),k(),()=>A.removeEventListener("scroll",Y)},[k]),i.useEffect(()=>{u&&(g(!0),requestAnimationFrame(()=>{U()}))},[u,U]);const E=y?.content&&y.content.split(`
9
+ `).filter(Boolean).pop()||"",z=E.length>100?`${E.slice(0,100)}...`:E,C=a?(a.split(`
10
+ `)[0]??"").slice(0,100)+(a.length>100?"...":""):"";return e.jsxs("div",{children:[!m&&e.jsx("div",{className:"w-full max-w-md",children:z?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:z}):C?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate",children:C}):null}),m&&e.jsxs("div",{className:"space-y-3",children:[(s||a)&&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:[s&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"agentName: "}),e.jsx("span",{className:"text-foreground",children:s})]}),a&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"query: "}),e.jsx("span",{className:"text-foreground",children:a})]})]})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>d(!u),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(le,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${u?"rotate-180":""}`})]}),u&&e.jsxs("div",{ref:h,className:"mt-2 rounded-md overflow-hidden bg-muted/30 border border-border/50 max-h-[200px] overflow-y-auto",children:[!j&&f&&e.jsx("div",{className:"px-2 py-2 text-[11px] text-muted-foreground",children:"Waiting for sub-agent response..."}),y&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[y.contentBlocks&&y.contentBlocks.length>0?y.contentBlocks.map((A,Y)=>A.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(Et,{content:A.text})},`text-${A.text.slice(0,30)}-${Y}`):e.jsx(fl,{toolCall:A.toolCall},A.toolCall.id)):y.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(Et,{content:y.content})}),y.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!f&&y?.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(Et,{content:y.content})})]})]})]})}function fl({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(Lt,{className:"h-2.5 w-2.5 animate-spin"})]})}function gl({todos:t,className:s}){if(!t||t.length===0)return null;const a=i.useMemo(()=>{const o=t.find(r=>r.status==="in_progress");if(o)return o;const l=t.find(r=>r.status==="completed");return l||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(wt,{className:"size-3 text-muted-foreground shrink-0"}):a.status==="pending"?e.jsx(yt,{className:"size-3 text-foreground shrink-0"}):null,e.jsx("span",{className:"truncate",children:n})]})}const xs={Globe:Ws,Image:oo,Link:ao,Cloud:no,CheckSquare:jt,Search:so,FileText:$e,Edit:to,Wrench:eo,BrainCircuit:Za,CircleDot:Ot};function hl(t,s){const[a,n]=i.useState(0),o=i.useRef(null);return i.useEffect(()=>{if(!t){n(0);return}const l=()=>{n((Date.now()-t)/1e3)};return l(),o.current=setInterval(l,100),()=>{o.current&&clearInterval(o.current)}},[t,s]),a}function ta(t){if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/3600),a=Math.floor(t%3600/60),n=Math.floor(t%60);return s>0?`${s}h ${a}m ${n}s`:`${a}m ${n}s`}function Ue({startTime:t}){const s=hl(t,!0);return e.jsx("span",{className:"text-xs text-text-secondary/70 tabular-nums ml-1",children:ta(s)})}function xl({compactionAction:t,originalTokens:s,finalTokens:a,originalContentPath:n}){const o=s&&a?s-a:void 0,l=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(re,{className:"w-3.5 h-3.5 text-text-secondary"}):e.jsx(Je,{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"]})]}),l!==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:[l,"%"]})]})]}),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 _e({toolCalls:t,isGrouped:s=!1,autoMinimize:a=!0,hookNotifications:n=[]}){const[o,l]=i.useState(!1),[r,c]=i.useState(!1),[m,u]=i.useState(!1),d=t.length===1?t[0]:null,p=d?.title==="todo_write",g=d?n.find(R=>R.toolCallId===d.id):void 0,h=!!(g?.status==="completed"&&g.metadata?.action&&g.metadata.action!=="no_action_needed"&&g.metadata.action!=="none"||d?._meta?.compactionAction),x=g?.metadata?.action==="truncated"||g?.metadata?.action==="compacted_then_truncated"||d?._meta?.compactionAction==="truncated",f=s?t.some(R=>R._meta?.compactionAction||n.some(N=>N.toolCallId===R.id&&N.status==="completed"&&N.metadata?.action&&N.metadata.action!=="no_action_needed"&&N.metadata.action!=="none")):!1,y=s?t.some(R=>R._meta?.compactionAction==="truncated"||n.some(N=>N.toolCallId===R.id&&(N.metadata?.action==="truncated"||N.metadata?.action==="compacted_then_truncated"))):!1,j=!!(d?.subagentMessages&&d.subagentMessages.length>0),[v,k]=i.useState(!1),U=Pt.useContext(Vt),E=s?rl(t):d?Ct(d):"executing",z=E==="completed",C=E==="failed",A=E==="selecting";i.useEffect(()=>{if(a&&z&&!r&&!m){const R=setTimeout(()=>{c(!0),l(!1)},500);return()=>clearTimeout(R)}},[a,z,r,m]);const Y=Pt.useCallback(()=>{p&&U&&d?U.panelSize!=="hidden"&&U.activeTab==="todo"?U.setPanelSize("hidden"):(U.setPanelSize("small"),U.setActiveTab("todo")):j?(u(!0),k(!v)):(u(!0),l(!o),r&&c(!1))},[p,U,o,r,d,j,v]),W=s?ts:d?.icon&&xs[d.icon]?xs[d.icon]:Ot,D=s?ml(t,z?"past":"active"):d?Xn(d):"Tool operation";if(A&&!s)return e.jsx("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(W,{className:"h-3 w-3"})}),e.jsxs("span",{className:"text-paragraph-xs text-text-muted",children:[D,d?.startedAt&&e.jsx(Ue,{startTime:d.startedAt})]})]})});if(A&&s){const R=(()=>{const N=t.map(_=>_.startedAt).filter(_=>_!=null);return N.length===0?null:Math.min(...N)})();return 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(ts,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Selecting tools"}),R&&e.jsx(Ue,{startTime:R}),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:D})]})}return e.jsxs("div",{className:"flex flex-col my-4",children:[e.jsxs("button",{type:"button",className:"flex flex-col items-start gap-0.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit rounded-md px-1 -mx-1",onClick:Y,"aria-expanded":p?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(W,{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&&D]}),!s&&d?.startedAt&&E==="executing"&&e.jsx(Ue,{startTime:d.startedAt}),s&&E==="executing"&&(()=>{const R=t.map(_=>_.startedAt).filter(_=>_!=null);if(R.length===0)return null;const N=Math.min(...R);return e.jsx(Ue,{startTime:N})})(),s&&e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-text-secondary/70",children:t.length}),C&&e.jsx("span",{title:s?`${t.filter(R=>R.status==="failed").length} of ${t.length} operations failed`:d?.error||"Operation failed",children:e.jsx(ut,{className:"h-3 w-3 text-destructive"})}),s&&f&&e.jsx(fe,{delayDuration:0,children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx("span",{children:y?e.jsx(Je,{className:"h-3 w-3 text-destructive"}):e.jsx(re,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ce,{children:y?"Some responses were truncated":"Some responses were compacted"})]})}),!s&&h&&e.jsx(fe,{delayDuration:0,children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx("span",{children:x?e.jsx(Je,{className:"h-3 w-3 text-destructive"}):e.jsx(re,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ce,{children:(()=>{const R=d?._meta,N=R?.originalTokens&&R?.finalTokens?Math.round((1-R.finalTokens/R.originalTokens)*100):null;return x?N?`Response truncated (${N}% reduction)`:"Response was truncated":N?`Response compacted (${N}% reduction)`:"Response was compacted"})()})]})}),p?e.jsx(qe,{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(le,{className:"h-3 w-3"})})]}),!s&&d&&(p&&d.rawInput?.todos?e.jsx(gl,{todos:d.rawInput.todos,className:"text-paragraph-sm text-text-secondary/70 pl-4.5"}):d.subline?e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:d.subline}):null),!s&&g&&e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:g.status==="triggered"?"Compacting response...":g.status==="completed"?g.metadata?.action==="no_action_needed"?`Response checked (${g.currentPercentage?.toFixed(0)}% context)`:g.metadata?.tokensSaved?`Response compacted (${(g.metadata.tokensSaved/(g.metadata.originalTokens||1)*100).toFixed(0)}% reduced)`:"Response compacted":g.status==="error"?`Compaction error: ${g.error}`:null}),s&&!o&&e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:D}),s&&n.length>0&&(()=>{const R=n.filter(_=>_.status==="completed"&&_.metadata?.action!=="no_action_needed").length,N=n.filter(_=>_.status==="triggered").length;return N>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:["Compacting ",N," response",N>1?"s":"","..."]}):R>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:[R," response",R>1?"s":""," ","compacted"]}):null})()]}),!p&&j&&d&&e.jsx("div",{className:"pl-4.5 mt-2",children:e.jsx(ea,{parentStatus:d.status,agentName:d.rawInput?.agentName,query:d.rawInput?.query,isExpanded:v,onExpandChange:k,storedMessages:d.subagentMessages})}),!p&&o&&e.jsx("div",{className:"mt-1",children:s?e.jsx("div",{className:"flex flex-col gap-4 mt-2",children:t.map(R=>{const N=n.find(_=>_.toolCallId===R.id);return e.jsx(bl,{toolCall:R,...N?{hookNotification:N}:{}},R.id)})}):d&&e.jsx(sa,{toolCall:d,...g?{hookNotification:g}:{}})})]})}function bl({toolCall:t,hookNotification:s}){const[a,n]=i.useState(!1),o=!!(t.subagentMessages&&t.subagentMessages.length>0),l=!!(s?.status==="completed"&&s.metadata?.action&&s.metadata.action!=="no_action_needed"&&s.metadata.action!=="none"||t._meta?.compactionAction),r=s?.metadata?.action==="truncated"||s?.metadata?.action==="compacted_then_truncated"||t._meta?.compactionAction==="truncated",c=t.status==="failed",m=t.status==="pending"||t.status==="in_progress";return o?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(Ot,{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"}),m&&t.startedAt&&e.jsx(Ue,{startTime:t.startedAt}),c&&e.jsx("span",{title:t.error||"Operation failed",children:e.jsx(ut,{className:"h-3 w-3 text-destructive"})}),l&&e.jsx(fe,{delayDuration:0,children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx("span",{children:r?e.jsx(Je,{className:"h-3 w-3 text-destructive"}):e.jsx(re,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ce,{children:(()=>{const u=t._meta,d=u?.originalTokens&&u?.finalTokens?Math.round((1-u.finalTokens/u.originalTokens)*100):null;return r?d?`Response truncated (${d}% reduction)`:"Response was truncated":d?`Response compacted (${d}% reduction)`:"Response was compacted"})()})]})}),e.jsx(le,{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(ea,{parentStatus:t.status,agentName:t.rawInput?.agentName,query:t.rawInput?.query,isExpanded:a,onExpandChange:n,storedMessages:t.subagentMessages})})]}):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}),m&&t.startedAt&&e.jsx(Ue,{startTime:t.startedAt}),c&&e.jsx("span",{title:t.error||"Operation failed",children:e.jsx(ut,{className:"h-3 w-3 text-destructive"})}),l&&e.jsx(fe,{delayDuration:0,children:e.jsxs(ge,{children:[e.jsx(he,{asChild:!0,children:e.jsx("span",{children:r?e.jsx(Je,{className:"h-3 w-3 text-destructive"}):e.jsx(re,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ce,{children:(()=>{const u=t._meta,d=u?.originalTokens&&u?.finalTokens?Math.round((1-u.finalTokens/u.originalTokens)*100):null;return r?d?`Response truncated (${d}% reduction)`:"Response was truncated":d?`Response compacted (${d}% reduction)`:"Response was compacted"})()})]})}),e.jsx(le,{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(sa,{toolCall:t,...s?{hookNotification:s}:{}})})]})}function yl(t){let s="",a="",n="";const o=t.match(/\[stderr\]\n?([\s\S]*?)(?=\[error\]|$)/),l=t.match(/\[error\]\s*([\s\S]*?)$/);o?.[1]&&(a=o[1].trim()),l?.[1]&&(n=l[1].trim());const r=Math.min(t.includes("[stderr]")?t.indexOf("[stderr]"):t.length,t.includes("[error]")?t.indexOf("[error]"):t.length);return s=t.substring(0,r).trim(),{stdout:s,stderr:a,error:n}}function At(t){return t==="Sandbox_RunCode"||t==="Sandbox_RunBash"}function vl({stdout:t,stderr:s}){const[a,n]=i.useState(s?"stderr":"stdout");return e.jsxs("div",{className:"mx-3 mb-3 border border-border rounded-md overflow-hidden bg-zinc-950 dark:bg-zinc-950",children:[e.jsxs("div",{className:"flex border-b border-zinc-800 bg-zinc-900",children:[e.jsx("button",{type:"button",onClick:()=>n("stdout"),className:`px-3 py-1.5 text-[11px] font-mono transition-colors border-b-2 ${a==="stdout"?"text-zinc-100 border-zinc-100 bg-zinc-800":"text-zinc-500 border-transparent hover:text-zinc-300"}`,children:"stdout"}),e.jsxs("button",{type:"button",onClick:()=>n("stderr"),className:`px-3 py-1.5 text-[11px] font-mono transition-colors border-b-2 flex items-center gap-1.5 ${a==="stderr"?"text-zinc-100 border-zinc-100 bg-zinc-800":"text-zinc-500 border-transparent hover:text-zinc-300"}`,children:["stderr",s&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-red-500"})]})]}),e.jsxs("div",{className:"p-3 max-h-[300px] overflow-auto",children:[a==="stdout"&&e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-zinc-300",children:t||e.jsx("span",{className:"text-zinc-600 italic",children:"(no output)"})}),a==="stderr"&&e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-red-400",children:s||e.jsx("span",{className:"text-zinc-600 italic",children:"(no errors)"})})]})]})}function sa({toolCall:t,hookNotification:s}){const{resolvedTheme:a}=Wt(),[n,o]=i.useState(!1);if(ze(t))return e.jsx("div",{className:"text-paragraph-sm text-text-secondary/70 ml-2",children:Xn(t)});const l={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(r=>e.jsxs("li",{className:"font-mono text-[11px] text-foreground bg-muted px-1.5 py-0.5 rounded w-fit",children:[r.path,r.line!==null&&r.line!==void 0&&`:${r.line}`]},`${r.path}:${r.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(Jt,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:l})})]}),t._meta?.compactionAction&&e.jsx(xl,{compactionAction:t._meta.compactionAction,originalTokens:t._meta.originalTokens,finalTokens:t._meta.finalTokens,originalContentPath:t._meta.originalContentPath}),(t.content&&t.content.length>0||t.error)&&!At(t.title)&&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((r,c)=>{const m=()=>r.type==="diff"&&"path"in r?`diff-${r.path}-${c}`:r.type==="terminal"&&"terminalId"in r?`terminal-${r.terminalId}`:r.type==="text"&&"text"in r?`text-${r.text.substring(0,20)}-${c}`:r.type==="content"&&"content"in r?`content-${r.content.text?.substring(0,20)}-${c}`:`block-${c}`,u=(p,g)=>{try{const h=JSON.parse(p);if(typeof h=="object"&&h!==null){const x={...h};return"_compactionMeta"in x&&delete x._compactionMeta,e.jsx("div",{className:"text-[11px]",children:e.jsx(Jt,{value:x,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:l})},g)}}catch{}return e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-foreground overflow-x-auto",children:p},g)};if(At(t.title)&&(r.type==="text"||r.type==="content"))return null;if(r.type==="content"&&"content"in r){const p=r.content;if(p.type==="text"&&p.text)return u(p.text,m())}if(r.type==="text"&&"text"in r)return u(r.text,m());if(r.type==="image"){const p=r.alt||"Generated image";let g;if("data"in r)g=`data:${r.mimeType||"image/png"};base64,${r.data}`;else if("url"in r)g=r.url;else return null;return e.jsx("div",{className:"my-2",children:e.jsx("img",{src:g,alt:p,className:"max-w-full h-auto rounded-md border border-border"})},m())}return r.type==="diff"&&"path"in r&&"oldText"in r&&"newText"in r?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:[r.path,"line"in r&&r.line!==null&&r.line!==void 0&&`:${r.line}`]}),e.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"text-red-500 dark:text-red-400",children:["- ",r.oldText]}),e.jsxs("div",{className:"text-green-500 dark:text-green-400",children:["+ ",r.newText]})]})]},m()):null}),t.error&&e.jsxs("div",{className:"text-destructive font-mono text-[11px] mt-2",children:["Error: ",t.error]})]})]}),At(t.title)&&(()=>{const c=(()=>{for(const p of t.content||[]){if(p.type==="text"&&"text"in p)return p.text;if(p.type==="content"&&"content"in p){const g=p.content;if(g.type==="text"&&g.text)return g.text}}return null})();if(!c)return null;const m=yl(c),u=[m.stderr,m.error].filter(Boolean).join(`
11
+ `);return m.stdout||u?e.jsxs("div",{className:"border-b border-border last:border-0",children:[e.jsxs("button",{type:"button",onClick:()=>o(!n),className:"w-full p-3 flex items-center justify-between cursor-pointer bg-transparent border-none text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ro,{className:"h-3.5 w-3.5 text-text-secondary"}),e.jsx("span",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider font-sans",children:"Console"}),m.error&&e.jsx("span",{className:"px-1.5 py-0.5 bg-destructive/10 text-destructive rounded text-[9px] font-medium",children:"Error"})]}),e.jsx(le,{className:`h-3.5 w-3.5 text-text-secondary transition-transform duration-200 ${n?"rotate-180":""}`})]}),n&&e.jsx(vl,{stdout:m.stdout,stderr:u})]}):null})(),t._meta?.truncationWarning&&e.jsxs("div",{className:"mx-3 mt-3 mb-0 flex items-center gap-2 rounded-md bg-yellow-50 dark:bg-yellow-950/20 px-3 py-2 text-[11px] text-yellow-800 dark:text-yellow-200 border border-yellow-200 dark:border-yellow-900",children:[e.jsx("span",{className:"text-yellow-600 dark:text-yellow-500",children:"⚠️"}),e.jsx("span",{children:t._meta.truncationWarning})]}),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(e.Fragment,{children:[e.jsx("span",{children:"-"}),e.jsxs("span",{children:["Completed:"," ",new Date(t.completedAt).toLocaleTimeString()]}),e.jsx("span",{children:"-"}),e.jsxs("span",{children:["Duration:"," ",ta((t.completedAt-t.startedAt)/1e3)]})]})]})]})]})}const wl=we("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"}}),na=i.forwardRef(({role:t,variant:s,isStreaming:a,message:n,thinkingDisplayStyle:o="collapsible",className:l,children:r,...c},m)=>{const u=$(x=>x.streamingStartTime);$(x=>x.currentModel);const d=n&&!r,p=d?n.role:t||"assistant",g=d?n.isStreaming:a;let h=r;if(d){const x=n.metadata?.thinking,f=!!x,y=n.isStreaming&&!n.content&&n.role==="assistant";h=e.jsxs(e.Fragment,{children:[n.role==="assistant"&&f&&e.jsx("div",{children:e.jsx(Zn,{content:x,isStreaming:n.isStreaming,mode:o,autoCollapse:!0})}),y&&u&&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:"Working..."})})}),n.role==="assistant"?(()=>{const j=(n.toolCalls||[]).slice().sort((N,_)=>(N.contentPosition??1/0)-(_.contentPosition??1/0)),v=N=>{const _=[],T=new Map;let S=[],M=[],I=null;const V=()=>{S.length>1?_.push({type:"selecting",toolCalls:S}):S.length===1&&_.push(S[0]),S=[]},J=()=>{M.length>1?_.push({type:"batch",toolCalls:M}):M.length===1&&_.push(M[0]),M=[],I=null};for(const B of N){if(B.title==="todo_write"){V(),J(),_.push(B);continue}if(B.batchId){V(),J();const P=T.get(B.batchId);if(P)P.push(B);else{const G=[B];T.set(B.batchId,G),_.push({type:"batch",toolCalls:G})}}else ze(B)?(J(),S.push(B)):(V(),I===B.title?M.push(B):(J(),M=[B],I=B.title))}return V(),J(),_},k=(n.hookNotifications||[]).filter(N=>N.hookType==="tool_response"),U=(N,_)=>{if(typeof N=="object"&&"type"in N&&N.type==="batch"){const M=k.filter(I=>N.toolCalls.some(V=>V.id===I.toolCallId));return e.jsx(_e,{toolCalls:N.toolCalls,isGrouped:!0,hookNotifications:M},`batch-${N.toolCalls[0]?.batchId||_}`)}if(typeof N=="object"&&"type"in N&&N.type==="selecting")return e.jsx(_e,{toolCalls:N.toolCalls,isGrouped:!0},`selecting-${N.toolCalls[0]?.id||_}`);const T=N,S=k.filter(M=>M.toolCallId===T.id);return e.jsx(_e,{toolCalls:[T],isGrouped:!1,hookNotifications:S},T.id)},E=(n.hookNotifications||[]).filter(N=>N.hookType!=="tool_response").slice().sort((N,_)=>(N.contentPosition??1/0)-(_.contentPosition??1/0));if(j.length===0||!j.some(N=>N.contentPosition!==void 0)){const N=v(j);if(!E.some(M=>M.contentPosition!==void 0))return e.jsxs(e.Fragment,{children:[E.length>0&&e.jsx("div",{className:"flex flex-col gap-2 mb-1",children:E.map(M=>e.jsx(Mt,{notification:M},M.id))}),N.length>0&&e.jsx("div",{className:"flex flex-col gap-2 mb-1",children:N.map((M,I)=>U(M,I))}),e.jsx("div",{children:e.jsx(De,{content:n.content,isStreaming:n.isStreaming,showEmpty:!1,sources:n.sources??[]})})]});const T=[];let S=0;if(E.forEach(M=>{const I=M.contentPosition??n.content.length;if(I>S){const V=n.content.slice(S,I);V&&T.push(e.jsx("div",{children:e.jsx(De,{content:V,isStreaming:!1,showEmpty:!1,sources:n.sources??[]})},`text-before-hook-${M.id}`))}T.push(e.jsx(Mt,{notification:M},M.id)),S=I}),S<n.content.length){const M=n.content.slice(S);M&&T.push(e.jsx("div",{children:e.jsx(De,{content:M,isStreaming:n.isStreaming,showEmpty:!1,sources:n.sources??[]})},"text-end-hooks"))}return N.length>0&&N.forEach((M,I)=>{T.push(U(M,I))}),e.jsx(e.Fragment,{children:T})}const z=[],C=[],A=j.filter(ze);j.filter(N=>!ze(N)).forEach(N=>{C.push({type:"toolCall",item:N,position:N.contentPosition??n.content.length})}),E.forEach(N=>{C.push({type:"hookNotification",item:N,position:N.contentPosition??0})}),C.sort((N,_)=>N.position-_.position);let H=0,W=[],K,D;const R=()=>{W.length>1?z.push(e.jsx(_e,{toolCalls:W,isGrouped:!0},`group-${K||D}-${W[0]?.id}`)):W.length===1&&z.push(e.jsx("div",{children:e.jsx(_e,{toolCalls:[W[0]],isGrouped:!1})},`tool-${W[0]?.id}`)),W=[],K=void 0,D=void 0};if(C.forEach((N,_)=>{const T=N.position;if(T>H){R();const S=n.content.slice(H,T);if(S){const M=(N.type==="toolCall",N.item.id);z.push(e.jsx("div",{children:e.jsx(De,{content:S,isStreaming:!1,showEmpty:!1,sources:n.sources??[]})},`text-before-${M}`))}}if(N.type==="hookNotification")R(),z.push(e.jsx(Mt,{notification:N.item},N.item.id));else{const S=N.item;S.title==="todo_write"?(R(),W=[S],R()):S.batchId?K===S.batchId?W.push(S):(R(),K=S.batchId,D=S.title,W=[S]):D===S.title&&!K?W.push(S):(R(),D=S.title,W=[S])}H=T,_===C.length-1&&R()}),H<n.content.length){const N=n.content.slice(H);N&&z.push(e.jsx("div",{children:e.jsx(De,{content:N,isStreaming:n.isStreaming,showEmpty:!1,sources:n.sources??[]})},"text-end"))}return A.length>0&&(A.length>1?z.push(e.jsx(_e,{toolCalls:A,isGrouped:!0},`selecting-group-${A[0]?.id}`)):z.push(e.jsx("div",{children:e.jsx(_e,{toolCalls:[A[0]],isGrouped:!1})},`tool-${A[0]?.id}`))),e.jsx(e.Fragment,{children:z})})():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((j,v)=>e.jsx("img",{src:`data:${j.mimeType};base64,${j.data}`,alt:`Attachment ${v+1}`,className:"max-w-[200px] max-h-[200px] rounded-lg object-cover"},`image-${j.mimeType}-${j.data.slice(0,20)}`))}),n.content&&e.jsx("div",{className:"whitespace-pre-wrap",children:n.content})]})]})}return e.jsx("div",{ref:m,className:b(wl({role:p,variant:s}),g&&"animate-pulse-subtle",l),...c,children:h})});na.displayName="MessageContent";const aa=i.forwardRef(({showIcons:t=!0,visibleTabs:s=["todo","files"],variant:a="default",className:n,...o},l)=>{const c=[{id:"todo",label:"To-do",icon:jt},{id:"files",label:"Files",icon:$e},{id:"database",label:"Database",icon:Vs},{id:"sources",label:"Sources",icon:qs},{id:"settings",label:"Settings",icon:$t}].filter(u=>s.includes(u.id)),m=a==="compact"?"gap-[4px]":"gap-3";return e.jsx(Ke,{ref:l,className:b("w-full justify-start bg-transparent p-0 h-auto",m,n),...o,children:c.map(u=>{const d=u.icon;return e.jsxs(Ye,{value:u.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&&d&&e.jsx(d,{className:"size-4"}),u.label]},u.id)})})});aa.displayName="PanelTabsHeader";const jl=i.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(Ds,{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(Ia,{asChild:!0,children:e.jsx(io,{className:"h-4 w-4 opacity-50"})})]}));jl.displayName=Ds.displayName;const oa=i.forwardRef(({className:t,...s},a)=>e.jsx(Us,{ref:a,className:b("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(lo,{className:"h-4 w-4"})}));oa.displayName=Us.displayName;const ra=i.forwardRef(({className:t,...s},a)=>e.jsx(zs,{ref:a,className:b("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(le,{className:"h-4 w-4"})}));ra.displayName=zs.displayName;const Nl=i.forwardRef(({className:t,children:s,position:a="popper",...n},o)=>e.jsx(Ra,{children:e.jsxs($s,{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(oa,{}),e.jsx(_a,{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(ra,{})]})}));Nl.displayName=$s.displayName;const Sl=i.forwardRef(({className:t,...s},a)=>e.jsx(Ls,{ref:a,className:b("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));Sl.displayName=Ls.displayName;const Cl=i.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(Os,{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(Ma,{children:e.jsx(bt,{className:"h-4 w-4"})})}),e.jsx(Ea,{children:s})]}));Cl.displayName=Os.displayName;const kl=i.forwardRef(({className:t,...s},a)=>e.jsx(Fs,{ref:a,className:b("-mx-1 my-1 h-px bg-muted",t),...s}));kl.displayName=Fs.displayName;const Tl=Es,ia=i.forwardRef(({className:t,...s},a)=>e.jsx(ft,{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}));ia.displayName=ft.displayName;const Il=we("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"}}),Rl=i.forwardRef(({side:t="right",className:s,children:a,...n},o)=>e.jsxs(Tl,{children:[e.jsx(ia,{}),e.jsxs(gt,{ref:o,className:b(Il({side:t}),s),...n,children:[a,e.jsxs(As,{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(vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Rl.displayName=gt.displayName;const _l=i.forwardRef(({className:t,...s},a)=>e.jsx(ht,{ref:a,className:b("text-lg font-semibold text-foreground",t),...s}));_l.displayName=ht.displayName;const Ml=i.forwardRef(({className:t,...s},a)=>e.jsx(xt,{ref:a,className:b("text-sm text-muted-foreground",t),...s}));Ml.displayName=xt.displayName;function El({className:t}){const{toggleSidebar:s,open:a}=ke();return e.jsx(Ce,{className:b(t),"data-testid":"sidebar-toggle-button","data-state":a?"open":"closed",onClick:s,"aria-label":"Toggle sidebar",children:e.jsx(co,{className:"size-4 text-muted-foreground"})})}const la=i.forwardRef(({task:t,collapsible:s=!0,defaultExpanded:a=!1,onTaskClick:n,className:o,...l},r)=>{const[c,m]=i.useState(a),u=!!(t.details||t.files&&t.files.length>0),d={pending:yt,in_progress:Lt,completed:wt}[t.status],p=()=>{switch(t.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},g=()=>{u&&s&&m(!c),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),...l,children:[e.jsxs("button",{type:"button",onClick:g,className:b("w-full flex items-center gap-3 px-3 py-2.5 text-left",u&&s&&"cursor-pointer"),disabled:!u&&!s,children:[e.jsx(d,{className:b("w-4 h-4 shrink-0",p(),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}),u&&s&&e.jsx(le,{className:b("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",c&&"rotate-180"),"aria-hidden":"true"})]}),u&&c&&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))})]})]})]})});la.displayName="Subagent";const Al=i.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:a,emptyMessage:n="No subagents yet.",className:o,...l},r)=>e.jsx("div",{ref:r,className:b("space-y-2 max-h-96 overflow-y-auto",o),...l,children:t.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:n}):t.map(c=>e.jsx(la,{task:c,collapsible:s,...a?{onTaskClick:a}:{}},c.id))}));Al.displayName="SubagentList";const Pl=we("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"}}),Dl=i.forwardRef(({className:t,autoResize:s=!1,maxHeight:a=200,variant:n,...o},l)=>{const r=i.useRef(null),c=i.useCallback(u=>{r.current=u,typeof l=="function"?l(u):l&&(l.current=u)},[l]),m=i.useCallback(()=>{const u=r.current;if(!u||!s)return;u.style.height="auto";const d=Math.min(u.scrollHeight,a);u.style.height=`${d}px`,u.scrollHeight>a?u.style.overflowY="auto":u.style.overflowY="hidden"},[s,a]);return i.useEffect(()=>{m()},[m]),e.jsx("textarea",{className:b(Pl({variant:n}),s&&"overflow-y-hidden",t),ref:c,...o})});Dl.displayName="Textarea";function Ul(){return"http://localhost:3100"}const bs={agentServerUrl:Ul(),debuggerUrl:void 0};function zl(){const{client:t,error:s,sessionId:a}=Ko({serverUrl:bs.agentServerUrl});return e.jsx(Zr,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(Ui,{client:t,initialSessionId:a,error:s,...bs.debuggerUrl})})}const $l="bibliotecha_auth";function Ll(t){return document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`))?.[2]??null}async function Ol(){new URLSearchParams(window.location.search).get("token"),Ll($l);const s=document.getElementById("root");if(!s)throw new Error("Root element not found");ua.createRoot(s).render(e.jsx(Pt.StrictMode,{children:e.jsx(zl,{})}))}Ol();