@townco/gui-template 0.1.114 → 0.1.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- import{r as l,j as e,M as ya,c as et,h as va}from"./react-DiSrVJhY.js";import{bb as $e,bc as wa,bd as os,be as ie,bf as q,bg as w,bh as ee,bi as F,bj as ae,bk as de,bl as it,bm as vt,bn as te,bo as Ne,bp as Bt,bq as ja,br as Na,bs as Ca,bt as Sa,bu as Te,bv as ka,bw as me,am as Ta,bx as Ia,by as rs}from"./vendor-Dm9xAZV8.js";import{P as is,a as Ra}from"./acp-sdk-D4VsTV6L.js";import{S as ye,P as _a,C as _s,a as Ma,R as Ea,T as Aa,b as Ms,c as Es,d as Pa,e as As,I as Ps,f as Ds,g as Us,h as zs,L as $s,i as Ls,j as Da,k as Ua,l as Os,m as Fs,n as Bs,o as za,O as Nt,p as Hs,q as Ct,r as Ws,s as St,D as kt,t as Vs,u as qs,v as $a,w as Ks,x as Ys,y as La,z as Qs,V as Oa,A as Gs,B as Xs,E as Fa,F as Ba,G as Js}from"./radix-BaZ_UeJz.js";import{c as tt,d as lt,e as Tt,P as Ha,E as Wa,S as Zs,f as en,g as Va,h as Ht,i as qa,j as Ka,k as Ya,l as Qa,m as fe,A as Ga,n as It,F as Xa,o as Ja,p as Za,q as eo,r as We,s as Rt,t as _t,G as tn,u as sn,v as nn,B as ls,w as to,x as so,y as no,z as Wt,H as ao,I as Vt,J as wt,T as oo,K as ce,N as ro,O as an,Q as cs,U as io,V as ds,W as at,Y as qt,_ as lo,$ as co,a0 as uo,a1 as mo,a2 as po,a3 as fo,a4 as go,a5 as ho,a6 as xo,a7 as bo,a8 as yo}from"./icons-B0Ax5AoZ.js";import{A as ot,m as ke}from"./framer-motion-DEDjTHcO.js";import{g as on}from"./markdown-jcH7_RT5.js";import"./katex-C5cjGaLm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();var vo={};const ht=typeof process<"u"&&process.versions?.node;let wo,jo=0;const $t=new Set;function No(t){return $t.add(t),()=>$t.delete(t)}function Co(t){for(const s of $t)s(t)}const us={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},So={trace:$e.TRACE,debug:$e.DEBUG,info:$e.INFO,warn:$e.WARN,error:$e.ERROR,fatal:$e.FATAL};class ko{service;minLevel;logsDir;enableConsoleOutput;constructor(s,n="debug"){this.service=s,this.minLevel=n,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&vo?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){this.logsDir}shouldLog(s){return us[s]>=us[this.minLevel]}log(s,n,o){if(!this.shouldLog(s))return;const r={id:`log_${++jo}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:n,...o&&{metadata:o}};if(Co(r),ht&&this.logsDir,ht&&this.logsDir){const c={timestamp:r.timestamp,level:r.level,service:r.service,message:r.message,...r.metadata&&{metadata:r.metadata}};this.writeToFile(JSON.stringify(c)).catch(()=>{})}if(ht&&this.enableConsoleOutput){const c=r.timestamp,u=r.level.toUpperCase().padEnd(5),d=`[${this.service}]`,m=r.metadata?` ${JSON.stringify(r.metadata)}`:"";console.log(`${c} ${u} ${d} ${r.message}${m}`)}const i=wa.getLogger(this.service),a=os.trace.getSpan(os.context.active());i.emit({severityNumber:So[s],severityText:s.toUpperCase(),body:n,attributes:{service:this.service,...o&&Object.fromEntries(Object.entries(o).map(([c,u])=>[`log.${c}`,typeof u=="object"?JSON.stringify(u):u])),...a&&{trace_id:a.spanContext().traceId,span_id:a.spanContext().spanId}}})}trace(s,n){this.log("trace",s,n)}debug(s,n){this.log("debug",s,n)}info(s,n){this.log("info",s,n)}warn(s,n){this.log("warn",s,n)}error(s,n){this.log("error",s,n)}fatal(s,n){this.log("fatal",s,n)}}function ue(t,s="debug"){return new ko(t,s)}const rn=ie(["user","assistant","system","tool"]),To=ie(["text","image","file","tool_call","tool_result"]),ct=q({type:To}),Io=ct.extend({type:ee("text"),text:w()}),Ro=ct.extend({type:ee("image"),url:w().url().optional(),source:q({type:ee("base64"),media_type:ie(["image/jpeg","image/png","image/gif","image/webp"]),data:w()}).optional()}),_o=ct.extend({type:ee("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:F().optional()}),Mo=ct.extend({type:ee("tool_call"),id:w(),name:w(),arguments:ae(w(),de())}),Eo=ct.extend({type:ee("tool_result"),callId:w(),result:de(),error:w().optional()}),ln=it("type",[Io,Ro,_o,Mo,Eo]),cn=q({id:w(),role:rn,content:te(ln),timestamp:vt(),metadata:ae(w(),de()).optional()}),Ao=q({type:ee("content"),id:w(),role:rn,contentDelta:ln,isComplete:Ne(),tokenUsage:q({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}).optional(),contextInputTokens:F().optional(),_meta:q({context_size:q({systemPromptTokens:F(),userMessagesTokens:F(),assistantMessagesTokens:F(),toolInputTokens:F(),toolResultsTokens:F(),totalEstimated:F(),llmReportedInputTokens:F().optional()}).optional()}).optional()}),Po=q({type:ee("tool_call"),id:w(),toolCall:Bt(),messageId:w().optional()}),Do=q({type:ee("tool_call_update"),id:w(),toolCallUpdate:Bt(),messageId:w().optional()}),Mt=ie(["context_size","tool_response"]),Uo=q({type:ee("hook_triggered"),hookType:Mt,threshold:F(),currentPercentage:F(),callback:w(),triggeredAt:F().optional(),toolCallId:w().optional()}),zo=q({type:ee("hook_completed"),hookType:Mt,callback:w(),metadata:q({action:w().optional(),messagesRemoved:F().optional(),tokensSaved:F().optional()}).passthrough().optional(),completedAt:F().optional(),toolCallId:w().optional()}),$o=q({type:ee("hook_error"),hookType:Mt,callback:w(),error:w(),completedAt:F().optional(),toolCallId:w().optional()}),Lo=it("type",[Uo,zo,$o]),Oo=q({type:ee("hook_notification"),id:w(),notification:Lo,messageId:w().optional()}),dn=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),Fo=q({type:ee("sources"),sources:te(dn)});it("type",[Ao,Po,Do,Oo,Fo]);const Bo=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),ms=q({systemPromptTokens:F(),toolOverheadTokens:F().optional(),mcpOverheadTokens:F().optional(),userMessagesTokens:F(),assistantMessagesTokens:F(),toolInputTokens:F(),toolResultsTokens:F(),totalEstimated:F(),llmReportedInputTokens:F().optional(),modelContextWindow:F().optional()}),Kt=ie(["pending","in_progress","completed","failed"]),Ho=ie(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),un=q({path:w(),line:F().nullable().optional()}),Yt=q({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}),Qt=it("type",[q({type:ee("content"),content:q({type:ee("text"),text:w()})}),q({type:ee("text"),text:w()}),q({type:ee("image"),data:w(),mimeType:w().optional(),alt:w().optional()}),q({type:ee("image"),url:w(),alt:w().optional()}),q({type:ee("diff"),path:w(),oldText:w(),newText:w(),line:F().nullable().optional()}),q({type:ee("terminal"),terminalId:w()})]),mn=q({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),status:Kt,content:te(Qt).optional()}),Wo=it("type",[q({type:ee("text"),text:w()}),q({type:ee("tool_call"),toolCall:mn})]),pn=q({id:w(),content:w(),toolCalls:te(mn).optional(),contentBlocks:te(Wo).optional(),isStreaming:Ne().optional(),context_size:ms.optional(),_meta:q({semanticName:w().optional(),agentDefinitionName:w().optional(),currentActivity:w().optional(),statusGenerating:Ne().optional(),context_size:ms.optional()}).passthrough().optional()}),fn=q({id:w(),batchId:w().optional(),title:w(),prettyName:w().optional(),icon:w().optional(),verbiage:q({active:w(),past:w(),paramKey:w().optional()}).optional(),subline:w().optional(),kind:Ho,status:Kt,contentPosition:F().optional(),locations:te(un).optional(),rawInput:ae(w(),de()).optional(),rawOutput:ae(w(),de()).optional(),content:te(Qt).optional(),error:w().optional(),startedAt:F().optional(),completedAt:F().optional(),tokenUsage:Yt.optional(),_meta:q({truncationWarning:w().optional(),compactionAction:ie(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(pn).optional(),subagentStreaming:Ne().optional(),subagentCompleted:Ne().optional()}),Vo=q({id:w(),status:Kt.optional(),title:w().optional(),prettyName:w().optional(),icon:w().optional(),batchId:w().optional(),rawInput:ae(w(),de()).optional(),locations:te(un).optional(),rawOutput:ae(w(),de()).optional(),content:te(Qt).optional(),error:w().optional(),completedAt:F().optional(),tokenUsage:Yt.optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(pn).optional(),subagentCompleted:Ne().optional(),_meta:q({truncationWarning:w().optional(),compactionAction:ie(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional()});function ps(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,subagentCompleted:s.subagentCompleted??t.subagentCompleted,_meta:s._meta??t._meta}}const qo=q({mimeType:w(),data:w()}),Ko=q({id:w(),hookType:Mt,callback:w(),status:ie(["triggered","completed","error"]),threshold:F().optional(),currentPercentage:F().optional(),metadata:q({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()}),Yo=q({id:w(),role:ie(["user","assistant","system"]),content:w(),timestamp:vt(),isStreaming:Ne().default(!1),streamingStartTime:F().optional(),metadata:ae(w(),de()).optional(),toolCalls:te(fn).optional(),hookNotifications:te(Ko).optional(),tokenUsage:Yt.optional(),images:te(qo).optional(),sources:te(Bo).optional()}),Qo=q({value:w(),isSubmitting:Ne(),attachedFiles:te(q({name:w(),path:w(),size:F(),mimeType:w(),data:w()})),selectedPromptParameters:ae(w(),w()).optional()});q({sessionId:w().nullable(),isConnected:Ne(),isStreaming:Ne(),messages:te(Yo),input:Qo,error:w().nullable()});ie(["disconnected","connecting","connected","error"]);let fs=0,gs=0;function we(t){const s=Date.now();s!==gs&&(fs=0,gs=s);const n=fs++,o=Math.random().toString(36).substring(2,7);return`msg_${s}_${n}_${o}_${t}`}const Go=q({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:ae(w(),w()).optional()}),L=ue("http-transport");class Xo{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;pendingReplayUpdates=[];agentInfo;constructor(s){const n=Go.safeParse(s);if(!n.success){const o=n.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ");throw new Error(`Invalid HTTP transport configuration: ${o}`)}this.options={...s,baseUrl:s.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const s={protocolVersion:is,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",s);if(n.agentInfo){const i=n._meta,a=i&&typeof i=="object",c=a&&"agentDescription"in i?String(i.agentDescription):void 0,u=a&&"suggestedPrompts"in i&&Array.isArray(i.suggestedPrompts)?i.suggestedPrompts:void 0,d=a&&"tools"in i&&Array.isArray(i.tools)?i.tools:void 0,m=a&&"mcps"in i&&Array.isArray(i.mcps)?i.mcps:void 0,p=a&&"subagents"in i&&Array.isArray(i.subagents)?i.subagents:void 0,g=a&&"initialMessage"in i&&i.initialMessage&&typeof i.initialMessage=="object"?i.initialMessage:void 0,x=a&&"uiConfig"in i&&i.uiConfig&&typeof i.uiConfig=="object"?i.uiConfig:void 0,h=a&&"promptParameters"in i&&Array.isArray(i.promptParameters)?i.promptParameters:void 0;this.agentInfo={name:n.agentInfo.name,...n.agentInfo.title?{displayName:n.agentInfo.title}:{},version:n.agentInfo.version,...c?{description:c}:{},...u?{suggestedPrompts:u}:{},...g?{initialMessage:g}:{},...x?{uiConfig:x}:{},...d?{tools:d}:{},...m?{mcps:m}:{},...p?{subagents:p}:{},...h?{promptParameters:h}:{}}}L.info("ACP connection initialized",{initResponse:n});const o={cwd:"/",mcpServers:[]},r=await this.sendRpcRequest("session/new",o);this.currentSessionId=r.sessionId,L.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(s){this.connected=!1;const n=s instanceof Error?s:new Error(String(s));throw this.notifyError(n),n}}async loadSession(s){this.connected&&(L.warn("Transport already connected, disconnecting first",{sessionId:s}),await this.disconnect());try{this.abortController=new AbortController;const n={protocolVersion:is,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};L.info("Loading session - initializing connection",{sessionId:s});const o=await this.sendRpcRequest("initialize",n);if(o.agentInfo){const a=o._meta,c=a&&typeof a=="object",u=c&&"agentDescription"in a?String(a.agentDescription):void 0,d=c&&"suggestedPrompts"in a&&Array.isArray(a.suggestedPrompts)?a.suggestedPrompts:void 0,m=c&&"tools"in a&&Array.isArray(a.tools)?a.tools:void 0,p=c&&"mcps"in a&&Array.isArray(a.mcps)?a.mcps:void 0,g=c&&"subagents"in a&&Array.isArray(a.subagents)?a.subagents:void 0,x=c&&"initialMessage"in a&&a.initialMessage&&typeof a.initialMessage=="object"?a.initialMessage:void 0,h=c&&"uiConfig"in a&&a.uiConfig&&typeof a.uiConfig=="object"?a.uiConfig:void 0,f=c&&"promptParameters"in a&&Array.isArray(a.promptParameters)?a.promptParameters:void 0;this.agentInfo={name:o.agentInfo.name,...o.agentInfo.title?{displayName:o.agentInfo.title}:{},version:o.agentInfo.version,...u?{description:u}:{},...d?{suggestedPrompts:d}:{},...x?{initialMessage:x}:{},...h?{uiConfig:h}:{},...m?{tools:m}:{},...p?{mcps:p}:{},...g?{subagents:g}:{},...f?{promptParameters:f}:{}}}if(!o.agentCapabilities?.loadSession)throw L.error("Agent does not support loading sessions",{capabilities:o.agentCapabilities}),new Error("Agent does not support loading sessions");L.info("ACP connection initialized, loading session",{sessionId:s,capabilities:o.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=s,await this.connectSSE();const r={sessionId:s,cwd:"/",mcpServers:[]};L.info("Sending session/load request",{loadRequest:r});const i=await this.sendRpcRequest("session/load",r);L.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:i}),this.connected=!0,this.reconnectAttempts=0}catch(n){this.connected=!1;const o=n instanceof Error?n:new Error(String(n));throw L.error("Failed to load session",{sessionId:s,error:o.message,stack:o.stack}),this.notifyError(o),o}}async listSessions(){try{const s={method:"GET"};this.options.headers&&(s.headers=this.options.headers);const n=await fetch(`${this.options.baseUrl}/sessions`,s);if(!n.ok)throw new Error(`HTTP ${n.status}: ${await n.text()}`);return(await n.json()).sessions||[]}catch(s){return 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 n=s instanceof Error?s:new Error(String(s));throw this.notifyError(n),n}}async send(s,n){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");this.isInReplayMode&&(L.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const o=s.content.map(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),r={sessionId:this.currentSessionId,prompt:o};n?.promptParameters&&(r._meta={promptParameters:n.promptParameters});const i=await this.sendRpcRequest("session/prompt",r);L.debug("Prompt sent",{promptResponse:i}),this.streamComplete=!0;const a=this.chunkResolvers.shift();a?a({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(o){this.streamComplete=!0;const r=o instanceof Error?o:new Error(String(o));throw this.notifyError(r),r}}async cancel(s){if(!this.connected){L.warn("Cannot cancel: transport not connected");return}const n=s||this.currentSessionId;if(!n){L.warn("Cannot cancel: no session ID");return}L.info("Cancelling session",{sessionId:n}),this.streamComplete=!0,this.messageQueue.length=0,await this.sendNotification("session/cancel",{sessionId:n});const o={type:"content",id:n,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0};for(;this.chunkResolvers.length>0;){const r=this.chunkResolvers.shift();r&&r(o)}}async editAndResend(s,n,o){if(!this.connected)throw new Error("Transport not connected");const r=s||this.currentSessionId;if(!r)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:r,messageIndex:n});const i={"Content-Type":"application/json",...this.options.headers},a=this.options.timeout??600*1e3,c=new AbortController,u=setTimeout(()=>c.abort(),a);try{const d=await fetch(`${this.options.baseUrl}/sessions/${r}/edit-and-resend`,{method:"POST",headers:i,body:JSON.stringify({messageIndex:n,prompt:o}),signal:c.signal});if(clearTimeout(u),!d.ok){const p=await d.text();throw new Error(`HTTP ${d.status}: ${p}`)}this.streamComplete=!0;const m=this.chunkResolvers.shift();m?m({type:"content",id:r,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:r,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(d){throw clearTimeout(u),this.streamComplete=!0,d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${a}ms`):d}}async*receive(){this.isReceivingMessages=!0;try{for(;!this.streamComplete;)if(this.messageQueue.length>0){const s=this.messageQueue.shift();if(s&&(yield s,s.type==="content"&&s.isComplete))return}else{const s=await new Promise(n=>{this.chunkResolvers.push(n)});if(s.type==="content"&&s.isComplete){yield s;return}else yield s}for(;this.messageQueue.length>0;){const s=this.messageQueue.shift();s&&(yield s)}yield{type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}finally{this.isReceivingMessages=!1}}isConnected(){return this.connected}onSessionUpdate(s){if(this.sessionUpdateCallbacks.add(s),this.pendingReplayUpdates.length>0){L.info("Replaying queued session updates to ALL callbacks",{count:this.pendingReplayUpdates.length,callbackCount:this.sessionUpdateCallbacks.size,updateTypes:this.pendingReplayUpdates.map(o=>o.type),updateDetails:this.pendingReplayUpdates.map(o=>{if(o.type==="tool_call")return{type:"tool_call",toolCallId:o.toolCall?.id};if(o.type==="sources")return{type:"sources",count:o.sources?.length,ids:o.sources?.map(r=>r.id)};if(o.type==="generic"&&o.message){const r=o.message.content?.[0];return{type:"message",role:o.message.role,contentLength:r?.type==="text"?r.text?.length:0}}return{type:o.type}})});const n=[...this.pendingReplayUpdates];this.pendingReplayUpdates=[],setTimeout(()=>{L.info("Starting replay of queued updates to all callbacks",{updateCount:n.length,callbackCount:this.sessionUpdateCallbacks.size});for(const o of n)try{L.info("Replaying update to all callbacks",{type:o.type}),this.notifySessionUpdate(o)}catch(r){L.error("Error replaying session update",{error:r})}L.info("Finished replay of queued updates")},0)}return()=>{this.sessionUpdateCallbacks.delete(s)}}onError(s){return this.errorCallbacks.add(s),()=>{this.errorCallbacks.delete(s)}}onFileSystemChange(s,n){return L.debug("Registering file system change callback",{sessionId:s}),this.fileSystemChangeCallbacks.set(s,n),()=>{L.debug("Unregistering file system change callback",{sessionId:s}),this.fileSystemChangeCallbacks.delete(s)}}notifyFileSystemChange(s){const n=this.fileSystemChangeCallbacks.get(s.sessionId);L.debug("notifyFileSystemChange",{sessionId:s.sessionId,hasCallback:!!n,callbackCount:this.fileSystemChangeCallbacks.size}),n&&n(s)}getAgentInfo(){return this.agentInfo||{}}async sendNotification(s,n){const o={jsonrpc:"2.0",method:s,params:n};L.debug("Sending notification",{method:s,params:n});const r={"Content-Type":"application/json",...this.options.headers};try{const i=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:r,body:JSON.stringify(o)});if(!i.ok){const a=await i.text();L.error("Notification failed",{status:i.status,errorText:a})}}catch(i){L.error("Error sending notification",{error:i})}}async sendRpcRequest(s,n){const r={jsonrpc:"2.0",id:this.generateRequestId(),method:s,params:n};L.debug("Sending RPC request",{method:s,params:n,request:r});const i={"Content-Type":"application/json",...this.options.headers},a=this.options.timeout??600*1e3,c=new AbortController,u=setTimeout(()=>c.abort(),a);try{const d=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(r),signal:c.signal});if(clearTimeout(u),!d.ok){const p=await d.text();throw new Error(`HTTP ${d.status}: ${p}`)}const m=await d.json();if(m.error)throw new Error(`ACP error: ${m.error.message||JSON.stringify(m.error)}`);return m.result||m}catch(d){throw clearTimeout(u),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${a}ms`):d}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const s=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const o=await fetch(s,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!o.ok)throw new Error(`SSE connection failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response body is null");L.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const r=o.body.getReader(),i=new TextDecoder;let a="";(async()=>{try{for(;;){const{done:c,value:u}=await r.read();if(c){L.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}a+=i.decode(u,{stream:!0});const d=a.split(`
2
- `);a=d.pop()||"";let m={event:"message",data:""};for(const p of d)p.startsWith("event:")?m.event=p.substring(6).trim():p.startsWith("data:")?m.data=p.substring(5).trim():p===""&&(m.event==="message"&&m.data&&this.handleSSEMessage(m.data),m={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(o){throw L.error("SSE connection error",{error:o}),o}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const n=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(n),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const 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(n=>setTimeout(n,s));try{await this.connectSSE(),L.info("SSE reconnected successfully"),this.reconnecting=!1}catch(n){L.error("SSE reconnection failed",{error:n}),this.reconnecting=!1}}handleSSEMessage(s){try{const n=JSON.parse(s);if(L.debug("Received SSE message",{message:n}),n&&typeof n=="object"&&n.method==="session/update"&&n.params?.update?.sessionUpdate==="sources"){try{this.handleSessionNotification(n.params)}catch(a){L.error("Error in handleSessionNotification for sources",{error:a})}return}const r=Ra.safeParse(n);if(!r.success){L.error("Invalid ACP message from SSE",{issues:r.error.issues});return}const i=r.data;L.debug("Parsed ACP message",{method:"method"in i?i.method:"(no method)"}),"method"in i&&i.method==="session/update"&&(L.debug("Received session/update notification"),"params"in i&&i.params&&(L.debug("Calling handleSessionNotification",{params:i.params}),this.handleSessionNotification(i.params)))}catch(n){L.error("Error parsing SSE message",{error:n}),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(s){const r=s.update?.sessionUpdate==="sources";if(this.streamComplete&&!r){L.debug("Skipping session notification - stream complete/cancelled");return}L.debug("handleSessionNotification called",{params:s});const a=s.update,c=this.currentSessionId||s.sessionId;if(L.warn("📥 SSE UPDATE RECEIVED",{sessionUpdate:a?.sessionUpdate,hasUpdate:!!a,isInReplayMode:this.isInReplayMode,callbackCount:this.sessionUpdateCallbacks.size}),a?.sessionUpdate==="sandbox_files_changed"){const d=a;d._meta?.isReplay===!0||(L.debug("Sandbox files changed",{paths:d.paths,source:d._meta?.source}),this.notifyFileSystemChange({sessionId:c,...d.paths&&{paths:d.paths},...d._meta?.source&&{source:d._meta.source}}));return}if(a?.sessionUpdate==="tool_call"){L.debug("Tool call notification",{tokenUsage:a.tokenUsage});const d=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,m=a._meta&&typeof a._meta=="object"&&"prettyName"in a._meta&&typeof a._meta.prettyName=="string"?a._meta.prettyName:void 0,p=a._meta&&typeof a._meta=="object"&&"icon"in a._meta&&typeof a._meta.icon=="string"?a._meta.icon:void 0,g=a._meta&&typeof a._meta=="object"&&"subline"in a._meta&&typeof a._meta.subline=="string"?a._meta.subline:void 0,x=a._meta&&typeof a._meta=="object"&&"batchId"in a._meta&&typeof a._meta.batchId=="string"?a._meta.batchId:void 0,h=a._meta&&typeof a._meta=="object"&&"subagentPort"in a._meta&&typeof a._meta.subagentPort=="number"?a._meta.subagentPort:void 0,f=a._meta&&typeof a._meta=="object"&&"subagentSessionId"in a._meta&&typeof a._meta.subagentSessionId=="string"?a._meta.subagentSessionId:void 0,b=a._meta&&typeof a._meta=="object"&&"subagentMessages"in a._meta&&Array.isArray(a._meta.subagentMessages)?a._meta.subagentMessages:void 0,N=a._meta&&typeof a._meta=="object"&&"compactionAction"in a._meta&&typeof a._meta.compactionAction=="string"?a._meta.compactionAction:void 0,v=a._meta&&typeof a._meta=="object"&&"originalTokens"in a._meta&&typeof a._meta.originalTokens=="number"?a._meta.originalTokens:void 0,C=a._meta&&typeof a._meta=="object"&&"finalTokens"in a._meta&&typeof a._meta.finalTokens=="number"?a._meta.finalTokens:void 0,U=a._meta&&typeof a._meta=="object"&&"originalContentPreview"in a._meta&&typeof a._meta.originalContentPreview=="string"?a._meta.originalContentPreview:void 0,B=a._meta&&typeof a._meta=="object"&&"originalContentPath"in a._meta&&typeof a._meta.originalContentPath=="string"?a._meta.originalContentPath:void 0,D={id:a.toolCallId??"",batchId:x,title:a.title??"",prettyName:m,icon:p,subline:g,kind:a.kind||"other",status:a.status||"pending",locations:a.locations,rawInput:a.rawInput,tokenUsage:a.tokenUsage,content:a.content?.map(M=>{if(typeof M!="object"||M===null)return{type:"text",text:""};const E=M;if(E.type==="content"&&typeof E.content=="object"&&E.content!==null){const K=E.content;if(K.type==="text")return{type:"content",content:{type:"text",text:typeof K.text=="string"?K.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:""}}),startedAt:Date.now(),subagentPort:h,subagentSessionId:f,subagentMessages:b,_meta:N||v||C||U||B?{compactionAction:N,originalTokens:v,finalTokens:C,originalContentPreview:U,originalContentPath:B}:void 0},I={type:"tool_call",sessionId:c,status:"active",toolCall:D,messageId:d},_=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0;if(L.info("Creating tool_call session update",{toolCallId:D.id,title:D.title,hasSubagentPort:!!h,hasSubagentSessionId:!!f,hasSubagentMessages:!!b,subagentMessagesCount:b?.length,isReplay:_,isInReplayMode:this.isInReplayMode}),_||this.isInReplayMode)this.sessionUpdateCallbacks.size===0?(L.debug("Queueing tool_call for late-subscribing callbacks",{toolCallId:D.id}),this.pendingReplayUpdates.push(I)):this.notifySessionUpdate(I);else{const M={type:"tool_call",id:c,toolCall:D,messageId:d},E=this.chunkResolvers.shift();E?E(M):this.messageQueue.push(M)}}else if(a?.sessionUpdate==="tool_call_update"){const d=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,m=a._meta&&typeof a._meta=="object"&&"prettyName"in a._meta&&typeof a._meta.prettyName=="string"?a._meta.prettyName:void 0,p=a._meta&&typeof a._meta=="object"&&"icon"in a._meta&&typeof a._meta.icon=="string"?a._meta.icon:void 0,g=a._meta&&typeof a._meta=="object"&&"batchId"in a._meta&&typeof a._meta.batchId=="string"?a._meta.batchId:void 0,x=a._meta&&typeof a._meta=="object"&&"subagentPort"in a._meta&&typeof a._meta.subagentPort=="number"?a._meta.subagentPort:void 0,h=a._meta&&typeof a._meta=="object"&&"subagentSessionId"in a._meta&&typeof a._meta.subagentSessionId=="string"?a._meta.subagentSessionId:void 0,f=a._meta&&typeof a._meta=="object"&&"subagentMessages"in a._meta&&Array.isArray(a._meta.subagentMessages)?a._meta.subagentMessages:void 0;(x||h||f)&&L.info("Extracted subagent info from tool_call_update",{toolCallId:a.toolCallId,subagentPort:x,subagentSessionId:h,subagentMessagesCount:f?.length});const b=a._meta&&typeof a._meta=="object"&&"compactionAction"in a._meta&&typeof a._meta.compactionAction=="string"?a._meta.compactionAction:void 0,N=a._meta&&typeof a._meta=="object"&&"originalTokens"in a._meta&&typeof a._meta.originalTokens=="number"?a._meta.originalTokens:void 0,v=a._meta&&typeof a._meta=="object"&&"finalTokens"in a._meta&&typeof a._meta.finalTokens=="number"?a._meta.finalTokens:void 0,C=a._meta&&typeof a._meta=="object"&&"originalContentPreview"in a._meta&&typeof a._meta.originalContentPreview=="string"?a._meta.originalContentPreview:void 0,U=a._meta&&typeof a._meta=="object"&&"originalContentPath"in a._meta&&typeof a._meta.originalContentPath=="string"?a._meta.originalContentPath:void 0,B="subagentCompleted"in a&&typeof a.subagentCompleted=="boolean"?a.subagentCompleted:a._meta&&typeof a._meta=="object"&&"subagentCompleted"in a._meta&&typeof a._meta.subagentCompleted=="boolean"?a._meta.subagentCompleted:void 0,D={id:a.toolCallId??"",status:a.status,title:a.title,prettyName:m,icon:p,batchId:g,rawInput:a.rawInput,locations:a.locations,rawOutput:a.rawOutput,tokenUsage:a.tokenUsage,subagentCompleted:B,content:a.content?.map(_=>{if(typeof _!="object"||_===null)return{type:"text",text:""};const M=_;if(M.type==="content"&&typeof M.content=="object"&&M.content!==null){const E=M.content;if(E.type==="text")return{type:"content",content:{type:"text",text:typeof E.text=="string"?E.text:""}}}return M.type==="text"?{type:"text",text:typeof M.text=="string"?M.text:""}:M.type==="diff"?{type:"diff",path:typeof M.path=="string"?M.path:"",oldText:typeof M.oldText=="string"?M.oldText:"",newText:typeof M.newText=="string"?M.newText:"",line:typeof M.line=="number"?M.line:null}:M.type==="terminal"?{type:"terminal",terminalId:typeof M.terminalId=="string"?M.terminalId:""}:{type:"text",text:""}}),error:a.error,completedAt:a.status==="completed"||a.status==="failed"?Date.now():void 0,subagentPort:x,subagentSessionId:h,subagentMessages:f,_meta:b||N||v||C||U?{compactionAction:b,originalTokens:N,finalTokens:v,originalContentPreview:C,originalContentPath:U}:void 0},I={type:"tool_call_update",sessionId:c,status:"active",toolCallUpdate:D,messageId:d};if(this.isInReplayMode)this.sessionUpdateCallbacks.size===0?(L.debug("Queueing tool_call_update for late-subscribing callbacks",{toolCallId:D.id}),this.pendingReplayUpdates.push(I)):this.notifySessionUpdate(I);else{const _={type:"tool_call_update",id:c,toolCallUpdate:D,messageId:d},M=this.chunkResolvers.shift();M?M(_):this.messageQueue.push(_)}L.debug("Processed tool_call_update",{sessionUpdate:I,isReplay:this.isInReplayMode})}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="hook_notification"){const d=a;L.debug("Received hook_notification",{id:d.id,notificationType:d.notification.type,hookType:d.notification.hookType});const m={type:"hook_notification",id:d.id,notification:d.notification,messageId:d.messageId},p=this.chunkResolvers.shift();p?p(m):this.messageQueue.push(m)}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="tool_output"){const d=a,m=d._meta&&typeof d._meta=="object"&&"messageId"in d._meta?String(d._meta.messageId):void 0,p={id:d.toolCallId??"",rawOutput:d.rawOutput,content:d.content?.map(x=>{if(typeof x!="object"||x===null)return{type:"text",text:""};const h=x;if(h.type==="content"&&typeof h.content=="object"&&h.content!==null){const f=h.content;if(f.type==="text")return{type:"content",content:{type:"text",text:typeof f.text=="string"?f.text:""}}}return h.type==="text"?{type:"text",text:typeof h.text=="string"?h.text:""}:h.type==="diff"?{type:"diff",path:typeof h.path=="string"?h.path:"",oldText:typeof h.oldText=="string"?h.oldText:"",newText:typeof h.newText=="string"?h.newText:"",line:typeof h.line=="number"?h.line:null}:h.type==="terminal"?{type:"terminal",terminalId:typeof h.terminalId=="string"?h.terminalId:""}:h.type==="image"?{type:"image",data:typeof h.data=="string"?h.data:"",mimeType:typeof h.mimeType=="string"?h.mimeType:"image/png",alt:typeof h.alt=="string"?h.alt:void 0}:{type:"text",text:""}})},g={type:"tool_call_update",sessionId:c,status:"active",toolCallUpdate:p,messageId:m};if(this.isInReplayMode)this.sessionUpdateCallbacks.size===0?(L.debug("Queueing tool_output for late-subscribing callbacks",{toolCallId:p.id}),this.pendingReplayUpdates.push(g)):this.notifySessionUpdate(g);else{const x={type:"tool_call_update",id:c,toolCallUpdate:p,messageId:m},h=this.chunkResolvers.shift();h?h(x):this.messageQueue.push(x)}L.debug("Queued tool_output as tool_call_update chunk",{sessionUpdate:g})}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="sources"){const d=a,m={type:"sources",sessionId:c,status:"active",sources:d.sources};if(this.isInReplayMode)this.sessionUpdateCallbacks.size===0?this.pendingReplayUpdates.push(m):this.notifySessionUpdate(m);else{const p={type:"sources",sources:d.sources},g=this.chunkResolvers.shift();g?g(p):this.messageQueue.push(p)}}else if(a?.sessionUpdate==="agent_message_chunk"){const d=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0;if(this.isInReplayMode&&!d)return;const m=a._meta&&typeof a._meta=="object"&&"tokenUsage"in a._meta?a._meta.tokenUsage:void 0,p=a._meta&&typeof a._meta=="object"&&"contextInputTokens"in a._meta&&typeof a._meta.contextInputTokens=="number"?a._meta.contextInputTokens:void 0,g=a._meta&&typeof a._meta=="object"&&"context_size"in a._meta?a._meta.context_size:void 0,x={type:"generic",sessionId:c,status:"active",_meta:a._meta},h=a.content;if(h&&typeof h=="object"){const b=h;let N=null;if(b.type==="text"&&typeof b.text=="string"&&(N={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:b.text},tokenUsage:m,contextInputTokens:p,_meta:g?{context_size:g}:void 0,isComplete:!1}),N){const v=this.chunkResolvers.shift();v?v(N):this.messageQueue.push(N)}if(N&&typeof b.text=="string"&&(d||!this.isReceivingMessages)){const v={type:"generic",sessionId:c,status:"active",message:{id:we("assistant"),role:"assistant",content:[{type:"text",text:b.text}],timestamp:new Date().toISOString()}};d&&this.sessionUpdateCallbacks.size===0?(L.debug("Queueing assistant message for late-subscribing callbacks",{textLength:b.text.length}),this.pendingReplayUpdates.push(v)):this.notifySessionUpdate(v)}}const f=x._meta&&"context_size"in x._meta;(!d||f)&&this.notifySessionUpdate(x)}else if(a?.sessionUpdate==="user_message_chunk"){L.debug("Received user_message_chunk",{update:a});const d=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0,m=a.content;if(m&&typeof m=="object"){const p=m;if(p.type==="text"&&typeof p.text=="string"){const g={type:"generic",sessionId:c,status:"active",message:{id:we("user"),role:"user",content:[{type:"text",text:p.text}],timestamp:new Date().toISOString()}};d&&this.sessionUpdateCallbacks.size===0?(L.debug("Queueing user message for late-subscribing callbacks",{textLength:p.text.length}),this.pendingReplayUpdates.push(g)):(L.debug("Notifying session update for user message"),this.notifySessionUpdate(g))}}}else{L.warn("⚠️ UNHANDLED SESSION UPDATE - falling through to generic",{sessionUpdate:a?.sessionUpdate,updateKeys:a?Object.keys(a):[],hasSources:a&&"sources"in a});const d={type:"generic",sessionId:c,status:"active"};this.notifySessionUpdate(d)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(s){for(const n of this.sessionUpdateCallbacks)try{n(s)}catch(o){L.error("Error in session update callback",{error:o})}}notifyError(s){for(const n of this.errorCallbacks)try{n(s)}catch(o){L.error("Error in error callback",{error:o})}}}class Jo{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 Zo{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 Le=ue("acp-client","debug");class er{constructor(s){this.config=s,this.transport=this.createTransport(),this.setupTransportListeners(),s.autoConnect&&this.connect().catch(n=>{Le.error("Failed to auto-connect",{error:n instanceof Error?n.message:String(n)})})}transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(s){const n="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(n){const c=new Date().toISOString(),u=this.transport.getAgentInfo?.()?.name,d={id:n,status:"connected",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:c,agentName:u}};return this.sessions.set(n,d),this.currentSessionId=n,n}const o=this.generateSessionId(),r=new Date().toISOString(),i=this.transport.getAgentInfo?.()?.name,a={id:o,status:"connecting",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:r,agentName:i}};return this.sessions.set(o,a),this.currentSessionId=o,this.updateSessionStatus(o,"connected"),o}async loadSession(s,n){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const o=new Date().toISOString(),r={id:s,status:"connecting",config:n?{...n,agentPath:n.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};if(this.sessions.set(s,r),this.currentSessionId=s,await this.transport.loadSession(s),this.transport.getAgentInfo){const i=this.transport.getAgentInfo();i.name&&r.metadata&&(r.metadata.agentName=i.name)}return this.updateSessionStatus(s,"connected"),s}async listSessions(){return this.transport.listSessions?this.transport.listSessions():[]}async sendMessage(s,n,o,r){const i=n||this.currentSessionId;if(!i)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(i);if(!a)throw new Error(`Session ${i} not found`);const c=[];if(o&&o.length>0)for(const d of o)d.mimeType.startsWith("image/")&&c.push({type:"image",source:{type:"base64",media_type:d.mimeType,data:d.data}});c.push({type:"text",text:s});const u={id:we("user"),role:"user",content:c,timestamp:new Date().toISOString()};a.messages.push(u),this.updateSessionStatus(i,"active"),await this.transport.send(u,r?{promptParameters:r}:void 0)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}async cancel(s){const n=s||this.currentSessionId;if(!n){Le.warn("Cannot cancel: no session ID");return}Le.info("Cancelling session",{sessionId:n}),await this.transport.cancel(n)}async editAndResend(s,n,o,r){const i=o||this.currentSessionId;if(!i)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 a=[];if(r&&r.length>0)for(const c of r)c.mimeType.startsWith("image/")&&a.push({type:"image",data:c.data,mimeType:c.mimeType});a.push({type:"text",text:n}),Le.info("Edit and resend",{sessionId:i,messageIndex:s}),await this.transport.editAndResend(i,s,a)}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,n){return this.transport&&"onFileSystemChange"in this.transport?this.transport.onFileSystemChange(s,n):()=>{}}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 Jo(this.config.options);case"http":return new Xo(this.config.options);case"websocket":return new Zo(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(s=>{this.handleSessionUpdate(s)}),this.transport.onError(s=>{this.handleError(s)})}handleSessionUpdate(s){if(s.sessionId){const n=this.sessions.get(s.sessionId);n&&(s.status&&(n.status=s.status),s.message&&n.messages.push(s.message),s.error&&(n.error=s.error))}for(const n of this.sessionUpdateHandlers)try{n(s)}catch(o){Le.error("Error in session update handler",{error:o instanceof Error?o.message:String(o)})}}handleError(s){for(const n of this.errorHandlers)try{n(s)}catch(o){Le.error("Error in error handler",{error:o instanceof Error?o.message:String(o)})}}updateSessionStatus(s,n){const o=this.sessions.get(s);o&&(o.status=n,this.handleSessionUpdate({sessionId:s,status:n}))}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}const Oe=ue("acp-client-hook");function tr(t){const[s,n]=l.useState(null),[o,r]=l.useState(null),[i,a]=l.useState(null);return l.useEffect(()=>{const u=new URLSearchParams(window.location.search).get("session");u&&(Oe.info("Session ID found in URL",{sessionId:u}),a(u));try{Oe.info("Initializing ACP client",{serverUrl:t.serverUrl});const d=new er({type:"http",options:{baseUrl:t.serverUrl}});return n(d),Oe.info("ACP client initialized successfully"),()=>{Oe.debug("Disconnecting ACP client"),d.disconnect().catch(m=>{Oe.error("Failed to disconnect ACP client",{error:m instanceof Error?m.message:String(m)})})}}catch(d){const m=d instanceof Error?d.message:"Failed to initialize ACP client";r(m),Oe.error("Failed to initialize ACP client",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0});return}},[t.serverUrl]),{client:s,error:o,sessionId:i}}const se=ue("chat-store","debug"),yt=[];function Et(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 xt={sessionId:null,toolCallId:null,todos:yt};const sr=t=>{const s=t.sessionId;if(!s)return yt;const o=(t.toolCalls[s]||[]).filter(a=>a.title==="todo_write").sort((a,c)=>(c.startedAt||0)-(a.startedAt||0));if(o.length===0)return yt;const r=o[0];if(!r?.rawInput?.todos||!Array.isArray(r.rawInput.todos))return yt;if(xt.sessionId===s&&xt.toolCallId===r.id)return xt.todos;const i=r.rawInput.todos.map((a,c)=>({id:`${r.id}-${c}`,text:a.status==="in_progress"?a.activeForm:a.content,status:a.status}));return xt={sessionId:s,toolCallId:r.id,todos:i},i},H=ja(t=>({connectionStatus:"disconnected",sessionId:null,error:null,messages:[],isStreaming:!1,streamingStartTime:null,sources:[],toolCalls:{},totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null,currentModel:"claude-sonnet-4-5-20250929",tokenDisplayMode:"context",logs:[],activeTab:"chat",input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:s=>t({connectionStatus:s}),setSessionId:s=>t({sessionId:s}),setError:s=>t({error:s}),addMessage:s=>t(n=>({messages:[...n.messages,s]})),updateMessage:(s,n)=>t(o=>{const r=o.messages.find(d=>d.id===s);let i=o.totalBilled,a=o.currentContext,c=n;if(n.tokenUsage){const d=r?.tokenUsage;se.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:d});const m={inputTokens:Math.max(n.tokenUsage.inputTokens??0,d?.inputTokens??0),outputTokens:Math.max(n.tokenUsage.outputTokens??0,d?.outputTokens??0),totalTokens:Math.max(n.tokenUsage.inputTokens??0,d?.inputTokens??0)+Math.max(n.tokenUsage.outputTokens??0,d?.outputTokens??0)};se.debug("updateMessage: merged tokenUsage",{merged:m}),c={...n,tokenUsage:m};const p=m.inputTokens-(d?.inputTokens??0),g=m.outputTokens-(d?.outputTokens??0),x=m.totalTokens-(d?.totalTokens??0);i={inputTokens:o.totalBilled.inputTokens+p,outputTokens:o.totalBilled.outputTokens+g,totalTokens:o.totalBilled.totalTokens+x},a={inputTokens:m.inputTokens,outputTokens:o.currentContext.outputTokens+g,totalTokens:m.totalTokens}}const u=o.messages.map(d=>d.id===s?{...d,...c}:d);if(n.tokenUsage&&c.tokenUsage){const d=r?.tokenUsage,m=c.tokenUsage,p=(m.inputTokens??0)-(d?.inputTokens??0),g=(m.outputTokens??0)-(d?.outputTokens??0),x=(m.totalTokens??0)-(d?.totalTokens??0),h=u.filter(N=>N.tokenUsage).map(N=>({id:N.id,role:N.role,tokens:N.tokenUsage})),f=u.reduce((N,v)=>({inputTokens:N.inputTokens+(v.tokenUsage?.inputTokens??0),outputTokens:N.outputTokens+(v.tokenUsage?.outputTokens??0),totalTokens:N.totalTokens+(v.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),b=f.inputTokens===i.inputTokens&&f.outputTokens===i.outputTokens&&f.totalTokens===i.totalTokens;se.debug("updateMessage: tokenUsage update",{messageId:s,updates:n.tokenUsage,existing:d,messageMax:m,delta:{inputDelta:p,outputDelta:g,totalDelta:x},totalBilled:i,currentContext:a,actualSum:f,billedCorrect:b?"✅":"❌",messageCount:u.length,messagesWithTokens:h.length,breakdown:h})}return{messages:u,totalBilled:i,currentContext:a}}),clearMessages:()=>t({messages:[],sources:[]}),addSources:s=>t(n=>{if(!s||s.length===0)return n;const o=new Map;for(const r of n.sources)o.set(r.id,r);for(const r of s)o.set(r.id,r);return{sources:Array.from(o.values())}}),setIsStreaming:s=>t({isStreaming:s}),setStreamingStartTime:s=>t({streamingStartTime:s}),addToolCall:(s,n)=>t(o=>({toolCalls:{...o.toolCalls,[s]:[...o.toolCalls[s]||[],n]}})),addToolCallToCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(u=>u.role==="assistant");if(o===-1){se.debug("No assistant message found, creating one for tool call at position 0");const u={id:we("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,toolCalls:[{...s,contentPosition:0}]};return{messages:[...n.messages,u]}}const r=[...n.messages],i=r[o];if(!i)return n;const a=i.content.length,c={...s,contentPosition:a};return r[o]={...i,toolCalls:[...i.toolCalls||[],c]},{messages:r}}),updateToolCallInCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(p=>p.role==="assistant");if(o===-1)return se.warn("No assistant message found to update tool call in"),n;const r=[...n.messages],i=r[o];if(!i)return n;const a=i.toolCalls||[],c=a.findIndex(p=>p.id===s.id);if(c===-1)return se.warn(`Tool call ${s.id} not found in message`),n;const u=a[c];if(!u)return n;const d=[...a],m=ps(u,s);return d[c]=m,r[o]={...i,toolCalls:d},{messages:r}}),addHookNotificationToCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(m=>m.role==="assistant");if(o===-1){se.debug("No assistant message found, creating one for hook notification");const m={...Et(s),contentPosition:0},p={id:we("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,hookNotifications:[m]};return{messages:[...n.messages,p]}}const r=[...n.messages],i=r[o];if(!i)return n;const a=i.hookNotifications||[],c=i.content.length;if(s.type==="hook_triggered"){se.debug("Adding hook_triggered notification for loading state",{hookType:s.hookType,callback:s.callback,contentPosition:c});const m={...Et(s),contentPosition:c},p=[...a,m];return r[o]={...i,hookNotifications:p},{messages:r}}let u;const d=a.findIndex(m=>m.hookType===s.hookType&&m.callback===s.callback&&m.status==="triggered");if(d!==-1){const m=a[d];u=[...a];const p=s.type==="hook_completed"||s.type==="hook_error"?s.completedAt??Date.now():Date.now();u[d]={...m,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}:{}},se.debug("Merged hook notification with triggered state",{hookType:s.hookType,status:u[d]?.status})}else{const m={...Et(s),contentPosition:c};u=[...a,m],se.debug("Added hook notification without prior triggered state",{hookType:s.hookType,callback:s.callback,contentPosition:c})}return r[o]={...i,hookNotifications:u},{messages:r}}),addSourcesToCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(c=>c.role==="assistant");if(o===-1){se.debug("No assistant message found, creating one for sources");const c={id:we("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,sources:s},u=new Map;for(const d of n.sources)u.set(d.id,d);for(const d of s)u.set(d.id,d);return{messages:[...n.messages,c],sources:[...u.values()]}}const r=[...n.messages],i=r[o];if(!i)return n;r[o]={...i,sources:[...i.sources||[],...s]},se.debug("Added sources to current message",{sourcesCount:s.length,totalSources:(i.sources?.length||0)+s.length});const a=new Map;for(const c of n.sources)a.set(c.id,c);for(const c of s)a.set(c.id,c);return{messages:r,sources:[...a.values()]}}),addSourcesByToolCallId:s=>t(n=>{se.info("addSourcesByToolCallId called",{sourcesCount:s.length,messagesCount:n.messages.length,sourceDetails:s.map(c=>({id:c.id,toolCallId:c.toolCallId,title:c.title?.slice(0,30)}))}),se.info("Current messages state",{messages:n.messages.map((c,u)=>({index:u,role:c.role,contentLength:c.content?.length||0,toolCallIds:c.toolCalls?.map(d=>d.id)||[],existingSources:c.sources?.length||0}))});const o=new Map;for(const c of s){if(!c.toolCallId){se.warn("Source missing toolCallId",{sourceId:c.id});continue}const u=o.get(c.toolCallId)||[];u.push(c),o.set(c.toolCallId,u)}if(o.size===0)return se.warn("No sources with toolCallId to distribute"),n;const r=[...n.messages];let i=0;for(const[c,u]of o){const d=r.findIndex(m=>m.role==="assistant"&&m.toolCalls?.some(p=>p.id===c));if(se.info("Looking for message with toolCallId",{toolCallId:c,foundIndex:d,sourcesCount:u.length}),d!==-1){const m=r[d];m&&(r[d]={...m,sources:[...m.sources||[],...u]},i+=u.length,se.info("Added sources to message",{messageIndex:d,messageId:m.id,toolCallId:c,sourcesAdded:u.length,totalSourcesNow:r[d]?.sources?.length,messageContentPreview:m.content.slice(0,100)}))}else{se.warn("Tool call not found in any message, using fallback",{toolCallId:c});const m=r.findLastIndex(p=>p.role==="assistant");if(m!==-1){const p=r[m];p&&(r[m]={...p,sources:[...p.sources||[],...u]},i+=u.length,se.info("Added sources to last assistant message (fallback)",{lastAssistantIndex:m,sourcesAdded:u.length}))}else se.error("No assistant message found to add sources to")}}se.info("Finished distributing sources",{totalSources:s.length,sourcesAdded:i,toolCallIds:Array.from(o.keys())});const a=new Map;for(const c of n.sources)a.set(c.id,c);for(const c of s)a.set(c.id,c);return{messages:r,sources:[...a.values()]}}),updateToolCall:(s,n)=>t(o=>{const r=o.toolCalls[s]||[],i=r.findIndex(u=>u.id===n.id);if(i===-1)return o;const a=r[i];if(!a)return o;const c=[...r];return c[i]=ps(a,n),{toolCalls:{...o.toolCalls,[s]:c}}}),setInputValue:s=>t(n=>({input:{...n.input,value:s}})),setInputSubmitting:s=>t(n=>({input:{...n.input,isSubmitting:s}})),addFileAttachment:s=>t(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,s]}})),removeFileAttachment:s=>t(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((o,r)=>r!==s)}})),setSelectedPromptParameters:s=>t(n=>({input:{...n.input,selectedPromptParameters:s}})),clearInput:()=>t(s=>({input:{value:"",isSubmitting:!1,attachedFiles:[],selectedPromptParameters:void 0}})),addTokenUsage:s=>t(n=>({totalBilled:{inputTokens:n.totalBilled.inputTokens+(s.inputTokens??0),outputTokens:n.totalBilled.outputTokens+(s.outputTokens??0),totalTokens:n.totalBilled.totalTokens+(s.totalTokens??0)},currentContext:{inputTokens:s.inputTokens??n.currentContext.inputTokens,outputTokens:n.currentContext.outputTokens+(s.outputTokens??0),totalTokens:(s.inputTokens??n.currentContext.inputTokens)+(n.currentContext.outputTokens+(s.outputTokens??0))}})),setLatestContextSize:s=>t({latestContextSize:s}),setCurrentModel:s=>t({currentModel:s}),resetTokens:()=>t({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}),cycleTokenDisplayMode:()=>t(s=>{const n=["context","input","output"],r=(n.indexOf(s.tokenDisplayMode)+1)%n.length,i=n[r];return i?{tokenDisplayMode:i}:s}),addLog:s=>t(n=>({logs:[...n.logs,s]})),clearLogs:()=>t({logs:[]}),setActiveTab:s=>t({activeTab:s}),truncateMessagesFrom:s=>t(n=>({messages:n.messages.slice(0,s),totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}))})),Z=ue("use-chat-messages","debug");function gn(t,s){const n=H(I=>I.messages),o=H(I=>I.isStreaming),r=H(I=>I.sessionId),i=H(I=>I.setIsStreaming),a=H(I=>I.setStreamingStartTime),c=H(I=>I.addMessage),u=H(I=>I.updateMessage),d=H(I=>I.setError),m=H(I=>I.setLatestContextSize),p=H(I=>I.addToolCall),g=H(I=>I.updateToolCall),x=H(I=>I.addToolCallToCurrentMessage),h=H(I=>I.updateToolCallInCurrentMessage),f=H(I=>I.addHookNotificationToCurrentMessage),b=H(I=>I.addSourcesByToolCallId),N=H(I=>I.truncateMessagesFrom),v=l.useRef(null),C=l.useRef(!1),U=l.useCallback(async(I,_,M)=>{if(Z.debug("[sendMessage] Called with",{contentLength:I.length,attachmentsCount:_?.length||0,hasAttachments:!!_&&_.length>0,hasPromptParameters:!!M,promptParameters:M}),!t){Z.error("No client available"),d("No client available");return}let E=r;if(!E){Z.info("Creating new session before sending first message");const Y=await s();if(!Y){Z.error("Failed to create session"),d("Failed to create session");return}E=Y,Z.info("Session created successfully",{sessionId:Y})}const K=we("assistant");try{const Y=Date.now();i(!0),a(Y);const z={id:we("user"),role:"user",content:I,timestamp:new Date().toISOString(),isStreaming:!1,..._&&_.length>0?{images:_.filter(S=>S.mimeType.startsWith("image/")).map(S=>({mimeType:S.mimeType,data:S.data}))}:{}};c(z);const W={id:K,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:Y};c(W),v.current=K,C.current=!1;const V=t.receiveMessages();t.sendMessage(I,E,_,M).catch(S=>{const P=S instanceof Error?S.message:String(S);d(P),i(!1),a(null)});let T="",k=!1;for await(const S of V){if(C.current){Z.info("Stream cancelled, exiting loop");break}if(S.type==="content"){const P=S._meta,j=P?.context_size||S.context_size;if(j!=null){const O=j;Z.info("✅ Received context_size from backend",{context_size:O,totalEstimated:O.totalEstimated,source:P?.context_size?"_meta":"direct"}),m(O)}else Z.debug("Chunk does not have context_size",{hasContextSize:"context_size"in S,hasMeta:"_meta"in S,metaKeys:P?Object.keys(P):null});if(S.tokenUsage&&Z.debug("Received tokenUsage from backend",{tokenUsage:S.tokenUsage}),S.isComplete){u(K,{content:T,isStreaming:!1,streamingStartTime:void 0,...S.tokenUsage?{tokenUsage:S.tokenUsage}:{}}),i(!1),a(null),v.current=null,k=!0;break}else S.contentDelta.type==="text"&&(T+=S.contentDelta.text,u(K,{content:T,...S.tokenUsage?{tokenUsage:S.tokenUsage}:{}}),document.hidden||await new Promise(O=>setTimeout(O,16)))}else S.type==="tool_call"?(Z.debug("Received tool_call chunk",{chunk:S}),p(E,S.toolCall),x(S.toolCall)):S.type==="tool_call_update"?(Z.debug("Received tool_call_update chunk",{chunk:S}),g(E,S.toolCallUpdate),h(S.toolCallUpdate)):S.type==="hook_notification"?(Z.debug("Received hook_notification chunk",{chunk:S}),f(S.notification)):S.type==="sources"&&(Z.debug("Received sources chunk",{chunk:S}),b(S.sources))}k||(C.current?(Z.info("Stream cancelled by user"),u(K,{content:`${T}
1
+ import{r as l,j as e,M as ya,c as et,h as va}from"./react-DiSrVJhY.js";import{bb as $e,bc as wa,bd as os,be as ie,bf as q,bg as w,bh as ee,bi as F,bj as ae,bk as de,bl as it,bm as vt,bn as te,bo as Ne,bp as Bt,bq as ja,br as Na,bs as Ca,bt as Sa,bu as Te,bv as ka,bw as me,am as Ta,bx as Ia,by as rs}from"./vendor-Dm9xAZV8.js";import{P as is,a as Ra}from"./acp-sdk-D4VsTV6L.js";import{S as ye,P as _a,C as _s,a as Ma,R as Aa,T as Ea,b as Ms,c as As,d as Pa,e as Es,I as Ps,f as Ds,g as Us,h as zs,L as $s,i as Ls,j as Da,k as Ua,l as Os,m as Fs,n as Bs,o as za,O as Nt,p as Hs,q as Ct,r as Ws,s as St,D as kt,t as Vs,u as qs,v as $a,w as Ks,x as Ys,y as La,z as Qs,V as Oa,A as Gs,B as Xs,E as Fa,F as Ba,G as Js}from"./radix-BaZ_UeJz.js";import{c as tt,d as lt,e as Tt,P as Ha,E as Wa,S as Zs,f as en,g as Va,h as Ht,i as qa,j as Ka,k as Ya,l as Qa,m as fe,A as Ga,n as It,F as Xa,o as Ja,p as Za,q as eo,r as We,s as Rt,t as _t,G as tn,u as sn,v as nn,B as ls,w as to,x as so,y as no,z as Wt,H as ao,I as Vt,J as wt,T as oo,K as ce,N as ro,O as an,Q as cs,U as io,V as ds,W as at,Y as qt,_ as lo,$ as co,a0 as uo,a1 as mo,a2 as po,a3 as fo,a4 as go,a5 as ho,a6 as xo,a7 as bo,a8 as yo}from"./icons-B0Ax5AoZ.js";import{A as ot,m as ke}from"./framer-motion-DEDjTHcO.js";import{g as on}from"./markdown-jcH7_RT5.js";import"./katex-C5cjGaLm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();var vo={};const ht=typeof process<"u"&&process.versions?.node;let wo,jo=0;const $t=new Set;function No(t){return $t.add(t),()=>$t.delete(t)}function Co(t){for(const s of $t)s(t)}const us={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},So={trace:$e.TRACE,debug:$e.DEBUG,info:$e.INFO,warn:$e.WARN,error:$e.ERROR,fatal:$e.FATAL};class ko{service;minLevel;logsDir;enableConsoleOutput;constructor(s,n="debug"){this.service=s,this.minLevel=n,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&vo?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){this.logsDir}shouldLog(s){return us[s]>=us[this.minLevel]}log(s,n,o){if(!this.shouldLog(s))return;const r={id:`log_${++jo}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:n,...o&&{metadata:o}};if(Co(r),ht&&this.logsDir,ht&&this.logsDir){const c={timestamp:r.timestamp,level:r.level,service:r.service,message:r.message,...r.metadata&&{metadata:r.metadata}};this.writeToFile(JSON.stringify(c)).catch(()=>{})}if(ht&&this.enableConsoleOutput){const c=r.timestamp,u=r.level.toUpperCase().padEnd(5),d=`[${this.service}]`,m=r.metadata?` ${JSON.stringify(r.metadata)}`:"";console.log(`${c} ${u} ${d} ${r.message}${m}`)}const i=wa.getLogger(this.service),a=os.trace.getSpan(os.context.active());i.emit({severityNumber:So[s],severityText:s.toUpperCase(),body:n,attributes:{service:this.service,...o&&Object.fromEntries(Object.entries(o).map(([c,u])=>[`log.${c}`,typeof u=="object"?JSON.stringify(u):u])),...a&&{trace_id:a.spanContext().traceId,span_id:a.spanContext().spanId}}})}trace(s,n){this.log("trace",s,n)}debug(s,n){this.log("debug",s,n)}info(s,n){this.log("info",s,n)}warn(s,n){this.log("warn",s,n)}error(s,n){this.log("error",s,n)}fatal(s,n){this.log("fatal",s,n)}}function ue(t,s="debug"){return new ko(t,s)}const rn=ie(["user","assistant","system","tool"]),To=ie(["text","image","file","tool_call","tool_result"]),ct=q({type:To}),Io=ct.extend({type:ee("text"),text:w()}),Ro=ct.extend({type:ee("image"),url:w().url().optional(),source:q({type:ee("base64"),media_type:ie(["image/jpeg","image/png","image/gif","image/webp"]),data:w()}).optional()}),_o=ct.extend({type:ee("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:F().optional()}),Mo=ct.extend({type:ee("tool_call"),id:w(),name:w(),arguments:ae(w(),de())}),Ao=ct.extend({type:ee("tool_result"),callId:w(),result:de(),error:w().optional()}),ln=it("type",[Io,Ro,_o,Mo,Ao]),cn=q({id:w(),role:rn,content:te(ln),timestamp:vt(),metadata:ae(w(),de()).optional()}),Eo=q({type:ee("content"),id:w(),role:rn,contentDelta:ln,isComplete:Ne(),tokenUsage:q({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}).optional(),contextInputTokens:F().optional(),_meta:q({context_size:q({systemPromptTokens:F(),userMessagesTokens:F(),assistantMessagesTokens:F(),toolInputTokens:F(),toolResultsTokens:F(),totalEstimated:F(),llmReportedInputTokens:F().optional()}).optional()}).optional()}),Po=q({type:ee("tool_call"),id:w(),toolCall:Bt(),messageId:w().optional()}),Do=q({type:ee("tool_call_update"),id:w(),toolCallUpdate:Bt(),messageId:w().optional()}),Mt=ie(["context_size","tool_response"]),Uo=q({type:ee("hook_triggered"),hookType:Mt,threshold:F(),currentPercentage:F(),callback:w(),triggeredAt:F().optional(),toolCallId:w().optional()}),zo=q({type:ee("hook_completed"),hookType:Mt,callback:w(),metadata:q({action:w().optional(),messagesRemoved:F().optional(),tokensSaved:F().optional()}).passthrough().optional(),completedAt:F().optional(),toolCallId:w().optional()}),$o=q({type:ee("hook_error"),hookType:Mt,callback:w(),error:w(),completedAt:F().optional(),toolCallId:w().optional()}),Lo=it("type",[Uo,zo,$o]),Oo=q({type:ee("hook_notification"),id:w(),notification:Lo,messageId:w().optional()}),dn=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),Fo=q({type:ee("sources"),sources:te(dn)});it("type",[Eo,Po,Do,Oo,Fo]);const Bo=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),ms=q({systemPromptTokens:F(),toolOverheadTokens:F().optional(),mcpOverheadTokens:F().optional(),userMessagesTokens:F(),assistantMessagesTokens:F(),toolInputTokens:F(),toolResultsTokens:F(),totalEstimated:F(),llmReportedInputTokens:F().optional(),modelContextWindow:F().optional()}),Kt=ie(["pending","in_progress","completed","failed"]),Ho=ie(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),un=q({path:w(),line:F().nullable().optional()}),Yt=q({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}),Qt=it("type",[q({type:ee("content"),content:q({type:ee("text"),text:w()})}),q({type:ee("text"),text:w()}),q({type:ee("image"),data:w(),mimeType:w().optional(),alt:w().optional()}),q({type:ee("image"),url:w(),alt:w().optional()}),q({type:ee("diff"),path:w(),oldText:w(),newText:w(),line:F().nullable().optional()}),q({type:ee("terminal"),terminalId:w()})]),mn=q({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),status:Kt,content:te(Qt).optional()}),Wo=it("type",[q({type:ee("text"),text:w()}),q({type:ee("tool_call"),toolCall:mn})]),pn=q({id:w(),content:w(),toolCalls:te(mn).optional(),contentBlocks:te(Wo).optional(),isStreaming:Ne().optional(),context_size:ms.optional(),_meta:q({semanticName:w().optional(),agentDefinitionName:w().optional(),currentActivity:w().optional(),statusGenerating:Ne().optional(),context_size:ms.optional()}).passthrough().optional()}),fn=q({id:w(),batchId:w().optional(),title:w(),prettyName:w().optional(),icon:w().optional(),verbiage:q({active:w(),past:w(),paramKey:w().optional()}).optional(),subline:w().optional(),kind:Ho,status:Kt,contentPosition:F().optional(),locations:te(un).optional(),rawInput:ae(w(),de()).optional(),rawOutput:ae(w(),de()).optional(),content:te(Qt).optional(),error:w().optional(),startedAt:F().optional(),completedAt:F().optional(),tokenUsage:Yt.optional(),_meta:q({truncationWarning:w().optional(),compactionAction:ie(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(pn).optional(),subagentStreaming:Ne().optional(),subagentCompleted:Ne().optional()}),Vo=q({id:w(),status:Kt.optional(),title:w().optional(),prettyName:w().optional(),icon:w().optional(),batchId:w().optional(),rawInput:ae(w(),de()).optional(),locations:te(un).optional(),rawOutput:ae(w(),de()).optional(),content:te(Qt).optional(),error:w().optional(),completedAt:F().optional(),tokenUsage:Yt.optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(pn).optional(),subagentCompleted:Ne().optional(),_meta:q({truncationWarning:w().optional(),compactionAction:ie(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional()});function ps(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,subagentCompleted:s.subagentCompleted??t.subagentCompleted,_meta:s._meta??t._meta}}const qo=q({mimeType:w(),data:w()}),Ko=q({id:w(),hookType:Mt,callback:w(),status:ie(["triggered","completed","error"]),threshold:F().optional(),currentPercentage:F().optional(),metadata:q({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()}),Yo=q({id:w(),role:ie(["user","assistant","system"]),content:w(),timestamp:vt(),isStreaming:Ne().default(!1),streamingStartTime:F().optional(),metadata:ae(w(),de()).optional(),toolCalls:te(fn).optional(),hookNotifications:te(Ko).optional(),tokenUsage:Yt.optional(),images:te(qo).optional(),sources:te(Bo).optional()}),Qo=q({value:w(),isSubmitting:Ne(),attachedFiles:te(q({name:w(),path:w(),size:F(),mimeType:w(),data:w()})),selectedPromptParameters:ae(w(),w()).optional()});q({sessionId:w().nullable(),isConnected:Ne(),isStreaming:Ne(),messages:te(Yo),input:Qo,error:w().nullable()});ie(["disconnected","connecting","connected","error"]);let fs=0,gs=0;function we(t){const s=Date.now();s!==gs&&(fs=0,gs=s);const n=fs++,o=Math.random().toString(36).substring(2,7);return`msg_${s}_${n}_${o}_${t}`}const Go=q({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:ae(w(),w()).optional()}),L=ue("http-transport");class Xo{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;pendingReplayUpdates=[];agentInfo;constructor(s){const n=Go.safeParse(s);if(!n.success){const o=n.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ");throw new Error(`Invalid HTTP transport configuration: ${o}`)}this.options={...s,baseUrl:s.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const s={protocolVersion:is,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",s);if(n.agentInfo){const i=n._meta,a=i&&typeof i=="object",c=a&&"agentDescription"in i?String(i.agentDescription):void 0,u=a&&"suggestedPrompts"in i&&Array.isArray(i.suggestedPrompts)?i.suggestedPrompts:void 0,d=a&&"tools"in i&&Array.isArray(i.tools)?i.tools:void 0,m=a&&"mcps"in i&&Array.isArray(i.mcps)?i.mcps:void 0,p=a&&"subagents"in i&&Array.isArray(i.subagents)?i.subagents:void 0,g=a&&"initialMessage"in i&&i.initialMessage&&typeof i.initialMessage=="object"?i.initialMessage:void 0,x=a&&"uiConfig"in i&&i.uiConfig&&typeof i.uiConfig=="object"?i.uiConfig:void 0,h=a&&"promptParameters"in i&&Array.isArray(i.promptParameters)?i.promptParameters:void 0;this.agentInfo={name:n.agentInfo.name,...n.agentInfo.title?{displayName:n.agentInfo.title}:{},version:n.agentInfo.version,...c?{description:c}:{},...u?{suggestedPrompts:u}:{},...g?{initialMessage:g}:{},...x?{uiConfig:x}:{},...d?{tools:d}:{},...m?{mcps:m}:{},...p?{subagents:p}:{},...h?{promptParameters:h}:{}}}L.info("ACP connection initialized",{initResponse:n});const o={cwd:"/",mcpServers:[]},r=await this.sendRpcRequest("session/new",o);this.currentSessionId=r.sessionId,L.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(s){this.connected=!1;const n=s instanceof Error?s:new Error(String(s));throw this.notifyError(n),n}}async loadSession(s){this.connected&&(L.warn("Transport already connected, disconnecting first",{sessionId:s}),await this.disconnect());try{this.abortController=new AbortController;const n={protocolVersion:is,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};L.info("Loading session - initializing connection",{sessionId:s});const o=await this.sendRpcRequest("initialize",n);if(o.agentInfo){const a=o._meta,c=a&&typeof a=="object",u=c&&"agentDescription"in a?String(a.agentDescription):void 0,d=c&&"suggestedPrompts"in a&&Array.isArray(a.suggestedPrompts)?a.suggestedPrompts:void 0,m=c&&"tools"in a&&Array.isArray(a.tools)?a.tools:void 0,p=c&&"mcps"in a&&Array.isArray(a.mcps)?a.mcps:void 0,g=c&&"subagents"in a&&Array.isArray(a.subagents)?a.subagents:void 0,x=c&&"initialMessage"in a&&a.initialMessage&&typeof a.initialMessage=="object"?a.initialMessage:void 0,h=c&&"uiConfig"in a&&a.uiConfig&&typeof a.uiConfig=="object"?a.uiConfig:void 0,f=c&&"promptParameters"in a&&Array.isArray(a.promptParameters)?a.promptParameters:void 0;this.agentInfo={name:o.agentInfo.name,...o.agentInfo.title?{displayName:o.agentInfo.title}:{},version:o.agentInfo.version,...u?{description:u}:{},...d?{suggestedPrompts:d}:{},...x?{initialMessage:x}:{},...h?{uiConfig:h}:{},...m?{tools:m}:{},...p?{mcps:p}:{},...g?{subagents:g}:{},...f?{promptParameters:f}:{}}}if(!o.agentCapabilities?.loadSession)throw L.error("Agent does not support loading sessions",{capabilities:o.agentCapabilities}),new Error("Agent does not support loading sessions");L.info("ACP connection initialized, loading session",{sessionId:s,capabilities:o.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=s,await this.connectSSE();const r={sessionId:s,cwd:"/",mcpServers:[]};L.info("Sending session/load request",{loadRequest:r});const i=await this.sendRpcRequest("session/load",r);L.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:i}),this.connected=!0,this.reconnectAttempts=0}catch(n){this.connected=!1;const o=n instanceof Error?n:new Error(String(n));throw L.error("Failed to load session",{sessionId:s,error:o.message,stack:o.stack}),this.notifyError(o),o}}async listSessions(){try{const s={method:"GET"};this.options.headers&&(s.headers=this.options.headers);const n=await fetch(`${this.options.baseUrl}/sessions`,s);if(!n.ok)throw new Error(`HTTP ${n.status}: ${await n.text()}`);return(await n.json()).sessions||[]}catch(s){return 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 n=s instanceof Error?s:new Error(String(s));throw this.notifyError(n),n}}async send(s,n){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");this.isInReplayMode&&(L.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const o=s.content.map(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),r={sessionId:this.currentSessionId,prompt:o};n?.promptParameters&&(r._meta={promptParameters:n.promptParameters});const i=await this.sendRpcRequest("session/prompt",r);L.debug("Prompt sent",{promptResponse:i}),this.streamComplete=!0;const a=this.chunkResolvers.shift();a?a({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(o){this.streamComplete=!0;const r=o instanceof Error?o:new Error(String(o));throw this.notifyError(r),r}}async cancel(s){if(!this.connected){L.warn("Cannot cancel: transport not connected");return}const n=s||this.currentSessionId;if(!n){L.warn("Cannot cancel: no session ID");return}L.info("Cancelling session",{sessionId:n}),this.streamComplete=!0,this.messageQueue.length=0,await this.sendNotification("session/cancel",{sessionId:n});const o={type:"content",id:n,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0};for(;this.chunkResolvers.length>0;){const r=this.chunkResolvers.shift();r&&r(o)}}async editAndResend(s,n,o){if(!this.connected)throw new Error("Transport not connected");const r=s||this.currentSessionId;if(!r)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:r,messageIndex:n});const i={"Content-Type":"application/json",...this.options.headers},a=this.options.timeout??600*1e3,c=new AbortController,u=setTimeout(()=>c.abort(),a);try{const d=await fetch(`${this.options.baseUrl}/sessions/${r}/edit-and-resend`,{method:"POST",headers:i,body:JSON.stringify({messageIndex:n,prompt:o}),signal:c.signal});if(clearTimeout(u),!d.ok){const p=await d.text();throw new Error(`HTTP ${d.status}: ${p}`)}this.streamComplete=!0;const m=this.chunkResolvers.shift();m?m({type:"content",id:r,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({type:"content",id:r,role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(d){throw clearTimeout(u),this.streamComplete=!0,d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${a}ms`):d}}async*receive(){this.isReceivingMessages=!0;try{for(;!this.streamComplete;)if(this.messageQueue.length>0){const s=this.messageQueue.shift();if(s&&(yield s,s.type==="content"&&s.isComplete))return}else{const s=await new Promise(n=>{this.chunkResolvers.push(n)});if(s.type==="content"&&s.isComplete){yield s;return}else yield s}for(;this.messageQueue.length>0;){const s=this.messageQueue.shift();s&&(yield s)}yield{type:"content",id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}finally{this.isReceivingMessages=!1}}isConnected(){return this.connected}onSessionUpdate(s){if(this.sessionUpdateCallbacks.add(s),this.pendingReplayUpdates.length>0){L.info("Replaying queued session updates to ALL callbacks",{count:this.pendingReplayUpdates.length,callbackCount:this.sessionUpdateCallbacks.size,updateTypes:this.pendingReplayUpdates.map(o=>o.type),updateDetails:this.pendingReplayUpdates.map(o=>{if(o.type==="tool_call")return{type:"tool_call",toolCallId:o.toolCall?.id};if(o.type==="sources")return{type:"sources",count:o.sources?.length,ids:o.sources?.map(r=>r.id)};if(o.type==="generic"&&o.message){const r=o.message.content?.[0];return{type:"message",role:o.message.role,contentLength:r?.type==="text"?r.text?.length:0}}return{type:o.type}})});const n=[...this.pendingReplayUpdates];this.pendingReplayUpdates=[],setTimeout(()=>{L.info("Starting replay of queued updates to all callbacks",{updateCount:n.length,callbackCount:this.sessionUpdateCallbacks.size});for(const o of n)try{L.info("Replaying update to all callbacks",{type:o.type}),this.notifySessionUpdate(o)}catch(r){L.error("Error replaying session update",{error:r})}L.info("Finished replay of queued updates")},0)}return()=>{this.sessionUpdateCallbacks.delete(s)}}onError(s){return this.errorCallbacks.add(s),()=>{this.errorCallbacks.delete(s)}}onFileSystemChange(s,n){return L.debug("Registering file system change callback",{sessionId:s}),this.fileSystemChangeCallbacks.set(s,n),()=>{L.debug("Unregistering file system change callback",{sessionId:s}),this.fileSystemChangeCallbacks.delete(s)}}notifyFileSystemChange(s){const n=this.fileSystemChangeCallbacks.get(s.sessionId);L.debug("notifyFileSystemChange",{sessionId:s.sessionId,hasCallback:!!n,callbackCount:this.fileSystemChangeCallbacks.size}),n&&n(s)}getAgentInfo(){return this.agentInfo||{}}async sendNotification(s,n){const o={jsonrpc:"2.0",method:s,params:n};L.debug("Sending notification",{method:s,params:n});const r={"Content-Type":"application/json",...this.options.headers};try{const i=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:r,body:JSON.stringify(o)});if(!i.ok){const a=await i.text();L.error("Notification failed",{status:i.status,errorText:a})}}catch(i){L.error("Error sending notification",{error:i})}}async sendRpcRequest(s,n){const r={jsonrpc:"2.0",id:this.generateRequestId(),method:s,params:n};L.debug("Sending RPC request",{method:s,params:n,request:r});const i={"Content-Type":"application/json",...this.options.headers},a=this.options.timeout??600*1e3,c=new AbortController,u=setTimeout(()=>c.abort(),a);try{const d=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(r),signal:c.signal});if(clearTimeout(u),!d.ok){const p=await d.text();throw new Error(`HTTP ${d.status}: ${p}`)}const m=await d.json();if(m.error)throw new Error(`ACP error: ${m.error.message||JSON.stringify(m.error)}`);return m.result||m}catch(d){throw clearTimeout(u),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${a}ms`):d}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const s=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const o=await fetch(s,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!o.ok)throw new Error(`SSE connection failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response body is null");L.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const r=o.body.getReader(),i=new TextDecoder;let a="";(async()=>{try{for(;;){const{done:c,value:u}=await r.read();if(c){L.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}a+=i.decode(u,{stream:!0});const d=a.split(`
2
+ `);a=d.pop()||"";let m={event:"message",data:""};for(const p of d)p.startsWith("event:")?m.event=p.substring(6).trim():p.startsWith("data:")?m.data=p.substring(5).trim():p===""&&(m.event==="message"&&m.data&&this.handleSSEMessage(m.data),m={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(o){throw L.error("SSE connection error",{error:o}),o}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const n=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(n),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const 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(n=>setTimeout(n,s));try{await this.connectSSE(),L.info("SSE reconnected successfully"),this.reconnecting=!1}catch(n){L.error("SSE reconnection failed",{error:n}),this.reconnecting=!1}}handleSSEMessage(s){try{const n=JSON.parse(s);if(L.debug("Received SSE message",{message:n}),n&&typeof n=="object"&&n.method==="session/update"&&n.params?.update?.sessionUpdate==="sources"){try{this.handleSessionNotification(n.params)}catch(a){L.error("Error in handleSessionNotification for sources",{error:a})}return}const r=Ra.safeParse(n);if(!r.success){L.error("Invalid ACP message from SSE",{issues:r.error.issues});return}const i=r.data;L.debug("Parsed ACP message",{method:"method"in i?i.method:"(no method)"}),"method"in i&&i.method==="session/update"&&(L.debug("Received session/update notification"),"params"in i&&i.params&&(L.debug("Calling handleSessionNotification",{params:i.params}),this.handleSessionNotification(i.params)))}catch(n){L.error("Error parsing SSE message",{error:n}),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(s){const r=s.update?.sessionUpdate==="sources";if(this.streamComplete&&!r){L.debug("Skipping session notification - stream complete/cancelled");return}L.debug("handleSessionNotification called",{params:s});const a=s.update,c=this.currentSessionId||s.sessionId;if(L.warn("📥 SSE UPDATE RECEIVED",{sessionUpdate:a?.sessionUpdate,hasUpdate:!!a,isInReplayMode:this.isInReplayMode,callbackCount:this.sessionUpdateCallbacks.size}),a?.sessionUpdate==="sandbox_files_changed"){const d=a;d._meta?.isReplay===!0||(L.debug("Sandbox files changed",{paths:d.paths,source:d._meta?.source}),this.notifyFileSystemChange({sessionId:c,...d.paths&&{paths:d.paths},...d._meta?.source&&{source:d._meta.source}}));return}if(a?.sessionUpdate==="tool_call"){L.debug("Tool call notification",{tokenUsage:a.tokenUsage});const d=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,m=a._meta&&typeof a._meta=="object"&&"prettyName"in a._meta&&typeof a._meta.prettyName=="string"?a._meta.prettyName:void 0,p=a._meta&&typeof a._meta=="object"&&"icon"in a._meta&&typeof a._meta.icon=="string"?a._meta.icon:void 0,g=a._meta&&typeof a._meta=="object"&&"subline"in a._meta&&typeof a._meta.subline=="string"?a._meta.subline:void 0,x=a._meta&&typeof a._meta=="object"&&"batchId"in a._meta&&typeof a._meta.batchId=="string"?a._meta.batchId:void 0,h=a._meta&&typeof a._meta=="object"&&"subagentPort"in a._meta&&typeof a._meta.subagentPort=="number"?a._meta.subagentPort:void 0,f=a._meta&&typeof a._meta=="object"&&"subagentSessionId"in a._meta&&typeof a._meta.subagentSessionId=="string"?a._meta.subagentSessionId:void 0,b=a._meta&&typeof a._meta=="object"&&"subagentMessages"in a._meta&&Array.isArray(a._meta.subagentMessages)?a._meta.subagentMessages:void 0,N=a._meta&&typeof a._meta=="object"&&"compactionAction"in a._meta&&typeof a._meta.compactionAction=="string"?a._meta.compactionAction:void 0,v=a._meta&&typeof a._meta=="object"&&"originalTokens"in a._meta&&typeof a._meta.originalTokens=="number"?a._meta.originalTokens:void 0,C=a._meta&&typeof a._meta=="object"&&"finalTokens"in a._meta&&typeof a._meta.finalTokens=="number"?a._meta.finalTokens:void 0,U=a._meta&&typeof a._meta=="object"&&"originalContentPreview"in a._meta&&typeof a._meta.originalContentPreview=="string"?a._meta.originalContentPreview:void 0,B=a._meta&&typeof a._meta=="object"&&"originalContentPath"in a._meta&&typeof a._meta.originalContentPath=="string"?a._meta.originalContentPath:void 0,D={id:a.toolCallId??"",batchId:x,title:a.title??"",prettyName:m,icon:p,subline:g,kind:a.kind||"other",status:a.status||"pending",locations:a.locations,rawInput:a.rawInput,tokenUsage:a.tokenUsage,content:a.content?.map(M=>{if(typeof M!="object"||M===null)return{type:"text",text:""};const A=M;if(A.type==="content"&&typeof A.content=="object"&&A.content!==null){const K=A.content;if(K.type==="text")return{type:"content",content:{type:"text",text:typeof K.text=="string"?K.text:""}}}return A.type==="text"?{type:"text",text:typeof A.text=="string"?A.text:""}:A.type==="diff"?{type:"diff",path:typeof A.path=="string"?A.path:"",oldText:typeof A.oldText=="string"?A.oldText:"",newText:typeof A.newText=="string"?A.newText:"",line:typeof A.line=="number"?A.line:null}:A.type==="terminal"?{type:"terminal",terminalId:typeof A.terminalId=="string"?A.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now(),subagentPort:h,subagentSessionId:f,subagentMessages:b,_meta:N||v||C||U||B?{compactionAction:N,originalTokens:v,finalTokens:C,originalContentPreview:U,originalContentPath:B}:void 0},I={type:"tool_call",sessionId:c,status:"active",toolCall:D,messageId:d},_=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0;if(L.info("Creating tool_call session update",{toolCallId:D.id,title:D.title,hasSubagentPort:!!h,hasSubagentSessionId:!!f,hasSubagentMessages:!!b,subagentMessagesCount:b?.length,isReplay:_,isInReplayMode:this.isInReplayMode}),_||this.isInReplayMode)this.sessionUpdateCallbacks.size===0?(L.debug("Queueing tool_call for late-subscribing callbacks",{toolCallId:D.id}),this.pendingReplayUpdates.push(I)):this.notifySessionUpdate(I);else{const M={type:"tool_call",id:c,toolCall:D,messageId:d},A=this.chunkResolvers.shift();A?A(M):this.messageQueue.push(M)}}else if(a?.sessionUpdate==="tool_call_update"){const d=a._meta&&typeof a._meta=="object"&&"messageId"in a._meta?String(a._meta.messageId):void 0,m=a._meta&&typeof a._meta=="object"&&"prettyName"in a._meta&&typeof a._meta.prettyName=="string"?a._meta.prettyName:void 0,p=a._meta&&typeof a._meta=="object"&&"icon"in a._meta&&typeof a._meta.icon=="string"?a._meta.icon:void 0,g=a._meta&&typeof a._meta=="object"&&"batchId"in a._meta&&typeof a._meta.batchId=="string"?a._meta.batchId:void 0,x=a._meta&&typeof a._meta=="object"&&"subagentPort"in a._meta&&typeof a._meta.subagentPort=="number"?a._meta.subagentPort:void 0,h=a._meta&&typeof a._meta=="object"&&"subagentSessionId"in a._meta&&typeof a._meta.subagentSessionId=="string"?a._meta.subagentSessionId:void 0,f=a._meta&&typeof a._meta=="object"&&"subagentMessages"in a._meta&&Array.isArray(a._meta.subagentMessages)?a._meta.subagentMessages:void 0;(x||h||f)&&L.info("Extracted subagent info from tool_call_update",{toolCallId:a.toolCallId,subagentPort:x,subagentSessionId:h,subagentMessagesCount:f?.length});const b=a._meta&&typeof a._meta=="object"&&"compactionAction"in a._meta&&typeof a._meta.compactionAction=="string"?a._meta.compactionAction:void 0,N=a._meta&&typeof a._meta=="object"&&"originalTokens"in a._meta&&typeof a._meta.originalTokens=="number"?a._meta.originalTokens:void 0,v=a._meta&&typeof a._meta=="object"&&"finalTokens"in a._meta&&typeof a._meta.finalTokens=="number"?a._meta.finalTokens:void 0,C=a._meta&&typeof a._meta=="object"&&"originalContentPreview"in a._meta&&typeof a._meta.originalContentPreview=="string"?a._meta.originalContentPreview:void 0,U=a._meta&&typeof a._meta=="object"&&"originalContentPath"in a._meta&&typeof a._meta.originalContentPath=="string"?a._meta.originalContentPath:void 0,B="subagentCompleted"in a&&typeof a.subagentCompleted=="boolean"?a.subagentCompleted:a._meta&&typeof a._meta=="object"&&"subagentCompleted"in a._meta&&typeof a._meta.subagentCompleted=="boolean"?a._meta.subagentCompleted:void 0,D={id:a.toolCallId??"",status:a.status,title:a.title,prettyName:m,icon:p,batchId:g,rawInput:a.rawInput,locations:a.locations,rawOutput:a.rawOutput,tokenUsage:a.tokenUsage,subagentCompleted:B,content:a.content?.map(_=>{if(typeof _!="object"||_===null)return{type:"text",text:""};const M=_;if(M.type==="content"&&typeof M.content=="object"&&M.content!==null){const A=M.content;if(A.type==="text")return{type:"content",content:{type:"text",text:typeof A.text=="string"?A.text:""}}}return M.type==="text"?{type:"text",text:typeof M.text=="string"?M.text:""}:M.type==="diff"?{type:"diff",path:typeof M.path=="string"?M.path:"",oldText:typeof M.oldText=="string"?M.oldText:"",newText:typeof M.newText=="string"?M.newText:"",line:typeof M.line=="number"?M.line:null}:M.type==="terminal"?{type:"terminal",terminalId:typeof M.terminalId=="string"?M.terminalId:""}:{type:"text",text:""}}),error:a.error,completedAt:a.status==="completed"||a.status==="failed"?Date.now():void 0,subagentPort:x,subagentSessionId:h,subagentMessages:f,_meta:b||N||v||C||U?{compactionAction:b,originalTokens:N,finalTokens:v,originalContentPreview:C,originalContentPath:U}:void 0},I={type:"tool_call_update",sessionId:c,status:"active",toolCallUpdate:D,messageId:d};if(this.isInReplayMode)this.sessionUpdateCallbacks.size===0?(L.debug("Queueing tool_call_update for late-subscribing callbacks",{toolCallId:D.id}),this.pendingReplayUpdates.push(I)):this.notifySessionUpdate(I);else{const _={type:"tool_call_update",id:c,toolCallUpdate:D,messageId:d},M=this.chunkResolvers.shift();M?M(_):this.messageQueue.push(_)}L.debug("Processed tool_call_update",{sessionUpdate:I,isReplay:this.isInReplayMode})}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="hook_notification"){const d=a;L.debug("Received hook_notification",{id:d.id,notificationType:d.notification.type,hookType:d.notification.hookType});const m={type:"hook_notification",id:d.id,notification:d.notification,messageId:d.messageId},p=this.chunkResolvers.shift();p?p(m):this.messageQueue.push(m)}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="tool_output"){const d=a,m=d._meta&&typeof d._meta=="object"&&"messageId"in d._meta?String(d._meta.messageId):void 0,p={id:d.toolCallId??"",rawOutput:d.rawOutput,content:d.content?.map(x=>{if(typeof x!="object"||x===null)return{type:"text",text:""};const h=x;if(h.type==="content"&&typeof h.content=="object"&&h.content!==null){const f=h.content;if(f.type==="text")return{type:"content",content:{type:"text",text:typeof f.text=="string"?f.text:""}}}return h.type==="text"?{type:"text",text:typeof h.text=="string"?h.text:""}:h.type==="diff"?{type:"diff",path:typeof h.path=="string"?h.path:"",oldText:typeof h.oldText=="string"?h.oldText:"",newText:typeof h.newText=="string"?h.newText:"",line:typeof h.line=="number"?h.line:null}:h.type==="terminal"?{type:"terminal",terminalId:typeof h.terminalId=="string"?h.terminalId:""}:h.type==="image"?{type:"image",data:typeof h.data=="string"?h.data:"",mimeType:typeof h.mimeType=="string"?h.mimeType:"image/png",alt:typeof h.alt=="string"?h.alt:void 0}:{type:"text",text:""}})},g={type:"tool_call_update",sessionId:c,status:"active",toolCallUpdate:p,messageId:m};if(this.isInReplayMode)this.sessionUpdateCallbacks.size===0?(L.debug("Queueing tool_output for late-subscribing callbacks",{toolCallId:p.id}),this.pendingReplayUpdates.push(g)):this.notifySessionUpdate(g);else{const x={type:"tool_call_update",id:c,toolCallUpdate:p,messageId:m},h=this.chunkResolvers.shift();h?h(x):this.messageQueue.push(x)}L.debug("Queued tool_output as tool_call_update chunk",{sessionUpdate:g})}else if(a&&"sessionUpdate"in a&&a.sessionUpdate==="sources"){const d=a,m={type:"sources",sessionId:c,status:"active",sources:d.sources};if(this.isInReplayMode)this.sessionUpdateCallbacks.size===0?this.pendingReplayUpdates.push(m):this.notifySessionUpdate(m);else{const p={type:"sources",sources:d.sources},g=this.chunkResolvers.shift();g?g(p):this.messageQueue.push(p)}}else if(a?.sessionUpdate==="agent_message_chunk"){const d=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0;if(this.isInReplayMode&&!d)return;const m=a._meta&&typeof a._meta=="object"&&"tokenUsage"in a._meta?a._meta.tokenUsage:void 0,p=a._meta&&typeof a._meta=="object"&&"contextInputTokens"in a._meta&&typeof a._meta.contextInputTokens=="number"?a._meta.contextInputTokens:void 0,g=a._meta&&typeof a._meta=="object"&&"context_size"in a._meta?a._meta.context_size:void 0,x={type:"generic",sessionId:c,status:"active",_meta:a._meta},h=a.content;if(h&&typeof h=="object"){const b=h;let N=null;if(b.type==="text"&&typeof b.text=="string"&&(N={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:b.text},tokenUsage:m,contextInputTokens:p,_meta:g?{context_size:g}:void 0,isComplete:!1}),N){const v=this.chunkResolvers.shift();v?v(N):this.messageQueue.push(N)}if(N&&typeof b.text=="string"&&(d||!this.isReceivingMessages)){const v={type:"generic",sessionId:c,status:"active",message:{id:we("assistant"),role:"assistant",content:[{type:"text",text:b.text}],timestamp:new Date().toISOString()}};d&&this.sessionUpdateCallbacks.size===0?(L.debug("Queueing assistant message for late-subscribing callbacks",{textLength:b.text.length}),this.pendingReplayUpdates.push(v)):this.notifySessionUpdate(v)}}const f=x._meta&&"context_size"in x._meta;(!d||f)&&this.notifySessionUpdate(x)}else if(a?.sessionUpdate==="user_message_chunk"){L.debug("Received user_message_chunk",{update:a});const d=a._meta&&typeof a._meta=="object"&&"isReplay"in a._meta&&a._meta.isReplay===!0,m=a.content;if(m&&typeof m=="object"){const p=m;if(p.type==="text"&&typeof p.text=="string"){const g={type:"generic",sessionId:c,status:"active",message:{id:we("user"),role:"user",content:[{type:"text",text:p.text}],timestamp:new Date().toISOString()}};d&&this.sessionUpdateCallbacks.size===0?(L.debug("Queueing user message for late-subscribing callbacks",{textLength:p.text.length}),this.pendingReplayUpdates.push(g)):(L.debug("Notifying session update for user message"),this.notifySessionUpdate(g))}}}else{L.warn("⚠️ UNHANDLED SESSION UPDATE - falling through to generic",{sessionUpdate:a?.sessionUpdate,updateKeys:a?Object.keys(a):[],hasSources:a&&"sources"in a});const d={type:"generic",sessionId:c,status:"active"};this.notifySessionUpdate(d)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(s){for(const n of this.sessionUpdateCallbacks)try{n(s)}catch(o){L.error("Error in session update callback",{error:o})}}notifyError(s){for(const n of this.errorCallbacks)try{n(s)}catch(o){L.error("Error in error callback",{error:o})}}}class Jo{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 Zo{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 Le=ue("acp-client","debug");class er{constructor(s){this.config=s,this.transport=this.createTransport(),this.setupTransportListeners(),s.autoConnect&&this.connect().catch(n=>{Le.error("Failed to auto-connect",{error:n instanceof Error?n.message:String(n)})})}transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;async connect(){await this.transport.connect();const s="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(s){const n=new Date().toISOString(),o=this.transport.getAgentInfo?.()?.name,r={id:s,status:"connected",config:{agentPath:""},messages:[],metadata:{startedAt:n,agentName:o}};this.sessions.set(s,r),this.currentSessionId=s}}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(s){const n="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(n){const c=new Date().toISOString(),u=this.transport.getAgentInfo?.()?.name,d={id:n,status:"connected",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:c,agentName:u}};return this.sessions.set(n,d),this.currentSessionId=n,n}const o=this.generateSessionId(),r=new Date().toISOString(),i=this.transport.getAgentInfo?.()?.name,a={id:o,status:"connecting",config:s?{...s,agentPath:s.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:r,agentName:i}};return this.sessions.set(o,a),this.currentSessionId=o,this.updateSessionStatus(o,"connected"),o}async loadSession(s,n){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const o=new Date().toISOString(),r={id:s,status:"connecting",config:n?{...n,agentPath:n.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};if(this.sessions.set(s,r),this.currentSessionId=s,await this.transport.loadSession(s),this.transport.getAgentInfo){const i=this.transport.getAgentInfo();i.name&&r.metadata&&(r.metadata.agentName=i.name)}return this.updateSessionStatus(s,"connected"),s}async listSessions(){return this.transport.listSessions?this.transport.listSessions():[]}async sendMessage(s,n,o,r){const i=n||this.currentSessionId;if(!i)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(i);if(!a)throw new Error(`Session ${i} not found`);const c=[];if(o&&o.length>0)for(const d of o)d.mimeType.startsWith("image/")&&c.push({type:"image",source:{type:"base64",media_type:d.mimeType,data:d.data}});c.push({type:"text",text:s});const u={id:we("user"),role:"user",content:c,timestamp:new Date().toISOString()};a.messages.push(u),this.updateSessionStatus(i,"active"),await this.transport.send(u,r?{promptParameters:r}:void 0)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}async cancel(s){const n=s||this.currentSessionId;if(!n){Le.warn("Cannot cancel: no session ID");return}Le.info("Cancelling session",{sessionId:n}),await this.transport.cancel(n)}async editAndResend(s,n,o,r){const i=o||this.currentSessionId;if(!i)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 a=[];if(r&&r.length>0)for(const c of r)c.mimeType.startsWith("image/")&&a.push({type:"image",data:c.data,mimeType:c.mimeType});a.push({type:"text",text:n}),Le.info("Edit and resend",{sessionId:i,messageIndex:s}),await this.transport.editAndResend(i,s,a)}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,n){return this.transport&&"onFileSystemChange"in this.transport?this.transport.onFileSystemChange(s,n):()=>{}}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 Jo(this.config.options);case"http":return new Xo(this.config.options);case"websocket":return new Zo(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(s=>{this.handleSessionUpdate(s)}),this.transport.onError(s=>{this.handleError(s)})}handleSessionUpdate(s){if(s.sessionId){const n=this.sessions.get(s.sessionId);n&&(s.status&&(n.status=s.status),s.message&&n.messages.push(s.message),s.error&&(n.error=s.error))}for(const n of this.sessionUpdateHandlers)try{n(s)}catch(o){Le.error("Error in session update handler",{error:o instanceof Error?o.message:String(o)})}}handleError(s){for(const n of this.errorHandlers)try{n(s)}catch(o){Le.error("Error in error handler",{error:o instanceof Error?o.message:String(o)})}}updateSessionStatus(s,n){const o=this.sessions.get(s);o&&(o.status=n,this.handleSessionUpdate({sessionId:s,status:n}))}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}const Oe=ue("acp-client-hook");function tr(t){const[s,n]=l.useState(null),[o,r]=l.useState(null),[i,a]=l.useState(null);return l.useEffect(()=>{const u=new URLSearchParams(window.location.search).get("session");u&&(Oe.info("Session ID found in URL",{sessionId:u}),a(u));try{Oe.info("Initializing ACP client",{serverUrl:t.serverUrl});const d=new er({type:"http",options:{baseUrl:t.serverUrl}});return n(d),Oe.info("ACP client initialized successfully"),()=>{Oe.debug("Disconnecting ACP client"),d.disconnect().catch(m=>{Oe.error("Failed to disconnect ACP client",{error:m instanceof Error?m.message:String(m)})})}}catch(d){const m=d instanceof Error?d.message:"Failed to initialize ACP client";r(m),Oe.error("Failed to initialize ACP client",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0});return}},[t.serverUrl]),{client:s,error:o,sessionId:i}}const se=ue("chat-store","debug"),yt=[];function At(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 xt={sessionId:null,toolCallId:null,todos:yt};const sr=t=>{const s=t.sessionId;if(!s)return yt;const o=(t.toolCalls[s]||[]).filter(a=>a.title==="todo_write").sort((a,c)=>(c.startedAt||0)-(a.startedAt||0));if(o.length===0)return yt;const r=o[0];if(!r?.rawInput?.todos||!Array.isArray(r.rawInput.todos))return yt;if(xt.sessionId===s&&xt.toolCallId===r.id)return xt.todos;const i=r.rawInput.todos.map((a,c)=>({id:`${r.id}-${c}`,text:a.status==="in_progress"?a.activeForm:a.content,status:a.status}));return xt={sessionId:s,toolCallId:r.id,todos:i},i},H=ja(t=>({connectionStatus:"disconnected",sessionId:null,error:null,messages:[],isStreaming:!1,streamingStartTime:null,sources:[],toolCalls:{},totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null,currentModel:"claude-sonnet-4-5-20250929",tokenDisplayMode:"context",logs:[],activeTab:"chat",input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:s=>t({connectionStatus:s}),setSessionId:s=>t({sessionId:s}),setError:s=>t({error:s}),addMessage:s=>t(n=>({messages:[...n.messages,s]})),updateMessage:(s,n)=>t(o=>{const r=o.messages.find(d=>d.id===s);let i=o.totalBilled,a=o.currentContext,c=n;if(n.tokenUsage){const d=r?.tokenUsage;se.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:d});const m={inputTokens:Math.max(n.tokenUsage.inputTokens??0,d?.inputTokens??0),outputTokens:Math.max(n.tokenUsage.outputTokens??0,d?.outputTokens??0),totalTokens:Math.max(n.tokenUsage.inputTokens??0,d?.inputTokens??0)+Math.max(n.tokenUsage.outputTokens??0,d?.outputTokens??0)};se.debug("updateMessage: merged tokenUsage",{merged:m}),c={...n,tokenUsage:m};const p=m.inputTokens-(d?.inputTokens??0),g=m.outputTokens-(d?.outputTokens??0),x=m.totalTokens-(d?.totalTokens??0);i={inputTokens:o.totalBilled.inputTokens+p,outputTokens:o.totalBilled.outputTokens+g,totalTokens:o.totalBilled.totalTokens+x},a={inputTokens:m.inputTokens,outputTokens:o.currentContext.outputTokens+g,totalTokens:m.totalTokens}}const u=o.messages.map(d=>d.id===s?{...d,...c}:d);if(n.tokenUsage&&c.tokenUsage){const d=r?.tokenUsage,m=c.tokenUsage,p=(m.inputTokens??0)-(d?.inputTokens??0),g=(m.outputTokens??0)-(d?.outputTokens??0),x=(m.totalTokens??0)-(d?.totalTokens??0),h=u.filter(N=>N.tokenUsage).map(N=>({id:N.id,role:N.role,tokens:N.tokenUsage})),f=u.reduce((N,v)=>({inputTokens:N.inputTokens+(v.tokenUsage?.inputTokens??0),outputTokens:N.outputTokens+(v.tokenUsage?.outputTokens??0),totalTokens:N.totalTokens+(v.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),b=f.inputTokens===i.inputTokens&&f.outputTokens===i.outputTokens&&f.totalTokens===i.totalTokens;se.debug("updateMessage: tokenUsage update",{messageId:s,updates:n.tokenUsage,existing:d,messageMax:m,delta:{inputDelta:p,outputDelta:g,totalDelta:x},totalBilled:i,currentContext:a,actualSum:f,billedCorrect:b?"✅":"❌",messageCount:u.length,messagesWithTokens:h.length,breakdown:h})}return{messages:u,totalBilled:i,currentContext:a}}),clearMessages:()=>t({messages:[],sources:[]}),addSources:s=>t(n=>{if(!s||s.length===0)return n;const o=new Map;for(const r of n.sources)o.set(r.id,r);for(const r of s)o.set(r.id,r);return{sources:Array.from(o.values())}}),setIsStreaming:s=>t({isStreaming:s}),setStreamingStartTime:s=>t({streamingStartTime:s}),addToolCall:(s,n)=>t(o=>({toolCalls:{...o.toolCalls,[s]:[...o.toolCalls[s]||[],n]}})),addToolCallToCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(u=>u.role==="assistant");if(o===-1){se.debug("No assistant message found, creating one for tool call at position 0");const u={id:we("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,toolCalls:[{...s,contentPosition:0}]};return{messages:[...n.messages,u]}}const r=[...n.messages],i=r[o];if(!i)return n;const a=i.content.length,c={...s,contentPosition:a};return r[o]={...i,toolCalls:[...i.toolCalls||[],c]},{messages:r}}),updateToolCallInCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(p=>p.role==="assistant");if(o===-1)return se.warn("No assistant message found to update tool call in"),n;const r=[...n.messages],i=r[o];if(!i)return n;const a=i.toolCalls||[],c=a.findIndex(p=>p.id===s.id);if(c===-1)return se.warn(`Tool call ${s.id} not found in message`),n;const u=a[c];if(!u)return n;const d=[...a],m=ps(u,s);return d[c]=m,r[o]={...i,toolCalls:d},{messages:r}}),addHookNotificationToCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(m=>m.role==="assistant");if(o===-1){se.debug("No assistant message found, creating one for hook notification");const m={...At(s),contentPosition:0},p={id:we("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,hookNotifications:[m]};return{messages:[...n.messages,p]}}const r=[...n.messages],i=r[o];if(!i)return n;const a=i.hookNotifications||[],c=i.content.length;if(s.type==="hook_triggered"){se.debug("Adding hook_triggered notification for loading state",{hookType:s.hookType,callback:s.callback,contentPosition:c});const m={...At(s),contentPosition:c},p=[...a,m];return r[o]={...i,hookNotifications:p},{messages:r}}let u;const d=a.findIndex(m=>m.hookType===s.hookType&&m.callback===s.callback&&m.status==="triggered");if(d!==-1){const m=a[d];u=[...a];const p=s.type==="hook_completed"||s.type==="hook_error"?s.completedAt??Date.now():Date.now();u[d]={...m,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}:{}},se.debug("Merged hook notification with triggered state",{hookType:s.hookType,status:u[d]?.status})}else{const m={...At(s),contentPosition:c};u=[...a,m],se.debug("Added hook notification without prior triggered state",{hookType:s.hookType,callback:s.callback,contentPosition:c})}return r[o]={...i,hookNotifications:u},{messages:r}}),addSourcesToCurrentMessage:s=>t(n=>{const o=n.messages.findLastIndex(c=>c.role==="assistant");if(o===-1){se.debug("No assistant message found, creating one for sources");const c={id:we("assistant"),role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,sources:s},u=new Map;for(const d of n.sources)u.set(d.id,d);for(const d of s)u.set(d.id,d);return{messages:[...n.messages,c],sources:[...u.values()]}}const r=[...n.messages],i=r[o];if(!i)return n;r[o]={...i,sources:[...i.sources||[],...s]},se.debug("Added sources to current message",{sourcesCount:s.length,totalSources:(i.sources?.length||0)+s.length});const a=new Map;for(const c of n.sources)a.set(c.id,c);for(const c of s)a.set(c.id,c);return{messages:r,sources:[...a.values()]}}),addSourcesByToolCallId:s=>t(n=>{se.info("addSourcesByToolCallId called",{sourcesCount:s.length,messagesCount:n.messages.length,sourceDetails:s.map(c=>({id:c.id,toolCallId:c.toolCallId,title:c.title?.slice(0,30)}))}),se.info("Current messages state",{messages:n.messages.map((c,u)=>({index:u,role:c.role,contentLength:c.content?.length||0,toolCallIds:c.toolCalls?.map(d=>d.id)||[],existingSources:c.sources?.length||0}))});const o=new Map;for(const c of s){if(!c.toolCallId){se.warn("Source missing toolCallId",{sourceId:c.id});continue}const u=o.get(c.toolCallId)||[];u.push(c),o.set(c.toolCallId,u)}if(o.size===0)return se.warn("No sources with toolCallId to distribute"),n;const r=[...n.messages];let i=0;for(const[c,u]of o){const d=r.findIndex(m=>m.role==="assistant"&&m.toolCalls?.some(p=>p.id===c));if(se.info("Looking for message with toolCallId",{toolCallId:c,foundIndex:d,sourcesCount:u.length}),d!==-1){const m=r[d];m&&(r[d]={...m,sources:[...m.sources||[],...u]},i+=u.length,se.info("Added sources to message",{messageIndex:d,messageId:m.id,toolCallId:c,sourcesAdded:u.length,totalSourcesNow:r[d]?.sources?.length,messageContentPreview:m.content.slice(0,100)}))}else{se.warn("Tool call not found in any message, using fallback",{toolCallId:c});const m=r.findLastIndex(p=>p.role==="assistant");if(m!==-1){const p=r[m];p&&(r[m]={...p,sources:[...p.sources||[],...u]},i+=u.length,se.info("Added sources to last assistant message (fallback)",{lastAssistantIndex:m,sourcesAdded:u.length}))}else se.error("No assistant message found to add sources to")}}se.info("Finished distributing sources",{totalSources:s.length,sourcesAdded:i,toolCallIds:Array.from(o.keys())});const a=new Map;for(const c of n.sources)a.set(c.id,c);for(const c of s)a.set(c.id,c);return{messages:r,sources:[...a.values()]}}),updateToolCall:(s,n)=>t(o=>{const r=o.toolCalls[s]||[],i=r.findIndex(u=>u.id===n.id);if(i===-1)return o;const a=r[i];if(!a)return o;const c=[...r];return c[i]=ps(a,n),{toolCalls:{...o.toolCalls,[s]:c}}}),setInputValue:s=>t(n=>({input:{...n.input,value:s}})),setInputSubmitting:s=>t(n=>({input:{...n.input,isSubmitting:s}})),addFileAttachment:s=>t(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,s]}})),removeFileAttachment:s=>t(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((o,r)=>r!==s)}})),setSelectedPromptParameters:s=>t(n=>({input:{...n.input,selectedPromptParameters:s}})),clearInput:()=>t(s=>({input:{value:"",isSubmitting:!1,attachedFiles:[],selectedPromptParameters:void 0}})),addTokenUsage:s=>t(n=>({totalBilled:{inputTokens:n.totalBilled.inputTokens+(s.inputTokens??0),outputTokens:n.totalBilled.outputTokens+(s.outputTokens??0),totalTokens:n.totalBilled.totalTokens+(s.totalTokens??0)},currentContext:{inputTokens:s.inputTokens??n.currentContext.inputTokens,outputTokens:n.currentContext.outputTokens+(s.outputTokens??0),totalTokens:(s.inputTokens??n.currentContext.inputTokens)+(n.currentContext.outputTokens+(s.outputTokens??0))}})),setLatestContextSize:s=>t({latestContextSize:s}),setCurrentModel:s=>t({currentModel:s}),resetTokens:()=>t({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}),cycleTokenDisplayMode:()=>t(s=>{const n=["context","input","output"],r=(n.indexOf(s.tokenDisplayMode)+1)%n.length,i=n[r];return i?{tokenDisplayMode:i}:s}),addLog:s=>t(n=>({logs:[...n.logs,s]})),clearLogs:()=>t({logs:[]}),setActiveTab:s=>t({activeTab:s}),truncateMessagesFrom:s=>t(n=>({messages:n.messages.slice(0,s),totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}))})),Z=ue("use-chat-messages","debug");function gn(t,s){const n=H(I=>I.messages),o=H(I=>I.isStreaming),r=H(I=>I.sessionId),i=H(I=>I.setIsStreaming),a=H(I=>I.setStreamingStartTime),c=H(I=>I.addMessage),u=H(I=>I.updateMessage),d=H(I=>I.setError),m=H(I=>I.setLatestContextSize),p=H(I=>I.addToolCall),g=H(I=>I.updateToolCall),x=H(I=>I.addToolCallToCurrentMessage),h=H(I=>I.updateToolCallInCurrentMessage),f=H(I=>I.addHookNotificationToCurrentMessage),b=H(I=>I.addSourcesByToolCallId),N=H(I=>I.truncateMessagesFrom),v=l.useRef(null),C=l.useRef(!1),U=l.useCallback(async(I,_,M)=>{if(Z.debug("[sendMessage] Called with",{contentLength:I.length,attachmentsCount:_?.length||0,hasAttachments:!!_&&_.length>0,hasPromptParameters:!!M,promptParameters:M}),!t){Z.error("No client available"),d("No client available");return}let A=r;if(!A){Z.info("Creating new session before sending first message");const Y=await s();if(!Y){Z.error("Failed to create session"),d("Failed to create session");return}A=Y,Z.info("Session created successfully",{sessionId:Y})}const K=we("assistant");try{const Y=Date.now();i(!0),a(Y);const z={id:we("user"),role:"user",content:I,timestamp:new Date().toISOString(),isStreaming:!1,..._&&_.length>0?{images:_.filter(S=>S.mimeType.startsWith("image/")).map(S=>({mimeType:S.mimeType,data:S.data}))}:{}};c(z);const W={id:K,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:Y};c(W),v.current=K,C.current=!1;const V=t.receiveMessages();t.sendMessage(I,A,_,M).catch(S=>{const P=S instanceof Error?S.message:String(S);d(P),i(!1),a(null)});let T="",k=!1;for await(const S of V){if(C.current){Z.info("Stream cancelled, exiting loop");break}if(S.type==="content"){const P=S._meta,j=P?.context_size||S.context_size;if(j!=null){const O=j;Z.info("✅ Received context_size from backend",{context_size:O,totalEstimated:O.totalEstimated,source:P?.context_size?"_meta":"direct"}),m(O)}else Z.debug("Chunk does not have context_size",{hasContextSize:"context_size"in S,hasMeta:"_meta"in S,metaKeys:P?Object.keys(P):null});if(S.tokenUsage&&Z.debug("Received tokenUsage from backend",{tokenUsage:S.tokenUsage}),S.isComplete){u(K,{content:T,isStreaming:!1,streamingStartTime:void 0,...S.tokenUsage?{tokenUsage:S.tokenUsage}:{}}),i(!1),a(null),v.current=null,k=!0;break}else S.contentDelta.type==="text"&&(T+=S.contentDelta.text,u(K,{content:T,...S.tokenUsage?{tokenUsage:S.tokenUsage}:{}}),document.hidden||await new Promise(O=>setTimeout(O,16)))}else S.type==="tool_call"?(Z.debug("Received tool_call chunk",{chunk:S}),p(A,S.toolCall),x(S.toolCall)):S.type==="tool_call_update"?(Z.debug("Received tool_call_update chunk",{chunk:S}),g(A,S.toolCallUpdate),h(S.toolCallUpdate)):S.type==="hook_notification"?(Z.debug("Received hook_notification chunk",{chunk:S}),f(S.notification)):S.type==="sources"&&(Z.debug("Received sources chunk",{chunk:S}),b(S.sources))}k||(C.current?(Z.info("Stream cancelled by user"),u(K,{content:`${T}
3
3
 
4
- [Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Z.warn("Stream ended without isComplete flag"),u(K,{isStreaming:!1,streamingStartTime:void 0})),i(!1),a(null),v.current=null)}catch(Y){const z=Y instanceof Error?Y.message:String(Y);d(z),i(!1),a(null),v.current=null,u(K,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,s,c,u,i,a,d,m,p,g,x,h,f,b]),B=l.useCallback(async()=>{if(!t||!o){Z.debug("Cannot cancel: not streaming or no client");return}Z.info("Cancelling current turn"),C.current=!0;try{await t.cancel(r||void 0)}catch(I){Z.error("Error cancelling turn",{error:I})}},[t,o,r]),D=l.useCallback(async(I,_,M)=>{if(Z.debug("[editAndResend] Called with",{userMessageIndex:I,contentLength:_.length,attachmentsCount:M?.length||0}),!t){Z.error("No client available"),d("No client available");return}if(!r){Z.error("No session available"),d("No session available");return}let E=0,K=-1;for(let W=0;W<n.length;W++)if(n[W]?.role==="user"){if(E===I){K=W;break}E++}if(K===-1){Z.error("User message not found",{userMessageIndex:I,totalUserMessages:E}),d("User message not found");return}const Y=n[K];Z.debug("[editAndResend] Found target message",{userMessageIndex:I,targetArrayIndex:K,messageRole:Y?.role});const z=we("assistant");try{const W=Date.now();i(!0),a(W),N(K);const V={id:we("user"),role:"user",content:_,timestamp:new Date().toISOString(),isStreaming:!1,...M&&M.length>0?{images:M.filter(j=>j.mimeType.startsWith("image/")).map(j=>({mimeType:j.mimeType,data:j.data}))}:{}};c(V);const T={id:z,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:W};c(T),v.current=z,C.current=!1;const k=t.receiveMessages();t.editAndResend(I,_,r,M).catch(j=>{const O=j instanceof Error?j.message:String(j);d(O),i(!1),a(null)});let S="",P=!1;for await(const j of k){if(C.current){Z.info("Stream cancelled, exiting loop");break}if(j.type==="content"){const Q=j._meta?.context_size||j.context_size;if(Q!=null){const $=Q;Z.info("✅ Received context_size from backend",{context_size:$,totalEstimated:$.totalEstimated}),m($)}if(j.isComplete){u(z,{content:S,isStreaming:!1,streamingStartTime:void 0,...j.tokenUsage?{tokenUsage:j.tokenUsage}:{}}),i(!1),a(null),v.current=null,P=!0;break}else j.contentDelta.type==="text"&&(S+=j.contentDelta.text,u(z,{content:S,...j.tokenUsage?{tokenUsage:j.tokenUsage}:{}}),document.hidden||await new Promise($=>setTimeout($,16)))}else j.type==="tool_call"?(Z.debug("Received tool_call chunk",{chunk:j}),p(r,j.toolCall),x(j.toolCall)):j.type==="tool_call_update"?(Z.debug("Received tool_call_update chunk",{chunk:j}),g(r,j.toolCallUpdate),h(j.toolCallUpdate)):j.type==="hook_notification"?(Z.debug("Received hook_notification chunk",{chunk:j}),f(j.notification)):j.type==="sources"&&(Z.debug("Received sources chunk",{chunk:j}),b(j.sources))}P||(C.current?(Z.info("Stream cancelled by user"),u(z,{content:`${S}
4
+ [Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Z.warn("Stream ended without isComplete flag"),u(K,{isStreaming:!1,streamingStartTime:void 0})),i(!1),a(null),v.current=null)}catch(Y){const z=Y instanceof Error?Y.message:String(Y);d(z),i(!1),a(null),v.current=null,u(K,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,s,c,u,i,a,d,m,p,g,x,h,f,b]),B=l.useCallback(async()=>{if(!t||!o){Z.debug("Cannot cancel: not streaming or no client");return}Z.info("Cancelling current turn"),C.current=!0;try{await t.cancel(r||void 0)}catch(I){Z.error("Error cancelling turn",{error:I})}},[t,o,r]),D=l.useCallback(async(I,_,M)=>{if(Z.debug("[editAndResend] Called with",{userMessageIndex:I,contentLength:_.length,attachmentsCount:M?.length||0}),!t){Z.error("No client available"),d("No client available");return}if(!r){Z.error("No session available"),d("No session available");return}let A=0,K=-1;for(let W=0;W<n.length;W++)if(n[W]?.role==="user"){if(A===I){K=W;break}A++}if(K===-1){Z.error("User message not found",{userMessageIndex:I,totalUserMessages:A}),d("User message not found");return}const Y=n[K];Z.debug("[editAndResend] Found target message",{userMessageIndex:I,targetArrayIndex:K,messageRole:Y?.role});const z=we("assistant");try{const W=Date.now();i(!0),a(W),N(K);const V={id:we("user"),role:"user",content:_,timestamp:new Date().toISOString(),isStreaming:!1,...M&&M.length>0?{images:M.filter(j=>j.mimeType.startsWith("image/")).map(j=>({mimeType:j.mimeType,data:j.data}))}:{}};c(V);const T={id:z,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:W};c(T),v.current=z,C.current=!1;const k=t.receiveMessages();t.editAndResend(I,_,r,M).catch(j=>{const O=j instanceof Error?j.message:String(j);d(O),i(!1),a(null)});let S="",P=!1;for await(const j of k){if(C.current){Z.info("Stream cancelled, exiting loop");break}if(j.type==="content"){const Q=j._meta?.context_size||j.context_size;if(Q!=null){const $=Q;Z.info("✅ Received context_size from backend",{context_size:$,totalEstimated:$.totalEstimated}),m($)}if(j.isComplete){u(z,{content:S,isStreaming:!1,streamingStartTime:void 0,...j.tokenUsage?{tokenUsage:j.tokenUsage}:{}}),i(!1),a(null),v.current=null,P=!0;break}else j.contentDelta.type==="text"&&(S+=j.contentDelta.text,u(z,{content:S,...j.tokenUsage?{tokenUsage:j.tokenUsage}:{}}),document.hidden||await new Promise($=>setTimeout($,16)))}else j.type==="tool_call"?(Z.debug("Received tool_call chunk",{chunk:j}),p(r,j.toolCall),x(j.toolCall)):j.type==="tool_call_update"?(Z.debug("Received tool_call_update chunk",{chunk:j}),g(r,j.toolCallUpdate),h(j.toolCallUpdate)):j.type==="hook_notification"?(Z.debug("Received hook_notification chunk",{chunk:j}),f(j.notification)):j.type==="sources"&&(Z.debug("Received sources chunk",{chunk:j}),b(j.sources))}P||(C.current?(Z.info("Stream cancelled by user"),u(z,{content:`${S}
5
5
 
6
- [Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Z.warn("Stream ended without isComplete flag"),u(z,{isStreaming:!1,streamingStartTime:void 0})),i(!1),a(null),v.current=null)}catch(W){const V=W instanceof Error?W.message:String(W);d(V),i(!1),a(null),v.current=null,u(z,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,n,N,c,u,i,a,d,m,p,g,x,h,f,b]);return{messages:n,isStreaming:o,sendMessage:U,editAndResend:D,cancel:B}}const hs=ue("use-chat-input","debug");function nr(t,s){const n=H(g=>g.input),o=H(g=>g.setInputValue),r=H(g=>g.setInputSubmitting),i=H(g=>g.addFileAttachment),a=H(g=>g.removeFileAttachment),{sendMessage:c}=gn(t,s),u=l.useCallback(g=>{o(g)},[o]),d=l.useCallback(async()=>{const g=H.getState().input;if(!g.value.trim()||g.isSubmitting)return;const x=g.value,h=g.attachedFiles,f=g.selectedPromptParameters;hs.debug("Submitting message with attachments",{messageLength:x.length,attachmentCount:h.length,hasAttachments:h.length>0,hasPromptParameters:!!f&&Object.keys(f).length>0,promptParameters:f}),o(""),r(!0);try{await c(x,h.length>0?h:void 0,f&&Object.keys(f).length>0?f:void 0),H.setState(b=>({input:{...b.input,attachedFiles:[]}}))}catch(b){hs.error("Failed to send message",{error:b instanceof Error?b.message:String(b)})}finally{r(!1)}},[o,r,c]),m=l.useCallback(g=>{i(g)},[i]),p=l.useCallback(g=>{a(g)},[a]);return{value:n.value,isSubmitting:n.isSubmitting,attachedFiles:n.attachedFiles,onChange:u,onSubmit:d,onAttachFile:m,onRemoveFile:p}}const Ce=ue("use-chat-session","debug");function ar(t,s){const n=H(f=>f.connectionStatus),o=H(f=>f.sessionId),r=H(f=>f.setConnectionStatus),i=H(f=>f.setSessionId),a=H(f=>f.setError),c=H(f=>f.clearMessages),u=H(f=>f.resetTokens),d=H(f=>f.addMessage),m=H(f=>f.setLatestContextSize);l.useEffect(()=>t?t.onSessionUpdate(b=>{const N=b._meta,v=N?.context_size||b.context_size;if(v!=null){const C=v;Ce.info("✅ Received context_size from session update",{context_size:C,totalEstimated:C.totalEstimated,isReplay:N?.isReplay}),m(C)}if(b.message&&(Ce.debug("Session update with message",{message:b.message}),b.message.role!=="tool")){const C=b.message.content.map(_=>_.type==="text"?_.text:"").join(""),U=[];for(const _ of b.message.content)if(_.type==="image"){const M=_;M.source?.data?U.push({mimeType:M.source.media_type||"image/png",data:M.source.data}):M.data&&U.push({mimeType:M.mimeType||"image/png",data:M.data})}const B=H.getState().messages,D=B[B.length-1],I=N?.isReplay===!0;if(b.message.role==="assistant"&&D?.role==="assistant"&&C&&I)Ce.debug("Appending replay text to existing assistant message",{existingLength:D.content.length,appendingLength:C.length}),H.getState().updateMessage(D.id,{content:D.content+C});else if(b.message.role==="assistant"&&D?.role==="assistant"&&D.content===""&&C)Ce.debug("Appending text to existing empty assistant message"),H.getState().updateMessage(D.id,{content:D.content+C});else{const _={id:b.message.id,role:b.message.role,content:C,timestamp:b.message.timestamp,isStreaming:!1,...U.length>0?{images:U}:{}};d(_)}}}):void 0,[t,d,m]);const p=l.useCallback(async()=>{if(!t){a("No client available");return}try{r("connecting"),a(null),await t.connect();const f=t.getCurrentSession();if(f?.id&&(i(f.id),typeof window<"u")){const b=new URL(window.location.href);b.searchParams.set("session",f.id),window.history.replaceState({},"",b.toString())}r("connected")}catch(f){Ce.error("Failed to connect",{error:f instanceof Error?f.message:String(f)});const b=f instanceof Error?f.message:String(f);a(b),r("error")}},[t,r,i,a]),g=l.useCallback(async f=>{if(!t){a("No client available");return}try{r("connecting"),a(null),c(),u();const b=await t.loadSession(f);i(b),r("connected"),Ce.info("Session loaded successfully",{sessionId:b})}catch(b){Ce.warn("Failed to load session, creating new one instead",{sessionId:f,error:b instanceof Error?b.message:String(b)});try{await p();const N=await t.startSession();if(i(N),c(),u(),typeof window<"u"){const v=new URL(window.location.href);v.searchParams.set("session",N),window.history.replaceState({},"",v.toString())}Ce.info("Created new session after failed load",{sessionId:N})}catch(N){const v=N instanceof Error?N.message:String(N);a(`Failed to load or create session: ${v}`),r("error")}}},[t,r,i,a,c,u,p]),x=l.useCallback(async()=>{if(!t)return a("No client available"),null;try{const f=await t.startSession();if(i(f),H.getState().messages.length===0&&(c(),u()),typeof window<"u"){const N=new URL(window.location.href);N.searchParams.set("session",f),window.history.pushState({},"",N.toString())}return f}catch(f){const b=f instanceof Error?f.message:String(f);return a(b),null}},[t,i,a,c,u]),h=l.useCallback(async()=>{if(t)try{await t.disconnect(),r("disconnected"),i(null)}catch(f){const b=f instanceof Error?f.message:String(f);a(b)}},[t,r,i,a]);return l.useEffect(()=>{!t||n!=="disconnected"||(s?(Ce.info("Loading initial session from URL",{sessionId:s}),g(s)):p())},[t,n,s,p,g]),{connectionStatus:n,sessionId:o,connect:p,loadSession:g,startSession:x,disconnect:h}}const xs="town-message-history",or=100;function rr(){const[t,s]=l.useState(-1),[n,o]=l.useState(""),r=l.useCallback(()=>{try{const m=localStorage.getItem(xs);return m?JSON.parse(m):[]}catch{return[]}},[]),i=l.useCallback(m=>{const p=m.trim();if(p){try{const g=r();if(g[0]===p)return;const x=[p,...g].slice(0,or);localStorage.setItem(xs,JSON.stringify(x))}catch{}s(-1),o("")}},[r]),a=l.useCallback(m=>{const p=r();if(p.length===0)return null;t===-1&&o(m);const g=Math.min(t+1,p.length-1);if(g===t)return null;const x=p[g];return x===void 0?null:(s(g),x)},[t,r]),c=l.useCallback(()=>{if(t===-1)return null;const m=r();if(t===0){s(-1);const x=n;return o(""),x}const p=t-1,g=m[p];return g===void 0?null:(s(p),g)},[t,n,r]),u=l.useCallback(()=>{t!==-1&&(s(-1),o(""))},[t]);return{addToHistory:i,navigatePrevious:a,navigateNext:c,resetNavigation:u,isBrowsingHistory:t!==-1,historyIndex:t}}const Ke=ue("use-tool-calls","debug");function ir(t){const s=H(c=>c.toolCalls),n=H(c=>c.addToolCall),o=H(c=>c.updateToolCall),r=H(c=>c.addToolCallToCurrentMessage),i=H(c=>c.updateToolCallInCurrentMessage),a=H(c=>c.addSourcesByToolCallId);return l.useEffect(()=>{if(!t)return;Ke.info("useToolCalls: subscribing to session updates");const c=t.onSessionUpdate(u=>{Ke.info("useToolCalls: received session update",{type:u.type,sessionId:u.sessionId}),u.type==="tool_call"?(Ke.info("useToolCalls: processing tool_call",{toolCallId:u.toolCall.id,title:u.toolCall.title}),n(u.sessionId,u.toolCall),r(u.toolCall)):u.type==="tool_call_update"?(Ke.info("useToolCalls: processing tool_call_update",{toolCallId:u.toolCallUpdate.id}),o(u.sessionId,u.toolCallUpdate),i(u.toolCallUpdate)):u.type==="sources"&&(Ke.info("useToolCalls: processing sources",{sourcesCount:u.sources.length,sourceIds:u.sources.map(d=>d.id),toolCallIds:u.sources.map(d=>d.toolCallId)}),a(u.sources))});return()=>{c()}},[t,n,o,r,i,a]),{toolCalls:s,getToolCallsForSession:c=>{const u=s[c];return u&&u.length>0?u:Object.values(s).flat()}}}const lr=q({name:w(),description:w().optional(),parameters:ae(w(),de()).optional()}),cr=q({name:w(),description:w(),parameters:ae(w(),de()),required:te(w()).optional()}),dr=q({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:te(lr).optional(),tools:te(cr).optional(),supportedFormats:te(w()).optional()}),ur=ie(["initializing","ready","busy","error","terminated"]);q({status:ur,info:dr.optional(),pid:F().optional(),error:w().optional(),uptime:F().optional()});const hn=ie(["idle","connecting","connected","active","streaming","error","disconnected"]),mr=q({agentPath:w(),agentArgs:te(w()).optional(),environment:ae(w(),w()).optional(),workingDirectory:w().optional(),timeout:F().optional()}),pr=q({agentName:w().optional(),agentVersion:w().optional(),capabilities:te(w()).optional(),startedAt:vt(),lastActivityAt:vt().optional()});q({id:w(),status:hn,config:mr,metadata:pr.optional(),messages:te(cn),error:w().optional()});const dt=q({sessionId:w(),status:hn.optional(),message:cn.optional(),error:w().optional(),_meta:ae(w(),de()).optional()}),fr=dt.extend({type:ee("tool_call"),toolCall:fn,messageId:w().optional()}),gr=dt.extend({type:ee("tool_call_update"),toolCallUpdate:Vo,messageId:w().optional()}),hr=dt.extend({type:ee("tool_output"),toolOutput:q({id:w(),content:te(Bt()).optional(),rawOutput:ae(w(),de()).optional()}),messageId:w().optional()}),xr=dt.extend({type:ee("sources"),sources:te(dn)}),br=dt.extend({type:ee("generic").optional()});Na([fr,gr,hr,xr,br]);const yr=[{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 vr{data;constructor(s=yr){this.data=s}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(s){const n=r=>{for(const i of r){if(i.id===s)return i;if(i.children){const a=n(i.children);if(a)return a}}},o=n(this.data);return Promise.resolve(o?.children||[])}async getItemDetails(s){const n=r=>{for(const i of r){if(i.id===s)return i;if(i.children){const a=n(i.children);if(a)return a}}},o=n(this.data);if(!o)throw new Error(`Item with id ${s} not found`);return Promise.resolve(o)}}function y(...t){return Ca(Sa(t))}const wr=Te("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"}}),re=l.forwardRef(({className:t,variant:s,size:n,asChild:o=!1,...r},i)=>{const a=o?ye:"button";return e.jsx(a,{className:y(wr({variant:s,size:n,className:t})),ref:i,...r})});re.displayName="Button";const ge=Ma,he=Ea,xe=Aa,be=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(_a,{children:e.jsx(_s,{ref:o,sideOffset:s,className:y("z-[9999] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));be.displayName=_s.displayName;const Gt=({className:t,children:s,...n})=>e.jsx("div",{className:y("flex items-center gap-1",t),...n,children:s}),Ve=({tooltip:t,children:s,label:n,className:o,variant:r="ghost",size:i="sm",...a})=>{const c=e.jsxs(re,{className:y("relative size-7 p-1.5 text-muted-foreground hover:text-foreground",o),size:i,type:"button",variant:r,...a,children:[s,e.jsx("span",{className:"sr-only",children:n||t})]});return t?e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:c}),e.jsx(be,{children:e.jsx("p",{children:t})})]})}):c},Re=l.forwardRef(({className:t,...s},n)=>e.jsx(re,{ref:n,variant:"ghost",size:"icon",className:y("rounded-full",t),...s}));Re.displayName="IconButton";const ut=Da,mt=Ua,jr=l.forwardRef(({className:t,inset:s,children:n,...o},r)=>e.jsxs(Ms,{ref:r,className:y("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",s&&"pl-8",t),...o,children:[n,e.jsx(tt,{className:"ml-auto h-4 w-4"})]}));jr.displayName=Ms.displayName;const Nr=l.forwardRef(({className:t,...s},n)=>e.jsx(Es,{ref:n,className:y("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...s}));Nr.displayName=Es.displayName;const qe=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(Pa,{children:e.jsx(As,{ref:o,sideOffset:s,className:y("z-50 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-popover p-0.5 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...n})}));qe.displayName=As.displayName;const je=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx(Ps,{ref:o,className:y("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...n}));je.displayName=Ps.displayName;const Cr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Ds,{ref:o,className:y("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Us,{children:e.jsx(lt,{className:"h-4 w-4"})})}),s]}));Cr.displayName=Ds.displayName;const Sr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(zs,{ref:o,className:y("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Us,{children:e.jsx(Tt,{className:"h-2 w-2 fill-current"})})}),s]}));Sr.displayName=zs.displayName;const kr=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx($s,{ref:o,className:y("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...n}));kr.displayName=$s.displayName;const xn=l.forwardRef(({className:t,...s},n)=>e.jsx(Ls,{ref:n,className:y("-mx-1 my-1 h-px bg-border",t),...s}));xn.displayName=Ls.displayName;const Tr=256,Ir="calc(100vw - 104px)",bn=450,bs=250,ys=800,Rr=720,_r=56,Mr=_r*2;function yn(t){l.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 At=768;function vn(){const[t,s]=l.useState(void 0);return l.useEffect(()=>{const n=window.matchMedia(`(max-width: ${At-1}px)`),o=()=>{s(window.innerWidth<At)};return n.addEventListener("change",o),s(window.innerWidth<At),()=>n.removeEventListener("change",o)},[]),!!t}const pt={smooth:[.25,.1,.25,1]},Er={duration:.25,ease:pt.smooth},vs={duration:.15,ease:pt.smooth},Ar={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},Pr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},ws={initial:{opacity:0,x:-20},animate:{opacity:1,x:0}},js={duration:.25,ease:pt.smooth,delay:.1},Dr={initial:{opacity:0},animate:{opacity:1},exit:{opacity:0}},Ur={initial:{x:"100%"},animate:{x:0},exit:{x:"100%"}},zr={initial:{opacity:0,x:20},animate:{opacity:1,x:0}},$r={duration:.25,ease:pt.smooth,delay:.1},Lr={duration:.15,ease:pt.smooth},Or=Te("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"}}),wn=l.forwardRef(({className:t,type:s,variant:n,...o},r)=>e.jsx("input",{type:s,className:y(Or({variant:n,className:t})),ref:r,...o}));wn.displayName="Input";const Fr="sidebar_state",Br=3600*24*7,Hr="s",jn=l.createContext(null);function _e(){const t=l.useContext(jn);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const Nn=l.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:n,className:o,style:r,children:i,...a},c)=>{const u=vn(),[d,m]=l.useState(!1),[p,g]=l.useState(t),x=s??p,h=l.useCallback(v=>{const C=typeof v=="function"?v(x):v;n?n(C):g(C),document.cookie=`${Fr}=${C}; path=/; max-age=${Br}`},[n,x]),f=l.useCallback(()=>u?m(v=>!v):h(v=>!v),[u,h]);l.useEffect(()=>{const v=C=>{C.key.toLowerCase()===Hr&&C.shiftKey&&(C.metaKey||C.ctrlKey)&&(C.preventDefault(),f())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[f]);const b=x?"expanded":"collapsed",N=l.useMemo(()=>({state:b,open:x,setOpen:h,isMobile:u,openMobile:d,setOpenMobile:m,toggleSidebar:f}),[b,x,h,u,d,f]);return e.jsx(jn.Provider,{value:N,children:e.jsx(ge,{delayDuration:0,children:e.jsx("div",{className:y("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",o),ref:c,style:r,...a,children:i})})})});Nn.displayName="SidebarProvider";const Cn=l.forwardRef(({className:t,children:s},n)=>{const{isMobile:o,open:r,openMobile:i,setOpenMobile:a}=_e();return yn(o&&i),o?e.jsx(ot,{initial:!1,children:i&&e.jsxs(e.Fragment,{children:[e.jsx(ke.div,{className:"fixed inset-0 z-40 bg-background/80",variants:Dr,initial:"initial",animate:"animate",exit:"exit",transition:vs,onClick:()=>a(!1),"aria-label":"Close sidebar"}),e.jsx(ke.aside,{ref:n,className:y("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:Ir},variants:Pr,initial:"initial",animate:"animate",exit:"exit",transition:vs,"data-sidebar":"sidebar","data-mobile":"true",children:e.jsx(ke.div,{className:"flex flex-col h-full overflow-y-auto",variants:ws,initial:"initial",animate:"animate",transition:js,children:s})})]})}):e.jsx("div",{className:"group peer hidden md:block","data-state":r?"expanded":"collapsed","data-side":"left",ref:n,children:e.jsx(ot,{initial:!1,mode:"wait",children:r&&e.jsx(ke.aside,{className:y("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:Tr},variants:Ar,initial:"initial",animate:"animate",exit:"exit",transition:Er,"data-sidebar":"sidebar",children:e.jsx(ke.div,{className:"flex flex-col h-full overflow-y-auto",variants:ws,initial:"initial",animate:"animate",transition:js,children:s})})})})});Cn.displayName="Sidebar";const Wr=l.forwardRef(({className:t,onClick:s,...n},o)=>{const{toggleSidebar:r}=_e();return e.jsxs(re,{className:y("h-7 w-7",t),"data-sidebar":"trigger",onClick:i=>{s?.(i),r()},ref:o,size:"icon",variant:"ghost",...n,children:[e.jsx(Ha,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Wr.displayName="SidebarTrigger";const Vr=l.forwardRef(({className:t,...s},n)=>{const{toggleSidebar:o}=_e();return e.jsx("button",{type:"button","aria-label":"Toggle Sidebar",className:y("-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:hover:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),"data-sidebar":"rail",onClick:o,ref:n,tabIndex:-1,title:"Toggle Sidebar",...s})});Vr.displayName="SidebarRail";const Sn=l.forwardRef(({className:t,children:s,...n},o)=>{const{isMobile:r,open:i}=_e();return e.jsx("main",{className:y("relative flex w-full flex-1 flex-col bg-background transition-all duration-250",!r&&i&&"md:pl-64",t),ref:o,...n,children:s})});Sn.displayName="SidebarInset";const qr=l.forwardRef(({className:t,...s},n)=>e.jsx(wn,{className:y("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),"data-sidebar":"input",ref:n,...s}));qr.displayName="SidebarInput";const kn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex flex-col gap-2 p-2",t),"data-sidebar":"header",ref:n,...s}));kn.displayName="SidebarHeader";const Tn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex flex-col gap-2 p-2",t),"data-sidebar":"footer",ref:n,...s}));Tn.displayName="SidebarFooter";const Kr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("mx-2 h-px w-auto bg-sidebar-border",t),"data-sidebar":"separator",ref:n,...s}));Kr.displayName="SidebarSeparator";const In=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),"data-sidebar":"content",ref:n,...s}));In.displayName="SidebarContent";const Je=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("relative flex w-full min-w-0 flex-col p-4",t),"data-sidebar":"group",ref:n,...s}));Je.displayName="SidebarGroup";const Rn=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ye:"div";return e.jsx(r,{className:y("flex h-8 shrink-0 items-center rounded-md px-2 font-medium text-sidebar-foreground/70 text-xs outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),"data-sidebar":"group-label",ref:o,...n})});Rn.displayName="SidebarGroupLabel";const Yr=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ye:"button";return e.jsx(r,{className:y("absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"group-action",ref:o,type:"button",...n})});Yr.displayName="SidebarGroupAction";const Ze=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("w-full text-sm",t),"data-sidebar":"group-content",ref:n,...s}));Ze.displayName="SidebarGroupContent";const _n=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:y("flex w-full min-w-0 flex-col gap-1",t),"data-sidebar":"menu",ref:n,...s}));_n.displayName="SidebarMenu";const Mn=l.forwardRef(({className:t,...s},n)=>e.jsx("li",{className:y("group/menu-item relative",t),"data-sidebar":"menu-item",ref:n,...s}));Mn.displayName="SidebarMenuItem";const Qr=Te("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"}}),En=l.forwardRef(({asChild:t=!1,isActive:s=!1,variant:n="default",size:o="default",tooltip:r,className:i,...a},c)=>{const u=t?ye:"button",{isMobile:d,state:m}=_e(),p=e.jsx(u,{className:y(Qr({variant:n,size:o}),i),"data-active":s,"data-sidebar":"menu-button","data-size":o,ref:c,type:t?void 0:"button",...a});return r?(typeof r=="string"&&(r={children:r}),e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:p}),e.jsx(be,{align:"center",hidden:m!=="collapsed"||d,side:"right",...r})]})):p});En.displayName="SidebarMenuButton";const An=l.forwardRef(({className:t,asChild:s=!1,showOnHover:n=!1,...o},r)=>{const i=s?ye:"button";return e.jsx(i,{className:y("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",n&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",t),"data-sidebar":"menu-action",ref:r,type:s?void 0:"button",...o})});An.displayName="SidebarMenuAction";const Gr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 font-medium text-sidebar-foreground text-xs tabular-nums","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-badge",ref:n,...s}));Gr.displayName="SidebarMenuBadge";const Xr=l.forwardRef(({className:t,showIcon:s=!1,...n},o)=>{const r=l.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{className:y("flex h-8 items-center gap-2 rounded-md px-2",t),"data-sidebar":"menu-skeleton",ref:o,...n,children:[s&&e.jsx("div",{className:"size-4 rounded-md bg-sidebar-accent-foreground/10 animate-pulse","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 rounded-md bg-sidebar-accent-foreground/10 animate-pulse","data-sidebar":"menu-skeleton-text",style:{maxWidth:r}})]})});Xr.displayName="SidebarMenuSkeleton";const Jr=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:y("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-sub",ref:n,...s}));Jr.displayName="SidebarMenuSub";const Zr=l.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));Zr.displayName="SidebarMenuSubItem";const ei=l.forwardRef(({asChild:t=!1,size:s="md",isActive:n,className:o,...r},i)=>{const a=t?ye:"a";return e.jsx(a,{className:y("-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",s==="sm"&&"text-xs",s==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",o),"data-active":n,"data-sidebar":"menu-sub-button","data-size":s,ref:i,...r})});ei.displayName="SidebarMenuSubButton";const ti=({session:t,isActive:s,onSelect:n,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a})=>e.jsxs(Mn,{children:[e.jsx(En,{asChild:!0,isActive:s,onClick:()=>{n(t.sessionId),a(!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(ut,{modal:!0,children:[e.jsx(mt,{asChild:!0,children:e.jsxs(An,{className:"mr-0.5 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",showOnHover:!s,children:[e.jsx(Wa,{}),e.jsx("span",{className:"sr-only",children:"More"})]})}),e.jsxs(qe,{align:"end",side:"bottom",children:[e.jsx(je,{className:"cursor-pointer",disabled:!o,onSelect:()=>o?.(t.sessionId),children:"Rename"}),e.jsx(je,{className:"cursor-pointer",disabled:!r,onSelect:()=>r?.(t.sessionId),children:"Archive"}),e.jsx(xn,{}),e.jsx(je,{className:y("cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive"),disabled:!i,onSelect:()=>i?.(t.sessionId),children:"Delete"})]})]})]}),Ye=l.memo(ti,(t,s)=>!(t.isActive!==s.isActive||t.session.sessionId!==s.session.sessionId||t.session.firstUserMessage!==s.session.firstUserMessage)),si=ue("session-history"),ni=t=>{const s=new Date;return t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},ai=t=>{const s=new Date;return s.setDate(s.getDate()-1),t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},oi=t=>{const s=new Date,n=new Date(s.getTime()-10080*60*1e3),o=new Date(s.getTime()-720*60*60*1e3);return t.reduce((r,i)=>{const a=new Date(i.updatedAt);return ni(a)?r.today.push(i):ai(a)?r.yesterday.push(i):a>n?r.lastWeek.push(i):a>o?r.lastMonth.push(i):r.older.push(i),r},{today:[],yesterday:[],lastWeek:[],lastMonth:[],older:[]})};function ri({client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:o,onArchiveSession:r,onDeleteSession:i}){const{setOpenMobile:a}=_e(),[c,u]=l.useState([]),[d,m]=l.useState(!1),p=l.useCallback(async()=>{if(t){m(!0);try{const f=(await t.listSessions()).filter(b=>!b.isSubagentSession);u(f)}catch(h){si.error("Failed to fetch sessions",{error:h})}finally{m(!1)}}},[t]);l.useEffect(()=>{p()},[p]);const g=h=>{if(h!==s)if(n)n(h);else{const f=new URL(window.location.href);f.searchParams.set("session",h),window.location.href=f.toString()}};if(!t)return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx("div",{className:"flex w-full flex-row items-center justify-center gap-2 px-2 text-sm text-muted-foreground",children:"Connect to an agent to see session history"})})});if(d)return e.jsxs(Je,{children:[e.jsx(Rn,{children:"Today"}),e.jsx(Ze,{children:e.jsx("div",{className:"flex flex-col",children:[44,32,28,64,52].map(h=>e.jsx("div",{className:"flex h-8 items-center gap-2 rounded-md px-2",children:e.jsx("div",{className:"h-4 flex-1 rounded-md bg-sidebar-accent-foreground/10 animate-pulse",style:{maxWidth:`${h}%`}})},h))})})]});if(c.length===0)return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx("div",{className:"flex w-full flex-row items-center justify-center gap-2 px-2 py-4 text-sm text-muted-foreground",children:"Your sessions will appear here once you start chatting!"})})});const x=oi(c);return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx(_n,{children:e.jsxs("div",{className:"flex flex-col gap-6",children:[x.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"}),x.today.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.yesterday.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.lastWeek.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.lastMonth.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.older.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]})]})})})})}const ii={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Pn=l.createContext(ii);function li({children:t,defaultTheme:s="system",storageKey:n="vite-ui-theme"}){const[o,r]=l.useState(()=>localStorage.getItem(n)||s),[i,a]=l.useState("light");l.useEffect(()=>{const u=window.document.documentElement;if(u.classList.remove("light","dark"),o==="system"){const d=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";u.classList.add(d),a(d);return}u.classList.add(o),a(o)},[o]);const c={theme:o,setTheme:u=>{localStorage.setItem(n,u),r(u)},resolvedTheme:i};return e.jsx(Pn.Provider,{value:c,children:t})}const Xt=()=>{const t=l.useContext(Pn);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function ci(){const{setTheme:t}=Xt();return e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsxs(Re,{children:[e.jsx(Zs,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(en,{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(qe,{align:"end",children:[e.jsx(je,{onClick:()=>t("light"),children:"Light"}),e.jsx(je,{onClick:()=>t("dark"),children:"Dark"}),e.jsx(je,{onClick:()=>t("system"),children:"System"})]})]})}function di({client:t,currentSessionId:s,onSessionSelect:n,onNewSession:o,onRenameSession:r,onArchiveSession:i,onDeleteSession:a,className:c}){const{setOpenMobile:u}=_e(),d=()=>{if(o)o();else{const m=new URL(window.location.href);m.searchParams.delete("session"),window.location.href=m.toString()}u(!1)};return e.jsxs(Cn,{className:y("group-data-[side=left]:border-r-0",c),children:[e.jsx(kn,{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(Re,{onClick:d,"aria-label":"New Chat",variant:"default",children:e.jsx(Va,{className:"size-4"})})]})}),e.jsx(In,{className:"gap-6",children:e.jsx(ri,{client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:r,onArchiveSession:i,onDeleteSession:a})}),e.jsx(Tn,{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(ci,{}),e.jsx(Re,{"aria-label":"Settings",children:e.jsx(Ht,{className:"size-4 text-muted-foreground"})})]})})]})}const ui=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));ui.displayName="Card";const mi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("flex flex-col space-y-1.5 p-6",t),...s}));mi.displayName="CardHeader";const pi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("text-2xl font-semibold leading-none tracking-tight",t),...s}));pi.displayName="CardTitle";const fi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("text-sm text-muted-foreground",t),...s}));fi.displayName="CardDescription";const gi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("p-6 pt-0",t),...s}));gi.displayName="CardContent";const hi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("flex items-center p-6 pt-0",t),...s}));hi.displayName="CardFooter";const Dn=l.forwardRef(({title:t,titleElement:s,description:n,guideUrl:o,guideText:r="Guide",suggestedPrompts:i=[],onPromptClick:a,onGuideClick:c,onOpenFiles:u,onOpenSettings:d,toolsAndMcpsCount:m,onPromptHover:p,onPromptLeave:g,className:x,...h},f)=>{const b=C=>{a?.(C)},N=()=>{o&&window.open(o,"_blank","noopener,noreferrer"),c?.()},v=[];for(let C=0;C<i.length;C+=2)v.push(i.slice(C,C+2));return e.jsxs("div",{ref:f,className:y("flex flex-col items-start",x),...h,children:[s?e.jsx("div",{className:"text-heading-4 text-text-primary mb-6",children:s}):e.jsx("h3",{className:"text-heading-4 text-text-primary mb-6",children:t}),e.jsx("p",{className:"text-subheading text-text-secondary max-w-prose mb-6",children:n}),(u||d)&&e.jsxs("div",{className:"flex items-center gap-1 -ml-3 mb-6",children:[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.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:"View Files"}),e.jsx(tt,{className:"size-4 text-foreground shrink-0"})]}),d&&e.jsxs("button",{type:"button",onClick:d,className:"inline-flex items-center gap-1 py-1.5 pr-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsxs("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:["View Tools & MCPs",m!==void 0&&m>0&&e.jsxs("span",{className:"ml-1",children:["(",m,")"]})]}),e.jsx(tt,{className:"size-4 text-foreground shrink-0"})]})]}),(o||c)&&e.jsxs("button",{type:"button",onClick:N,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:r}),e.jsx(tt,{className:"size-4 text-foreground shrink-0"})]}),i.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[e.jsx("p",{className:"text-text-tertiary",children:"Suggested Prompts"}),e.jsx("div",{className:"flex flex-col gap-2.5",children:v.map(C=>e.jsx("div",{className:"flex gap-2.5 items-center",children:C.map(U=>e.jsx("button",{type:"button",onClick:()=>b(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))},C.join("-")))})]})]})});Dn.displayName="ChatEmptyState";const Un=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex items-center justify-between",t),...n,children:s}));Un.displayName="ChatHeader.Root";const xi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("h1",{ref:o,className:y("m-0 text-subheading font-semibold",t),...n,children:s}));xi.displayName="ChatHeader.Title";const bi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex items-center gap-3",t),...n,children:s}));bi.displayName="ChatHeader.Actions";const zn=l.forwardRef(({commands:t=[],showCommandMenu:s,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:r,setMenuItemCount:i,triggerCounter:a,onChange:c,onClose:u,className:d,...m},p)=>{const g=l.useCallback((f,b)=>{const N=f.toLowerCase(),v=b.toLowerCase();if(!b)return 1;if(N.includes(v))return 1-v.length/N.length;let C=0;for(let U=0;U<N.length&&C<v.length;U++)N[U]===v[C]&&C++;return C===v.length?.5-C/N.length:0},[]),x=l.useMemo(()=>t.map(f=>({...f,score:Math.max(g(f.label,n),f.description?g(f.description,n):0)})).filter(f=>f.score>0).sort((f,b)=>b.score-f.score),[t,n,g]);l.useEffect(()=>{i(x.length)},[x.length,i]),l.useEffect(()=>{r(0)},[r]);const h=l.useRef(0);return l.useEffect(()=>{a>0&&a!==h.current&&x[o]&&(h.current=a,x[o].onSelect(),c(""),u?.())},[a,x,o,c,u]),!s||x.length===0?null:e.jsxs("div",{ref:p,className:y("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",d),...m,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:x.map((f,b)=>e.jsxs("button",{type:"button",onClick:()=>{f.onSelect(),c(""),u?.()},className:y("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",b===o&&"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))})]})});zn.displayName="ChatInputCommandMenu";const $n=l.createContext(void 0),ft=()=>{const t=l.useContext($n);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},Ln=l.forwardRef(({client:t,startSession:s,value:n,onChange:o,onSubmit:r,onCancel:i,disabled:a=!1,isSubmitting:c,submitOnEnter:u=!0,className:d,children:m,...p},g)=>{const x=l.useRef(null),h=l.useCallback(async()=>Promise.resolve(null),[]),f=nr(t??null,s??h),b=H(R=>R.isStreaming),{addToHistory:N,navigatePrevious:v,navigateNext:C,resetNavigation:U}=rr(),B=t&&s,D=B?f.value:n||"",I=B?f.onChange:o||(()=>{}),_=B?f.onSubmit:r||(async()=>{}),M=B?f.isSubmitting||b:c||!1,E=l.useCallback(async()=>{const R=D.trim();R&&N(R),await _()},[D,N,_]),[K,Y]=l.useState(!1),[z,W]=l.useState(""),[V,T]=l.useState(0),[k,S]=l.useState(0),[P,j]=l.useState(0),O=l.useCallback(()=>{j(R=>R+1)},[]),Q=async R=>{R.preventDefault(),D.trim()&&!M&&!a&&(await E(),setTimeout(()=>{x.current?.focus()},0))},$=R=>{const A=R.target;!(A.tagName==="BUTTON"||A.tagName==="INPUT"||A.tagName==="TEXTAREA"||A.closest("button"))&&x.current&&x.current.focus()},X=R=>{const A=R.target;!(A.tagName==="BUTTON"||A.tagName==="INPUT"||A.tagName==="TEXTAREA"||A.closest("button"))&&R.key===" "&&(R.preventDefault(),x.current&&x.current.focus())};return l.useEffect(()=>{const R=document.querySelector('textarea[name="chat-input"]');R&&x.current!==R&&(x.current=R)},[]),l.useEffect(()=>{!D&&x.current&&(x.current.style.height="auto",x.current.style.overflowY="hidden")},[D]),e.jsx($n.Provider,{value:{value:D,onChange:I,onSubmit:E,onCancel:i,disabled:a,isSubmitting:M,submitOnEnter:u,showCommandMenu:K,setShowCommandMenu:Y,commandMenuQuery:z,setCommandMenuQuery:W,selectedMenuIndex:V,setSelectedMenuIndex:T,menuItemCount:k,setMenuItemCount:S,triggerMenuSelect:O,triggerCounter:P,navigateHistoryPrevious:v,navigateHistoryNext:C,resetHistoryNavigation:U},children:e.jsx("form",{ref:g,onSubmit:Q,onClick:$,onKeyDown:X,className:y("relative w-full divide-y rounded-xl border bg-background shadow-md",d),...p,children:m})})});Ln.displayName="ChatInput.Root";const On=l.forwardRef(({asChild:t=!1,className:s,onKeyDown:n,onFilesDropped:o,children:r,...i},a)=>{const{value:c,onChange:u,onSubmit:d,disabled:m,isSubmitting:p,submitOnEnter:g,showCommandMenu:x,setShowCommandMenu:h,setCommandMenuQuery:f,setSelectedMenuIndex:b,menuItemCount:N,triggerMenuSelect:v,navigateHistoryPrevious:C,navigateHistoryNext:U,resetHistoryNavigation:B}=ft(),D=l.useRef(null),[I,_]=l.useState(!1),M=l.useCallback(k=>{D.current=k,typeof a=="function"?a(k):a&&(a.current=k)},[a]),E=k=>new Promise((S,P)=>{const j=new FileReader;j.readAsDataURL(k),j.onload=()=>{const O=j.result.split(",")[1];S(O||"")},j.onerror=O=>P(O)}),T={ref:M,name:"chat-input",value:c,onChange:k=>{const S=k.target.value;if(u(S),B(),S.startsWith("/")&&!S.includes(`
6
+ [Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Z.warn("Stream ended without isComplete flag"),u(z,{isStreaming:!1,streamingStartTime:void 0})),i(!1),a(null),v.current=null)}catch(W){const V=W instanceof Error?W.message:String(W);d(V),i(!1),a(null),v.current=null,u(z,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,n,N,c,u,i,a,d,m,p,g,x,h,f,b]);return{messages:n,isStreaming:o,sendMessage:U,editAndResend:D,cancel:B}}const hs=ue("use-chat-input","debug");function nr(t,s){const n=H(g=>g.input),o=H(g=>g.setInputValue),r=H(g=>g.setInputSubmitting),i=H(g=>g.addFileAttachment),a=H(g=>g.removeFileAttachment),{sendMessage:c}=gn(t,s),u=l.useCallback(g=>{o(g)},[o]),d=l.useCallback(async()=>{const g=H.getState().input;if(!g.value.trim()||g.isSubmitting)return;const x=g.value,h=g.attachedFiles,f=g.selectedPromptParameters;hs.debug("Submitting message with attachments",{messageLength:x.length,attachmentCount:h.length,hasAttachments:h.length>0,hasPromptParameters:!!f&&Object.keys(f).length>0,promptParameters:f}),o(""),r(!0);try{await c(x,h.length>0?h:void 0,f&&Object.keys(f).length>0?f:void 0),H.setState(b=>({input:{...b.input,attachedFiles:[]}}))}catch(b){hs.error("Failed to send message",{error:b instanceof Error?b.message:String(b)})}finally{r(!1)}},[o,r,c]),m=l.useCallback(g=>{i(g)},[i]),p=l.useCallback(g=>{a(g)},[a]);return{value:n.value,isSubmitting:n.isSubmitting,attachedFiles:n.attachedFiles,onChange:u,onSubmit:d,onAttachFile:m,onRemoveFile:p}}const Ce=ue("use-chat-session","debug");function ar(t,s){const n=H(f=>f.connectionStatus),o=H(f=>f.sessionId),r=H(f=>f.setConnectionStatus),i=H(f=>f.setSessionId),a=H(f=>f.setError),c=H(f=>f.clearMessages),u=H(f=>f.resetTokens),d=H(f=>f.addMessage),m=H(f=>f.setLatestContextSize);l.useEffect(()=>t?t.onSessionUpdate(b=>{const N=b._meta,v=N?.context_size||b.context_size;if(v!=null){const C=v;Ce.info("✅ Received context_size from session update",{context_size:C,totalEstimated:C.totalEstimated,isReplay:N?.isReplay}),m(C)}if(b.message&&(Ce.debug("Session update with message",{message:b.message}),b.message.role!=="tool")){const C=b.message.content.map(_=>_.type==="text"?_.text:"").join(""),U=[];for(const _ of b.message.content)if(_.type==="image"){const M=_;M.source?.data?U.push({mimeType:M.source.media_type||"image/png",data:M.source.data}):M.data&&U.push({mimeType:M.mimeType||"image/png",data:M.data})}const B=H.getState().messages,D=B[B.length-1],I=N?.isReplay===!0;if(b.message.role==="assistant"&&D?.role==="assistant"&&C&&I)Ce.debug("Appending replay text to existing assistant message",{existingLength:D.content.length,appendingLength:C.length}),H.getState().updateMessage(D.id,{content:D.content+C});else if(b.message.role==="assistant"&&D?.role==="assistant"&&D.content===""&&C)Ce.debug("Appending text to existing empty assistant message"),H.getState().updateMessage(D.id,{content:D.content+C});else{const _={id:b.message.id,role:b.message.role,content:C,timestamp:b.message.timestamp,isStreaming:!1,...U.length>0?{images:U}:{}};d(_)}}}):void 0,[t,d,m]);const p=l.useCallback(async()=>{if(!t){a("No client available");return}try{r("connecting"),a(null),await t.connect();const f=t.getCurrentSession();if(f?.id&&(i(f.id),typeof window<"u")){const b=new URL(window.location.href);b.searchParams.set("session",f.id),window.history.replaceState({},"",b.toString())}r("connected")}catch(f){Ce.error("Failed to connect",{error:f instanceof Error?f.message:String(f)});const b=f instanceof Error?f.message:String(f);a(b),r("error")}},[t,r,i,a]),g=l.useCallback(async f=>{if(!t){a("No client available");return}try{r("connecting"),a(null),c(),u();const b=await t.loadSession(f);i(b),r("connected"),Ce.info("Session loaded successfully",{sessionId:b})}catch(b){Ce.warn("Failed to load session, creating new one instead",{sessionId:f,error:b instanceof Error?b.message:String(b)});try{await p();const N=await t.startSession();if(i(N),c(),u(),typeof window<"u"){const v=new URL(window.location.href);v.searchParams.set("session",N),window.history.replaceState({},"",v.toString())}Ce.info("Created new session after failed load",{sessionId:N})}catch(N){const v=N instanceof Error?N.message:String(N);a(`Failed to load or create session: ${v}`),r("error")}}},[t,r,i,a,c,u,p]),x=l.useCallback(async()=>{if(!t)return a("No client available"),null;try{const f=await t.startSession();if(i(f),H.getState().messages.length===0&&(c(),u()),typeof window<"u"){const N=new URL(window.location.href);N.searchParams.set("session",f),window.history.pushState({},"",N.toString())}return f}catch(f){const b=f instanceof Error?f.message:String(f);return a(b),null}},[t,i,a,c,u]),h=l.useCallback(async()=>{if(t)try{await t.disconnect(),r("disconnected"),i(null)}catch(f){const b=f instanceof Error?f.message:String(f);a(b)}},[t,r,i,a]);return l.useEffect(()=>{!t||n!=="disconnected"||(s?(Ce.info("Loading initial session from URL",{sessionId:s}),g(s)):p())},[t,n,s,p,g]),{connectionStatus:n,sessionId:o,connect:p,loadSession:g,startSession:x,disconnect:h}}const xs="town-message-history",or=100;function rr(){const[t,s]=l.useState(-1),[n,o]=l.useState(""),r=l.useCallback(()=>{try{const m=localStorage.getItem(xs);return m?JSON.parse(m):[]}catch{return[]}},[]),i=l.useCallback(m=>{const p=m.trim();if(p){try{const g=r();if(g[0]===p)return;const x=[p,...g].slice(0,or);localStorage.setItem(xs,JSON.stringify(x))}catch{}s(-1),o("")}},[r]),a=l.useCallback(m=>{const p=r();if(p.length===0)return null;t===-1&&o(m);const g=Math.min(t+1,p.length-1);if(g===t)return null;const x=p[g];return x===void 0?null:(s(g),x)},[t,r]),c=l.useCallback(()=>{if(t===-1)return null;const m=r();if(t===0){s(-1);const x=n;return o(""),x}const p=t-1,g=m[p];return g===void 0?null:(s(p),g)},[t,n,r]),u=l.useCallback(()=>{t!==-1&&(s(-1),o(""))},[t]);return{addToHistory:i,navigatePrevious:a,navigateNext:c,resetNavigation:u,isBrowsingHistory:t!==-1,historyIndex:t}}const Ke=ue("use-tool-calls","debug");function ir(t){const s=H(c=>c.toolCalls),n=H(c=>c.addToolCall),o=H(c=>c.updateToolCall),r=H(c=>c.addToolCallToCurrentMessage),i=H(c=>c.updateToolCallInCurrentMessage),a=H(c=>c.addSourcesByToolCallId);return l.useEffect(()=>{if(!t)return;Ke.info("useToolCalls: subscribing to session updates");const c=t.onSessionUpdate(u=>{Ke.info("useToolCalls: received session update",{type:u.type,sessionId:u.sessionId}),u.type==="tool_call"?(Ke.info("useToolCalls: processing tool_call",{toolCallId:u.toolCall.id,title:u.toolCall.title}),n(u.sessionId,u.toolCall),r(u.toolCall)):u.type==="tool_call_update"?(Ke.info("useToolCalls: processing tool_call_update",{toolCallId:u.toolCallUpdate.id}),o(u.sessionId,u.toolCallUpdate),i(u.toolCallUpdate)):u.type==="sources"&&(Ke.info("useToolCalls: processing sources",{sourcesCount:u.sources.length,sourceIds:u.sources.map(d=>d.id),toolCallIds:u.sources.map(d=>d.toolCallId)}),a(u.sources))});return()=>{c()}},[t,n,o,r,i,a]),{toolCalls:s,getToolCallsForSession:c=>{const u=s[c];return u&&u.length>0?u:Object.values(s).flat()}}}const lr=q({name:w(),description:w().optional(),parameters:ae(w(),de()).optional()}),cr=q({name:w(),description:w(),parameters:ae(w(),de()),required:te(w()).optional()}),dr=q({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:te(lr).optional(),tools:te(cr).optional(),supportedFormats:te(w()).optional()}),ur=ie(["initializing","ready","busy","error","terminated"]);q({status:ur,info:dr.optional(),pid:F().optional(),error:w().optional(),uptime:F().optional()});const hn=ie(["idle","connecting","connected","active","streaming","error","disconnected"]),mr=q({agentPath:w(),agentArgs:te(w()).optional(),environment:ae(w(),w()).optional(),workingDirectory:w().optional(),timeout:F().optional()}),pr=q({agentName:w().optional(),agentVersion:w().optional(),capabilities:te(w()).optional(),startedAt:vt(),lastActivityAt:vt().optional()});q({id:w(),status:hn,config:mr,metadata:pr.optional(),messages:te(cn),error:w().optional()});const dt=q({sessionId:w(),status:hn.optional(),message:cn.optional(),error:w().optional(),_meta:ae(w(),de()).optional()}),fr=dt.extend({type:ee("tool_call"),toolCall:fn,messageId:w().optional()}),gr=dt.extend({type:ee("tool_call_update"),toolCallUpdate:Vo,messageId:w().optional()}),hr=dt.extend({type:ee("tool_output"),toolOutput:q({id:w(),content:te(Bt()).optional(),rawOutput:ae(w(),de()).optional()}),messageId:w().optional()}),xr=dt.extend({type:ee("sources"),sources:te(dn)}),br=dt.extend({type:ee("generic").optional()});Na([fr,gr,hr,xr,br]);const yr=[{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 vr{data;constructor(s=yr){this.data=s}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(s){const n=r=>{for(const i of r){if(i.id===s)return i;if(i.children){const a=n(i.children);if(a)return a}}},o=n(this.data);return Promise.resolve(o?.children||[])}async getItemDetails(s){const n=r=>{for(const i of r){if(i.id===s)return i;if(i.children){const a=n(i.children);if(a)return a}}},o=n(this.data);if(!o)throw new Error(`Item with id ${s} not found`);return Promise.resolve(o)}}function y(...t){return Ca(Sa(t))}const wr=Te("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"}}),re=l.forwardRef(({className:t,variant:s,size:n,asChild:o=!1,...r},i)=>{const a=o?ye:"button";return e.jsx(a,{className:y(wr({variant:s,size:n,className:t})),ref:i,...r})});re.displayName="Button";const ge=Ma,he=Aa,xe=Ea,be=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(_a,{children:e.jsx(_s,{ref:o,sideOffset:s,className:y("z-[9999] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));be.displayName=_s.displayName;const Gt=({className:t,children:s,...n})=>e.jsx("div",{className:y("flex items-center gap-1",t),...n,children:s}),Ve=({tooltip:t,children:s,label:n,className:o,variant:r="ghost",size:i="sm",...a})=>{const c=e.jsxs(re,{className:y("relative size-7 p-1.5 text-muted-foreground hover:text-foreground",o),size:i,type:"button",variant:r,...a,children:[s,e.jsx("span",{className:"sr-only",children:n||t})]});return t?e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:c}),e.jsx(be,{children:e.jsx("p",{children:t})})]})}):c},Re=l.forwardRef(({className:t,...s},n)=>e.jsx(re,{ref:n,variant:"ghost",size:"icon",className:y("rounded-full",t),...s}));Re.displayName="IconButton";const ut=Da,mt=Ua,jr=l.forwardRef(({className:t,inset:s,children:n,...o},r)=>e.jsxs(Ms,{ref:r,className:y("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",s&&"pl-8",t),...o,children:[n,e.jsx(tt,{className:"ml-auto h-4 w-4"})]}));jr.displayName=Ms.displayName;const Nr=l.forwardRef(({className:t,...s},n)=>e.jsx(As,{ref:n,className:y("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...s}));Nr.displayName=As.displayName;const qe=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(Pa,{children:e.jsx(Es,{ref:o,sideOffset:s,className:y("z-50 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-popover p-0.5 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...n})}));qe.displayName=Es.displayName;const je=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx(Ps,{ref:o,className:y("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...n}));je.displayName=Ps.displayName;const Cr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Ds,{ref:o,className:y("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Us,{children:e.jsx(lt,{className:"h-4 w-4"})})}),s]}));Cr.displayName=Ds.displayName;const Sr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(zs,{ref:o,className:y("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Us,{children:e.jsx(Tt,{className:"h-2 w-2 fill-current"})})}),s]}));Sr.displayName=zs.displayName;const kr=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx($s,{ref:o,className:y("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...n}));kr.displayName=$s.displayName;const xn=l.forwardRef(({className:t,...s},n)=>e.jsx(Ls,{ref:n,className:y("-mx-1 my-1 h-px bg-border",t),...s}));xn.displayName=Ls.displayName;const Tr=256,Ir="calc(100vw - 104px)",bn=450,bs=250,ys=800,Rr=720,_r=56,Mr=_r*2;function yn(t){l.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 Et=768;function vn(){const[t,s]=l.useState(void 0);return l.useEffect(()=>{const n=window.matchMedia(`(max-width: ${Et-1}px)`),o=()=>{s(window.innerWidth<Et)};return n.addEventListener("change",o),s(window.innerWidth<Et),()=>n.removeEventListener("change",o)},[]),!!t}const pt={smooth:[.25,.1,.25,1]},Ar={duration:.25,ease:pt.smooth},vs={duration:.15,ease:pt.smooth},Er={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},Pr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},ws={initial:{opacity:0,x:-20},animate:{opacity:1,x:0}},js={duration:.25,ease:pt.smooth,delay:.1},Dr={initial:{opacity:0},animate:{opacity:1},exit:{opacity:0}},Ur={initial:{x:"100%"},animate:{x:0},exit:{x:"100%"}},zr={initial:{opacity:0,x:20},animate:{opacity:1,x:0}},$r={duration:.25,ease:pt.smooth,delay:.1},Lr={duration:.15,ease:pt.smooth},Or=Te("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"}}),wn=l.forwardRef(({className:t,type:s,variant:n,...o},r)=>e.jsx("input",{type:s,className:y(Or({variant:n,className:t})),ref:r,...o}));wn.displayName="Input";const Fr="sidebar_state",Br=3600*24*7,Hr="s",jn=l.createContext(null);function _e(){const t=l.useContext(jn);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const Nn=l.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:n,className:o,style:r,children:i,...a},c)=>{const u=vn(),[d,m]=l.useState(!1),[p,g]=l.useState(t),x=s??p,h=l.useCallback(v=>{const C=typeof v=="function"?v(x):v;n?n(C):g(C),document.cookie=`${Fr}=${C}; path=/; max-age=${Br}`},[n,x]),f=l.useCallback(()=>u?m(v=>!v):h(v=>!v),[u,h]);l.useEffect(()=>{const v=C=>{C.key.toLowerCase()===Hr&&C.shiftKey&&(C.metaKey||C.ctrlKey)&&(C.preventDefault(),f())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[f]);const b=x?"expanded":"collapsed",N=l.useMemo(()=>({state:b,open:x,setOpen:h,isMobile:u,openMobile:d,setOpenMobile:m,toggleSidebar:f}),[b,x,h,u,d,f]);return e.jsx(jn.Provider,{value:N,children:e.jsx(ge,{delayDuration:0,children:e.jsx("div",{className:y("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",o),ref:c,style:r,...a,children:i})})})});Nn.displayName="SidebarProvider";const Cn=l.forwardRef(({className:t,children:s},n)=>{const{isMobile:o,open:r,openMobile:i,setOpenMobile:a}=_e();return yn(o&&i),o?e.jsx(ot,{initial:!1,children:i&&e.jsxs(e.Fragment,{children:[e.jsx(ke.div,{className:"fixed inset-0 z-40 bg-background/80",variants:Dr,initial:"initial",animate:"animate",exit:"exit",transition:vs,onClick:()=>a(!1),"aria-label":"Close sidebar"}),e.jsx(ke.aside,{ref:n,className:y("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:Ir},variants:Pr,initial:"initial",animate:"animate",exit:"exit",transition:vs,"data-sidebar":"sidebar","data-mobile":"true",children:e.jsx(ke.div,{className:"flex flex-col h-full overflow-y-auto",variants:ws,initial:"initial",animate:"animate",transition:js,children:s})})]})}):e.jsx("div",{className:"group peer hidden md:block","data-state":r?"expanded":"collapsed","data-side":"left",ref:n,children:e.jsx(ot,{initial:!1,mode:"wait",children:r&&e.jsx(ke.aside,{className:y("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:Tr},variants:Er,initial:"initial",animate:"animate",exit:"exit",transition:Ar,"data-sidebar":"sidebar",children:e.jsx(ke.div,{className:"flex flex-col h-full overflow-y-auto",variants:ws,initial:"initial",animate:"animate",transition:js,children:s})})})})});Cn.displayName="Sidebar";const Wr=l.forwardRef(({className:t,onClick:s,...n},o)=>{const{toggleSidebar:r}=_e();return e.jsxs(re,{className:y("h-7 w-7",t),"data-sidebar":"trigger",onClick:i=>{s?.(i),r()},ref:o,size:"icon",variant:"ghost",...n,children:[e.jsx(Ha,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Wr.displayName="SidebarTrigger";const Vr=l.forwardRef(({className:t,...s},n)=>{const{toggleSidebar:o}=_e();return e.jsx("button",{type:"button","aria-label":"Toggle Sidebar",className:y("-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:hover:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),"data-sidebar":"rail",onClick:o,ref:n,tabIndex:-1,title:"Toggle Sidebar",...s})});Vr.displayName="SidebarRail";const Sn=l.forwardRef(({className:t,children:s,...n},o)=>{const{isMobile:r,open:i}=_e();return e.jsx("main",{className:y("relative flex w-full flex-1 flex-col bg-background transition-all duration-250",!r&&i&&"md:pl-64",t),ref:o,...n,children:s})});Sn.displayName="SidebarInset";const qr=l.forwardRef(({className:t,...s},n)=>e.jsx(wn,{className:y("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),"data-sidebar":"input",ref:n,...s}));qr.displayName="SidebarInput";const kn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex flex-col gap-2 p-2",t),"data-sidebar":"header",ref:n,...s}));kn.displayName="SidebarHeader";const Tn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex flex-col gap-2 p-2",t),"data-sidebar":"footer",ref:n,...s}));Tn.displayName="SidebarFooter";const Kr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("mx-2 h-px w-auto bg-sidebar-border",t),"data-sidebar":"separator",ref:n,...s}));Kr.displayName="SidebarSeparator";const In=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),"data-sidebar":"content",ref:n,...s}));In.displayName="SidebarContent";const Je=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("relative flex w-full min-w-0 flex-col p-4",t),"data-sidebar":"group",ref:n,...s}));Je.displayName="SidebarGroup";const Rn=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ye:"div";return e.jsx(r,{className:y("flex h-8 shrink-0 items-center rounded-md px-2 font-medium text-sidebar-foreground/70 text-xs outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),"data-sidebar":"group-label",ref:o,...n})});Rn.displayName="SidebarGroupLabel";const Yr=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ye:"button";return e.jsx(r,{className:y("absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"group-action",ref:o,type:"button",...n})});Yr.displayName="SidebarGroupAction";const Ze=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("w-full text-sm",t),"data-sidebar":"group-content",ref:n,...s}));Ze.displayName="SidebarGroupContent";const _n=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:y("flex w-full min-w-0 flex-col gap-1",t),"data-sidebar":"menu",ref:n,...s}));_n.displayName="SidebarMenu";const Mn=l.forwardRef(({className:t,...s},n)=>e.jsx("li",{className:y("group/menu-item relative",t),"data-sidebar":"menu-item",ref:n,...s}));Mn.displayName="SidebarMenuItem";const Qr=Te("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"}}),An=l.forwardRef(({asChild:t=!1,isActive:s=!1,variant:n="default",size:o="default",tooltip:r,className:i,...a},c)=>{const u=t?ye:"button",{isMobile:d,state:m}=_e(),p=e.jsx(u,{className:y(Qr({variant:n,size:o}),i),"data-active":s,"data-sidebar":"menu-button","data-size":o,ref:c,type:t?void 0:"button",...a});return r?(typeof r=="string"&&(r={children:r}),e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:p}),e.jsx(be,{align:"center",hidden:m!=="collapsed"||d,side:"right",...r})]})):p});An.displayName="SidebarMenuButton";const En=l.forwardRef(({className:t,asChild:s=!1,showOnHover:n=!1,...o},r)=>{const i=s?ye:"button";return e.jsx(i,{className:y("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",n&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",t),"data-sidebar":"menu-action",ref:r,type:s?void 0:"button",...o})});En.displayName="SidebarMenuAction";const Gr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:y("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 font-medium text-sidebar-foreground text-xs tabular-nums","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-badge",ref:n,...s}));Gr.displayName="SidebarMenuBadge";const Xr=l.forwardRef(({className:t,showIcon:s=!1,...n},o)=>{const r=l.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{className:y("flex h-8 items-center gap-2 rounded-md px-2",t),"data-sidebar":"menu-skeleton",ref:o,...n,children:[s&&e.jsx("div",{className:"size-4 rounded-md bg-sidebar-accent-foreground/10 animate-pulse","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 rounded-md bg-sidebar-accent-foreground/10 animate-pulse","data-sidebar":"menu-skeleton-text",style:{maxWidth:r}})]})});Xr.displayName="SidebarMenuSkeleton";const Jr=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:y("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-sub",ref:n,...s}));Jr.displayName="SidebarMenuSub";const Zr=l.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));Zr.displayName="SidebarMenuSubItem";const ei=l.forwardRef(({asChild:t=!1,size:s="md",isActive:n,className:o,...r},i)=>{const a=t?ye:"a";return e.jsx(a,{className:y("-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",s==="sm"&&"text-xs",s==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",o),"data-active":n,"data-sidebar":"menu-sub-button","data-size":s,ref:i,...r})});ei.displayName="SidebarMenuSubButton";const ti=({session:t,isActive:s,onSelect:n,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a})=>e.jsxs(Mn,{children:[e.jsx(An,{asChild:!0,isActive:s,onClick:()=>{n(t.sessionId),a(!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(ut,{modal:!0,children:[e.jsx(mt,{asChild:!0,children:e.jsxs(En,{className:"mr-0.5 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",showOnHover:!s,children:[e.jsx(Wa,{}),e.jsx("span",{className:"sr-only",children:"More"})]})}),e.jsxs(qe,{align:"end",side:"bottom",children:[e.jsx(je,{className:"cursor-pointer",disabled:!o,onSelect:()=>o?.(t.sessionId),children:"Rename"}),e.jsx(je,{className:"cursor-pointer",disabled:!r,onSelect:()=>r?.(t.sessionId),children:"Archive"}),e.jsx(xn,{}),e.jsx(je,{className:y("cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive"),disabled:!i,onSelect:()=>i?.(t.sessionId),children:"Delete"})]})]})]}),Ye=l.memo(ti,(t,s)=>!(t.isActive!==s.isActive||t.session.sessionId!==s.session.sessionId||t.session.firstUserMessage!==s.session.firstUserMessage)),si=ue("session-history"),ni=t=>{const s=new Date;return t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},ai=t=>{const s=new Date;return s.setDate(s.getDate()-1),t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},oi=t=>{const s=new Date,n=new Date(s.getTime()-10080*60*1e3),o=new Date(s.getTime()-720*60*60*1e3);return t.reduce((r,i)=>{const a=new Date(i.updatedAt);return ni(a)?r.today.push(i):ai(a)?r.yesterday.push(i):a>n?r.lastWeek.push(i):a>o?r.lastMonth.push(i):r.older.push(i),r},{today:[],yesterday:[],lastWeek:[],lastMonth:[],older:[]})};function ri({client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:o,onArchiveSession:r,onDeleteSession:i}){const{setOpenMobile:a}=_e(),[c,u]=l.useState([]),[d,m]=l.useState(!1),p=l.useCallback(async()=>{if(t){m(!0);try{const f=(await t.listSessions()).filter(b=>!b.isSubagentSession);u(f)}catch(h){si.error("Failed to fetch sessions",{error:h})}finally{m(!1)}}},[t]);l.useEffect(()=>{p()},[p]);const g=h=>{if(h!==s)if(n)n(h);else{const f=new URL(window.location.href);f.searchParams.set("session",h),window.location.href=f.toString()}};if(!t)return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx("div",{className:"flex w-full flex-row items-center justify-center gap-2 px-2 text-sm text-muted-foreground",children:"Connect to an agent to see session history"})})});if(d)return e.jsxs(Je,{children:[e.jsx(Rn,{children:"Today"}),e.jsx(Ze,{children:e.jsx("div",{className:"flex flex-col",children:[44,32,28,64,52].map(h=>e.jsx("div",{className:"flex h-8 items-center gap-2 rounded-md px-2",children:e.jsx("div",{className:"h-4 flex-1 rounded-md bg-sidebar-accent-foreground/10 animate-pulse",style:{maxWidth:`${h}%`}})},h))})})]});if(c.length===0)return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx("div",{className:"flex w-full flex-row items-center justify-center gap-2 px-2 py-4 text-sm text-muted-foreground",children:"Your sessions will appear here once you start chatting!"})})});const x=oi(c);return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx(_n,{children:e.jsxs("div",{className:"flex flex-col gap-6",children:[x.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"}),x.today.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.yesterday.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.lastWeek.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.lastMonth.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]}),x.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"}),x.older.map(h=>e.jsx(Ye,{session:h,isActive:h.sessionId===s,onSelect:g,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a},h.sessionId))]})]})})})})}const ii={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Pn=l.createContext(ii);function li({children:t,defaultTheme:s="system",storageKey:n="vite-ui-theme"}){const[o,r]=l.useState(()=>localStorage.getItem(n)||s),[i,a]=l.useState("light");l.useEffect(()=>{const u=window.document.documentElement;if(u.classList.remove("light","dark"),o==="system"){const d=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";u.classList.add(d),a(d);return}u.classList.add(o),a(o)},[o]);const c={theme:o,setTheme:u=>{localStorage.setItem(n,u),r(u)},resolvedTheme:i};return e.jsx(Pn.Provider,{value:c,children:t})}const Xt=()=>{const t=l.useContext(Pn);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function ci(){const{setTheme:t}=Xt();return e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsxs(Re,{children:[e.jsx(Zs,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(en,{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(qe,{align:"end",children:[e.jsx(je,{onClick:()=>t("light"),children:"Light"}),e.jsx(je,{onClick:()=>t("dark"),children:"Dark"}),e.jsx(je,{onClick:()=>t("system"),children:"System"})]})]})}function di({client:t,currentSessionId:s,onSessionSelect:n,onNewSession:o,onRenameSession:r,onArchiveSession:i,onDeleteSession:a,className:c}){const{setOpenMobile:u}=_e(),d=()=>{if(o)o();else{const m=new URL(window.location.href);m.searchParams.delete("session"),window.location.href=m.toString()}u(!1)};return e.jsxs(Cn,{className:y("group-data-[side=left]:border-r-0",c),children:[e.jsx(kn,{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(Re,{onClick:d,"aria-label":"New Chat",variant:"default",children:e.jsx(Va,{className:"size-4"})})]})}),e.jsx(In,{className:"gap-6",children:e.jsx(ri,{client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:r,onArchiveSession:i,onDeleteSession:a})}),e.jsx(Tn,{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(ci,{}),e.jsx(Re,{"aria-label":"Settings",children:e.jsx(Ht,{className:"size-4 text-muted-foreground"})})]})})]})}const ui=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));ui.displayName="Card";const mi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("flex flex-col space-y-1.5 p-6",t),...s}));mi.displayName="CardHeader";const pi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("text-2xl font-semibold leading-none tracking-tight",t),...s}));pi.displayName="CardTitle";const fi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("text-sm text-muted-foreground",t),...s}));fi.displayName="CardDescription";const gi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("p-6 pt-0",t),...s}));gi.displayName="CardContent";const hi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:y("flex items-center p-6 pt-0",t),...s}));hi.displayName="CardFooter";const Dn=l.forwardRef(({title:t,titleElement:s,description:n,guideUrl:o,guideText:r="Guide",suggestedPrompts:i=[],onPromptClick:a,onGuideClick:c,onOpenFiles:u,onOpenSettings:d,toolsAndMcpsCount:m,onPromptHover:p,onPromptLeave:g,className:x,...h},f)=>{const b=C=>{a?.(C)},N=()=>{o&&window.open(o,"_blank","noopener,noreferrer"),c?.()},v=[];for(let C=0;C<i.length;C+=2)v.push(i.slice(C,C+2));return e.jsxs("div",{ref:f,className:y("flex flex-col items-start",x),...h,children:[s?e.jsx("div",{className:"text-heading-4 text-text-primary mb-6",children:s}):e.jsx("h3",{className:"text-heading-4 text-text-primary mb-6",children:t}),e.jsx("p",{className:"text-subheading text-text-secondary max-w-prose mb-6",children:n}),(u||d)&&e.jsxs("div",{className:"flex items-center gap-1 -ml-3 mb-6",children:[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.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:"View Files"}),e.jsx(tt,{className:"size-4 text-foreground shrink-0"})]}),d&&e.jsxs("button",{type:"button",onClick:d,className:"inline-flex items-center gap-1 py-1.5 pr-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsxs("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:["View Tools & MCPs",m!==void 0&&m>0&&e.jsxs("span",{className:"ml-1",children:["(",m,")"]})]}),e.jsx(tt,{className:"size-4 text-foreground shrink-0"})]})]}),(o||c)&&e.jsxs("button",{type:"button",onClick:N,className:"inline-flex items-center gap-1 py-1.5 pr-3 -ml-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsx("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:r}),e.jsx(tt,{className:"size-4 text-foreground shrink-0"})]}),i.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[e.jsx("p",{className:"text-text-tertiary",children:"Suggested Prompts"}),e.jsx("div",{className:"flex flex-col gap-2.5",children:v.map(C=>e.jsx("div",{className:"flex gap-2.5 items-center",children:C.map(U=>e.jsx("button",{type:"button",onClick:()=>b(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))},C.join("-")))})]})]})});Dn.displayName="ChatEmptyState";const Un=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex items-center justify-between",t),...n,children:s}));Un.displayName="ChatHeader.Root";const xi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("h1",{ref:o,className:y("m-0 text-subheading font-semibold",t),...n,children:s}));xi.displayName="ChatHeader.Title";const bi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex items-center gap-3",t),...n,children:s}));bi.displayName="ChatHeader.Actions";const zn=l.forwardRef(({commands:t=[],showCommandMenu:s,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:r,setMenuItemCount:i,triggerCounter:a,onChange:c,onClose:u,className:d,...m},p)=>{const g=l.useCallback((f,b)=>{const N=f.toLowerCase(),v=b.toLowerCase();if(!b)return 1;if(N.includes(v))return 1-v.length/N.length;let C=0;for(let U=0;U<N.length&&C<v.length;U++)N[U]===v[C]&&C++;return C===v.length?.5-C/N.length:0},[]),x=l.useMemo(()=>t.map(f=>({...f,score:Math.max(g(f.label,n),f.description?g(f.description,n):0)})).filter(f=>f.score>0).sort((f,b)=>b.score-f.score),[t,n,g]);l.useEffect(()=>{i(x.length)},[x.length,i]),l.useEffect(()=>{r(0)},[r]);const h=l.useRef(0);return l.useEffect(()=>{a>0&&a!==h.current&&x[o]&&(h.current=a,x[o].onSelect(),c(""),u?.())},[a,x,o,c,u]),!s||x.length===0?null:e.jsxs("div",{ref:p,className:y("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",d),...m,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:x.map((f,b)=>e.jsxs("button",{type:"button",onClick:()=>{f.onSelect(),c(""),u?.()},className:y("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",b===o&&"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))})]})});zn.displayName="ChatInputCommandMenu";const $n=l.createContext(void 0),ft=()=>{const t=l.useContext($n);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},Ln=l.forwardRef(({client:t,startSession:s,value:n,onChange:o,onSubmit:r,onCancel:i,disabled:a=!1,isSubmitting:c,submitOnEnter:u=!0,className:d,children:m,...p},g)=>{const x=l.useRef(null),h=l.useCallback(async()=>Promise.resolve(null),[]),f=nr(t??null,s??h),b=H(R=>R.isStreaming),{addToHistory:N,navigatePrevious:v,navigateNext:C,resetNavigation:U}=rr(),B=t&&s,D=B?f.value:n||"",I=B?f.onChange:o||(()=>{}),_=B?f.onSubmit:r||(async()=>{}),M=B?f.isSubmitting||b:c||!1,A=l.useCallback(async()=>{const R=D.trim();R&&N(R),await _()},[D,N,_]),[K,Y]=l.useState(!1),[z,W]=l.useState(""),[V,T]=l.useState(0),[k,S]=l.useState(0),[P,j]=l.useState(0),O=l.useCallback(()=>{j(R=>R+1)},[]),Q=async R=>{R.preventDefault(),D.trim()&&!M&&!a&&(await A(),setTimeout(()=>{x.current?.focus()},0))},$=R=>{const E=R.target;!(E.tagName==="BUTTON"||E.tagName==="INPUT"||E.tagName==="TEXTAREA"||E.closest("button"))&&x.current&&x.current.focus()},X=R=>{const E=R.target;!(E.tagName==="BUTTON"||E.tagName==="INPUT"||E.tagName==="TEXTAREA"||E.closest("button"))&&R.key===" "&&(R.preventDefault(),x.current&&x.current.focus())};return l.useEffect(()=>{const R=document.querySelector('textarea[name="chat-input"]');R&&x.current!==R&&(x.current=R)},[]),l.useEffect(()=>{!D&&x.current&&(x.current.style.height="auto",x.current.style.overflowY="hidden")},[D]),e.jsx($n.Provider,{value:{value:D,onChange:I,onSubmit:A,onCancel:i,disabled:a,isSubmitting:M,submitOnEnter:u,showCommandMenu:K,setShowCommandMenu:Y,commandMenuQuery:z,setCommandMenuQuery:W,selectedMenuIndex:V,setSelectedMenuIndex:T,menuItemCount:k,setMenuItemCount:S,triggerMenuSelect:O,triggerCounter:P,navigateHistoryPrevious:v,navigateHistoryNext:C,resetHistoryNavigation:U},children:e.jsx("form",{ref:g,onSubmit:Q,onClick:$,onKeyDown:X,className:y("relative w-full divide-y rounded-xl border bg-background shadow-md",d),...p,children:m})})});Ln.displayName="ChatInput.Root";const On=l.forwardRef(({asChild:t=!1,className:s,onKeyDown:n,onFilesDropped:o,children:r,...i},a)=>{const{value:c,onChange:u,onSubmit:d,disabled:m,isSubmitting:p,submitOnEnter:g,showCommandMenu:x,setShowCommandMenu:h,setCommandMenuQuery:f,setSelectedMenuIndex:b,menuItemCount:N,triggerMenuSelect:v,navigateHistoryPrevious:C,navigateHistoryNext:U,resetHistoryNavigation:B}=ft(),D=l.useRef(null),[I,_]=l.useState(!1),M=l.useCallback(k=>{D.current=k,typeof a=="function"?a(k):a&&(a.current=k)},[a]),A=k=>new Promise((S,P)=>{const j=new FileReader;j.readAsDataURL(k),j.onload=()=>{const O=j.result.split(",")[1];S(O||"")},j.onerror=O=>P(O)}),T={ref:M,name:"chat-input",value:c,onChange:k=>{const S=k.target.value;if(u(S),B(),S.startsWith("/")&&!S.includes(`
7
7
  `)){h(!0);const O=S.slice(1);f(O)}else h(!1),f("");const P=D.current;if(!P)return;P.style.height="auto";const j=Math.min(P.scrollHeight,164);P.style.height=`${j}px`,P.scrollHeight>164?P.style.overflowY="auto":P.style.overflowY="hidden"},onKeyDown:k=>{if(x&&N>0){if(k.key==="ArrowDown"){k.preventDefault(),b(S=>(S+1)%N);return}else if(k.key==="ArrowUp"){k.preventDefault(),b(S=>(S-1+N)%N);return}else if(k.key==="Enter"&&!k.shiftKey){k.preventDefault(),v();return}else if(k.key==="Escape"){k.preventDefault(),h(!1),f("");return}}if(!x){const S=D.current,P=S?.selectionStart===0&&S?.selectionEnd===0,j=S?.selectionStart===c.length&&S?.selectionEnd===c.length,O=c.includes(`
8
- `);if(k.key==="ArrowUp"&&(P||!c||!O)){const Q=C(c);if(Q!==null){k.preventDefault(),u(Q),setTimeout(()=>{D.current&&(D.current.selectionStart=Q.length,D.current.selectionEnd=Q.length)},0);return}}else if(k.key==="ArrowDown"&&(j||!c||!O)){const Q=U();if(Q!==null){k.preventDefault(),u(Q),setTimeout(()=>{D.current&&(D.current.selectionStart=Q.length,D.current.selectionEnd=Q.length)},0);return}}}g&&k.key==="Enter"&&!k.shiftKey&&(c.trim()&&!p&&!m?(k.preventDefault(),d()):(p||m)&&k.preventDefault()),n?.(k)},onDrop:async k=>{k.preventDefault(),_(!1);const S=k.dataTransfer.files;if(!S||S.length===0||!o)return;const P=[];for(const j of Array.from(S))if(j.type.startsWith("image/"))try{const O=await E(j);P.push({name:j.name,path:j.name,size:j.size,mimeType:j.type,data:O})}catch(O){console.error("Failed to process dropped file:",j.name,O)}P.length>0&&o(P)},onDragOver:k=>{k.preventDefault(),_(!0)},onDragLeave:k=>{k.preventDefault(),_(!1)},disabled:m,...i};return t&&l.isValidElement(r)?l.cloneElement(r,T):e.jsx("textarea",{...T,rows:1,className:y("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 max-h-[6lh] min-h-[44px]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-paragraph-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",I&&"ring-2 ring-primary ring-offset-2",s)})});On.displayName="ChatInput.Field";const Fn=l.forwardRef(({asChild:t=!1,className:s,disabled:n,children:o,...r},i)=>{const{value:a,disabled:c,isSubmitting:u}=ft();if(u)return null;const d=n||c||!a.trim(),m=t?ye:re;return e.jsx(m,{ref:i,type:"submit",disabled:d,variant:t?void 0:"default",size:"icon",className:y(!t&&"gap-1.5 rounded-full",s),...r,children:o})});Fn.displayName="ChatInput.Submit";const Bn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const{onCancel:i,isSubmitting:a}=ft(),c=t?ye:re;return a?e.jsx(c,{ref:r,type:"button",onClick:()=>i?.(),variant:t?void 0:"default",size:"icon",className:y(!t&&"gap-1.5 rounded-full",s),...o,children:n||e.jsx(qa,{className:"size-4 fill-current"})}):null});Bn.displayName="ChatInput.Stop";const Hn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex items-center justify-between p-2",t),...n,children:s}));Hn.displayName="ChatInput.Toolbar";const Wn=l.forwardRef(({asChild:t=!1,className:s,children:n,onClick:o,...r},i)=>{const{value:a,onChange:c,setShowCommandMenu:u,setCommandMenuQuery:d}=ft(),m=g=>{a.startsWith("/")||(c("/"),u(!0),d("")),o?.(g)},p=t?ye:re;return e.jsx(p,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:m,...r,children:n||e.jsx(Ka,{className:"size-4"})})});Wn.displayName="ChatInput.Actions";const Vn=l.forwardRef(({asChild:t=!1,className:s,children:n,onFilesSelected:o,...r},i)=>{const a=l.useRef(null),c=p=>new Promise((g,x)=>{const h=new FileReader;h.readAsDataURL(p),h.onload=()=>{const f=h.result.split(",")[1];g(f||"")},h.onerror=f=>x(f)}),u=async p=>{const g=p.target.files;if(!g||g.length===0)return;const x=[];for(const h of Array.from(g))if(h.type.startsWith("image/"))try{const f=await c(h);x.push({name:h.name,path:h.name,size:h.size,mimeType:h.type,data:f})}catch(f){console.error("Failed to process file:",h.name,f)}x.length>0&&o&&o(x),a.current&&(a.current.value="")},d=p=>{p.preventDefault(),a.current?.click()},m=t?ye:re;return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:a,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:u}),e.jsx(m,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:d,...r,children:n||e.jsx(Ya,{className:"size-4"})})]})});Vn.displayName="ChatInput.Attachment";const qn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const i=t?ye:re;return e.jsx(i,{ref:r,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),...o,children:n||e.jsx(Qa,{className:"size-4"})})});qn.displayName="ChatInput.VoiceInput";const Kn=l.forwardRef(({commands:t=[],className:s,onChange:n,...o},r)=>{const{showCommandMenu:i,commandMenuQuery:a,selectedMenuIndex:c,setSelectedMenuIndex:u,setMenuItemCount:d,triggerCounter:m,onChange:p,setShowCommandMenu:g,setCommandMenuQuery:x}=ft();return e.jsx(zn,{ref:r,commands:t,showCommandMenu:i,commandMenuQuery:a,selectedMenuIndex:c,setSelectedMenuIndex:u,setMenuItemCount:d,triggerCounter:m,onChange:p,onClose:()=>{g(!1),x("")},className:s,...o})});Kn.displayName="ChatInput.CommandMenu";function yi({parameters:t,className:s}){const n=H(c=>c.input.selectedPromptParameters),o=H(c=>c.setSelectedPromptParameters),r=l.useCallback(c=>c.defaultOptionId??c.options[0]?.id??"",[]);l.useEffect(()=>{if(!n||Object.keys(n).length===0){const c={};for(const u of t)c[u.id]=r(u);Object.keys(c).length>0&&o(c)}},[t,n,o,r]);const i=l.useCallback((c,u)=>{const d={...n,[c]:u};o(d)},[n,o]);if(t.length===0)return null;const a=t.map(c=>{const u=n?.[c.id],d=r(c),m=c.options.find(g=>g.id===u);return{param:c,selectedOption:m,isNonDefault:u&&u!==d}}).filter(c=>c.selectedOption);return e.jsx("div",{className:y("flex items-center gap-1",s),children:a.map(({param:c,selectedOption:u,isNonDefault:d})=>e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsxs("button",{type:"button",className:y("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",d?"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:u?.label}),e.jsx(fe,{className:"h-4 w-4 opacity-50"})]})}),e.jsx(qe,{align:"start",className:"min-w-[160px]",children:c.options.map(m=>e.jsx(je,{onClick:()=>i(c.id,m.id),className:y(n?.[c.id]===m.id&&"bg-accent"),children:m.label},m.id))})]},c.id))})}function vi(t){const[s,n]=l.useState({width:0,height:0});return l.useEffect(()=>{const o=t.current;if(!o)return;const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const c=a[0];if(!c)return;const{width:u,height:d}=c.contentRect;n({width:u,height:d})});r.observe(o);const i=o.getBoundingClientRect();return n({width:i.width,height:i.height}),()=>{r.disconnect()}},[t]),s}function wi(){const t=l.useRef(null),s=l.useRef(null),[n,o]=l.useState(!0),r=l.useRef(!0),i=l.useRef(!1),[a,c]=l.useState(!1),[u,d]=l.useState(!1),[m,p]=l.useState(0),[g,x]=l.useState(0),h=l.useRef(-1),f=l.useRef(!1),b=l.useRef(null);l.useEffect(()=>{r.current=n},[n]);const N=l.useCallback(()=>{if(!t.current)return!0;const{scrollTop:z,scrollHeight:W,clientHeight:V}=t.current;return z+V>=W-100},[]),v=l.useCallback(()=>{if(!t.current)return[];const z=t.current.querySelectorAll('[aria-label="user message"]');return Array.from(z)},[]),C=l.useCallback(()=>{const z=t.current;if(!z)return[];const W=z.getBoundingClientRect();return v().map((T,k)=>{const P=T.getBoundingClientRect().bottom<W.top+50,j=T.textContent||"",O=j.slice(0,100)+(j.length>100?"...":"");return{index:k,preview:O,element:T,isAboveFold:P}}).filter(({isAboveFold:T})=>T).map(({index:T,preview:k,element:S})=>({index:T,preview:k,element:S}))},[v]),U=l.useCallback((z,W="smooth")=>{const V=v();if(z<0||z>=V.length)return;const T=V[z];if(T){f.current=!0,b.current&&clearTimeout(b.current),T.scrollIntoView({behavior:W,block:"start"}),h.current=z,p(z);const k=V.length-1-z;x(k),d(k>0),b.current=setTimeout(()=>{f.current=!1},500)}},[v]),B=l.useCallback(()=>{const z=t.current;if(!z)return[];const W=z.getBoundingClientRect();return v().filter(T=>T.getBoundingClientRect().bottom<W.top+50)},[v]);l.useCallback(()=>B().length>0,[B]);const D=l.useCallback(()=>{const z=t.current;if(!z)return-1;const W=z.getBoundingClientRect(),V=v();for(let T=0;T<V.length;T++){const k=V[T]?.getBoundingClientRect();if(k&&(k.top>=W.top-50&&k.top<W.top+150||k.top<W.top&&k.bottom>W.top+50))return T}for(let T=V.length-1;T>=0;T--){const k=V[T]?.getBoundingClientRect();if(k&&k.bottom<W.top+50)return T}return-1},[v]);l.useCallback(()=>{const z=v(),W=h.current!==-1?h.current:D();return W===-1?!1:W<z.length-1},[v,D]);const I=l.useCallback((z="smooth")=>{t.current&&(t.current.scrollTo({top:t.current.scrollHeight,behavior:z}),h.current=-1)},[]),_=l.useCallback((z="smooth")=>{const W=t.current;if(!W)return;const V=v();if(V.length===0)return;const T=W.getBoundingClientRect(),k=[];for(let P=0;P<V.length;P++){const j=V[P]?.getBoundingClientRect();j&&j.bottom<T.top+50&&k.push(P)}if(k.length===0)return;let S;if(h.current===-1){const P=k[k.length-1];if(P===void 0)return;S=P}else{const P=k.filter(j=>j<h.current);if(P.length>0){const j=P[P.length-1];if(j===void 0)return;S=j}else{const j=k[0];if(j===void 0)return;S=j}}if(S>=0&&S<V.length){const P=V[S];if(P){f.current=!0,b.current&&clearTimeout(b.current),P.scrollIntoView({behavior:z,block:"start"}),h.current=S,p(S);const j=V.length-1-S;x(j),d(j>0),b.current=setTimeout(()=>{f.current=!1},500)}}},[v]),M=l.useCallback((z="smooth")=>{if(!t.current)return;const V=v();if(V.length!==0&&h.current!==-1){const T=h.current+1;if(T<V.length){const k=V[T];if(k){f.current=!0,b.current&&clearTimeout(b.current),k.scrollIntoView({behavior:z,block:"start"}),h.current=T,p(T);const S=V.length-1-T;x(S),d(S>0),b.current=setTimeout(()=>{f.current=!1},500)}}}},[v]);l.useCallback(()=>h.current>0?!0:B().length>0,[B]),l.useCallback(()=>{const z=v();return h.current===-1?!1:h.current<z.length-1},[v]);const E=l.useCallback(()=>{h.current=-1},[]);l.useEffect(()=>{const z=t.current;if(!z)return;let W;const V=()=>{i.current=!0,clearTimeout(W);const T=N();o(T),r.current=T;const k=B(),S=k.length>0;if(c(S),!f.current){const P=D();P!==-1&&(h.current=P);const j=v();p(k.length);const O=h.current!==-1?h.current:P,Q=O!==-1&&O<j.length-1?j.length-1-O:0;x(Q),d(Q>0)}W=setTimeout(()=>{i.current=!1},150)};return z.addEventListener("scroll",V,{passive:!0}),()=>{z.removeEventListener("scroll",V),clearTimeout(W)}},[N,D,v,B]),l.useEffect(()=>{const z=t.current;if(!z)return;const W=()=>{r.current&&!i.current&&requestAnimationFrame(()=>{z.scrollTo({top:z.scrollHeight,behavior:"instant"}),o(!0),r.current=!0})},V=new MutationObserver(W);V.observe(z,{childList:!0,subtree:!0,characterData:!0});const T=new ResizeObserver(W);return T.observe(z),Array.from(z.children).forEach(k=>{T.observe(k)}),()=>{V.disconnect(),T.disconnect()}},[]);function K(){o(!0),r.current=!0}function Y(){o(!1),r.current=!1}return{containerRef:t,endRef:s,isAtBottom:n,scrollToBottom:I,onViewportEnter:K,onViewportLeave:Y,isUserMessageAboveFold:a,hasMoreUserMessagesBelow:u,userMessagesAboveCount:m,userMessagesBelowCount:g,scrollToPreviousUserMessage:_,scrollToNextUserMessage:M,scrollToUserMessageByIndex:U,getUserMessagePreviews:C,resetUserMessageCycle:E}}const ji=({...t})=>e.jsx(ka,{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}),Jt=l.createContext(void 0),Me=()=>{const t=l.useContext(Jt);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},Yn=l.forwardRef(({defaultSidebarOpen:t=!1,defaultPanelSize:s="hidden",defaultActiveTab:n="todo",className:o,children:r,...i},a)=>{const[c,u]=l.useState(t),[d,m]=l.useState(s),[p,g]=l.useState(n),x=l.useMemo(()=>d!=="hidden",[d]),h=l.useRef(!1),[f,b]=l.useState(!1),[N,v]=l.useState(bn),[C,U]=l.useState(0),B=l.useCallback(()=>{h.current||(h.current=!0,m(I=>I==="hidden"?"large":"hidden"),setTimeout(()=>{h.current=!1},350))},[]),D=l.useCallback(I=>{m(I?"large":"hidden")},[]);return l.useEffect(()=>{const I=_=>{_.key.toLowerCase()==="b"&&(_.metaKey||_.ctrlKey)&&!_.shiftKey&&(_.preventDefault(),B())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[B]),e.jsx(Jt.Provider,{value:{sidebarOpen:c,setSidebarOpen:u,panelSize:d,setPanelSize:I=>{m(I),D(I!=="hidden")},activeTab:p,setActiveTab:g,panelOpen:x,setPanelOpen:D,togglePanel:B,isDraggingAside:f,setIsDraggingAside:b,asideWidth:N,setAsideWidth:v,mainWidth:C,setMainWidth:U},children:e.jsx("div",{ref:a,"data-panel-state":x?"expanded":"collapsed",className:y("flex h-screen flex-row bg-background text-foreground overflow-hidden",o),...i,children:r})})});Yn.displayName="ChatLayout.Root";const Ni=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("relative z-10 border-b border-border bg-card shrink-0",t),...n,children:s}));Ni.displayName="ChatLayout.Header";const Qn=l.forwardRef(({className:t,children:s},n)=>{const{panelOpen:o,isDraggingAside:r,asideWidth:i,setMainWidth:a}=Me(),c=l.useRef(null),{width:u}=vi(c);return l.useEffect(()=>{a(u)},[u,a]),l.useImperativeHandle(n,()=>c.current),e.jsx("div",{ref:c,className:y("flex flex-1 flex-col overflow-hidden h-full min-w-0",!r&&"transition-[padding] duration-250",t),style:{paddingRight:o?i:0},children:s})});Qn.displayName="ChatLayout.Main";const Gn=l.forwardRef(({showToaster:t=!0,className:s,children:n,...o},r)=>e.jsxs("div",{ref:r,className:y("relative flex flex-1 flex-col overflow-hidden",s),...o,children:[n,t&&e.jsx(ji,{})]}));Gn.displayName="ChatLayout.Body";const Xn=l.forwardRef(({className:t,children:s,onScrollChange:n,showScrollToBottom:o=!0,initialScrollToBottom:r=!0,...i},a)=>{const{mainWidth:c}=Me(),{containerRef:u,endRef:d,isAtBottom:m,scrollToBottom:p,userMessagesAboveCount:g,scrollToUserMessageByIndex:x}=wi(),h=l.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=l.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}}}),[]),[b,N]=l.useState(!1),[v,C]=l.useState([]),[U,B]=l.useState(null),[D,I]=l.useState(0),_=l.useRef(null),M=l.useRef(null),E=l.useRef(null),K=l.useRef(0),Y=l.useCallback(()=>{const $=u.current;if(!$)return[];const X=$.querySelectorAll('[aria-label="user message"]');return Array.from(X).map((R,A)=>{const J=R.textContent||"",G=J.slice(0,100)+(J.length>100?"...":"");return{index:A,preview:G}})},[u]);l.useEffect(()=>{const $=u.current;if(!$)return;const X=()=>{const A=Y();C(A)};X();const R=new MutationObserver(X);return R.observe($,{childList:!0,subtree:!0}),()=>{R.disconnect()}},[u,Y]),l.useEffect(()=>()=>{_.current&&clearTimeout(_.current),M.current&&clearTimeout(M.current),E.current!==null&&cancelAnimationFrame(E.current)},[]);const z=c>Rr+Mr,W=v.length>1&&z,V=l.useCallback($=>{const R=$.currentTarget.getBoundingClientRect(),A=$.clientY-R.top;K.current=A,E.current===null&&(E.current=requestAnimationFrame(()=>{I(K.current),E.current=null}))},[]),T=l.useCallback(()=>{M.current&&(clearTimeout(M.current),M.current=null),_.current=setTimeout(()=>{N(!0)},1500)},[]),k=l.useCallback(()=>{_.current&&(clearTimeout(_.current),_.current=null),M.current=setTimeout(()=>{N(!1),B(null)},500)},[]),S=l.useCallback($=>{B($)},[]),P=l.useCallback(()=>{B(null)},[]),j=l.useCallback($=>{x($,"smooth")},[x]),O=l.useRef(!1);l.useImperativeHandle(a,()=>u.current),l.useEffect(()=>{n?.(m)},[m,n]),l.useEffect(()=>{if(!r)return;const $=u.current;if($&&!O.current){const X=setTimeout(()=>{$.scrollTop=$.scrollHeight,O.current=!0},100);return()=>clearTimeout(X)}},[r,u]);const Q=!m&&o;return e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsxs("div",{ref:u,className:y("h-full overflow-y-auto flex flex-col",t),...i,children:[e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s}),e.jsx("div",{ref:d,className:"shrink-0"})]}),e.jsx(ot,{mode:"wait",children:W&&e.jsxs(ke.nav,{variants:h,initial:"hidden",animate:"visible",exit:"exit",className:"absolute p-4 left-0 top-1/2 -translate-y-1/2 z-10",onMouseEnter:T,onMouseMove:V,onMouseLeave:k,"aria-label":"User message navigation",children:[e.jsx("div",{className:"flex flex-col",children:v.map(({index:$})=>{const X=$===g,R=U===$;return e.jsx("button",{type:"button",onClick:()=>j($),onMouseEnter:()=>S($),onMouseLeave:P,className:"py-2 px-1 group","aria-label":`Go to user message ${$+1}`,children:e.jsx("div",{className:y("w-4 h-[2px] rounded-full bg-primary transition-opacity duration-200",X?"opacity-80":"opacity-10",R&&"opacity-60",!R&&"group-hover:opacity-60")})},$)})}),e.jsx(ot,{children:b&&v.length>0&&U!==null&&(()=>{const R=40*Math.min(3,v.length)+10,A=40,J=40*U,G=A-J,Ie=0,ne=R-40*v.length-10,le=Math.max(ne,Math.min(Ie,G));return e.jsx(ke.div,{variants:f,initial:"hidden",animate:"visible",exit:"exit",className:y("absolute left-12 pointer-events-none","w-72 overflow-hidden","bg-card border border-border rounded-lg shadow-xl"),style:{top:`${D}px`,y:"-50%",height:`${R}px`,willChange:"transform"},children:e.jsx("div",{className:"p-1",style:{transform:`translateY(${le}px)`,transition:"transform 0.15s cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:v.map(({index:oe,preview:ve})=>{const ze=oe===U;return e.jsx("div",{className:y("w-full text-left px-3 py-2 rounded-md","text-sm text-muted-foreground","transition-colors duration-100","truncate",ze&&"bg-accent text-foreground"),style:{height:"40px"},children:ve},oe)})})},"hover-menu")})()})]},"toc")}),Q&&e.jsx("button",{type:"button",onClick:()=>p("smooth"),className:y("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:e.jsx(Ga,{className:"size-4"})})]})});Xn.displayName="ChatLayout.Messages";const Jn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("bg-linear-to-t from-background to-transparent px-4 pb-4",t),...n,children:e.jsx("div",{className:"mx-auto max-w-chat",children:s})}));Jn.displayName="ChatLayout.Footer";const Ci=l.forwardRef(({className:t,children:s,...n},o)=>{const{sidebarOpen:r}=Me();return r?e.jsx("div",{ref:o,className:y("border-r border-border bg-card w-64 overflow-y-auto",t),...n,children:s}):null});Ci.displayName="ChatLayout.Sidebar";const Zn=l.forwardRef(({breakpoint:t="md",onClose:s,className:n,children:o},r)=>{const{panelSize:i,togglePanel:a,setIsDraggingAside:c,setAsideWidth:u}=Me(),[d,m]=l.useState(bn),[p,g]=l.useState(d),[x,h]=l.useState(!1),f=l.useRef(0),b=l.useRef(d),N=i!=="hidden",[v,C]=l.useState(!1);l.useEffect(()=>{if(!N){C(!1);return}const E=requestAnimationFrame(()=>{C(!0)});return()=>cancelAnimationFrame(E)},[N]);const U=vn();yn(U&&N),l.useEffect(()=>{g(d)},[d]),l.useEffect(()=>{N&&u(x?p:d)},[N,x,p,d,u]);const B=l.useCallback(E=>{E.preventDefault(),h(!0),c(!0),f.current=E.clientX,b.current=d,E.target.setPointerCapture(E.pointerId)},[d,c]),D=l.useCallback(E=>{if(!x)return;const K=E.clientX-f.current,Y=Math.max(bs,Math.min(ys,b.current-K));g(Y)},[x]),I=l.useCallback(E=>{if(!x)return;const K=E.clientX-f.current,Y=Math.max(bs,Math.min(ys,b.current-K));m(Y),g(Y),h(!1),c(!1),E.target.releasePointerCapture(E.pointerId)},[x,c]),_=N&&U,M=N&&!U;return e.jsxs(ot,{initial:!1,children:[_&&e.jsx(ke.aside,{variants:Ur,initial:"initial",animate:"animate",exit:"exit",transition:Lr,className:y("fixed inset-0 z-50 bg-card","flex flex-col","block md:hidden",n),"data-aside":"aside","data-mobile":"true",children:e.jsxs(ke.div,{className:"flex flex-col h-full",variants:zr,initial:"initial",animate:"animate",transition:$r,children:[e.jsx("div",{className:"flex justify-end px-4 pt-3 shrink-0",children:e.jsx(Re,{onClick:()=>{s?.(),a()},"aria-label":"Close panel",children:e.jsx(It,{className:"size-4"})})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:o})]})},"aside-mobile"),M&&e.jsx("aside",{ref:r,style:{width:x?p:v?d:0,transition:x?"none":"width 0.25s cubic-bezier(0.25, 0.1, 0.25, 1)"},className:y("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",n),"data-aside":"aside",children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{onPointerDown:B,onPointerMove:D,onPointerUp:I,className:y("absolute left-0 inset-y-0 w-2 -ml-1 cursor-col-resize z-10","group flex items-center justify-center","hover:bg-primary/5 transition-colors delay-300",x&&"bg-primary/10")}),e.jsx("div",{className:y("h-full overflow-y-auto",x?"w-full":void 0),style:x?void 0:{width:`${d}px`},children:o})]})},"aside-desktop")]})});Zn.displayName="ChatLayout.Aside";class Si{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:n}=await s.json();return n.map(this.toFileSystemItem)}catch(s){return console.error("Error fetching sandbox root items:",s),[]}}async getItemChildren(s){try{const n=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=${encodeURIComponent(s)}`);if(!n.ok)return console.error("Failed to fetch sandbox directory:",await n.text()),[];const{files:o}=await n.json();return o.map(this.toFileSystemItem)}catch(n){return console.error("Error fetching sandbox item children:",n),[]}}async getItemDetails(s){try{const n=s.substring(0,s.lastIndexOf("/")),o=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=${encodeURIComponent(n||"/")}`);if(!o.ok)throw new Error(`Failed to fetch file details: ${await o.text()}`);const{files:r}=await o.json(),i=r.find(a=>a.path===s);if(!i)throw new Error(`File not found: ${s}`);return this.toFileSystemItem(i)}catch(n){throw console.error("Error fetching sandbox item details:",n),n}}toFileSystemItem=s=>{const n=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),...n!==void 0&&{extension:n}}}}function ea({item:t,level:s=0,onSelect:n,selectedId:o,isDropTarget:r=!1,onDownload:i}){const[a,c]=l.useState(!0),u=o===t.id,d=()=>{t.type==="folder"&&c(!a)},m=()=>{n?.(t),t.type==="folder"&&d()},p=x=>{x.key==="Enter"||x.key===" "?(x.preventDefault(),m()):x.key==="ArrowRight"&&t.type==="folder"&&!a?(x.preventDefault(),c(!0)):x.key==="ArrowLeft"&&t.type==="folder"&&a&&(x.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"?a:void 0,className:y("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",u&&"bg-accent",r&&["bg-accent","border border-dashed border-border-dark"]),onClick:m,onKeyDown:p,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.type==="folder"?a?e.jsx(Xa,{className:"size-4"}):e.jsx(Ja,{className:"size-4"}):e.jsx(Za,{className:"size-4"})}),e.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:t.name}),e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsx("button",{className:y("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:x=>{x.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(eo,{className:"size-4"})})}),e.jsx(qe,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:x=>x.stopPropagation(),children:i&&e.jsx(je,{onClick:x=>{x.stopPropagation(),i(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(fe,{className:y("size-4 transition-transform",!a&&"-rotate-90")})})]}),t.type==="folder"&&a&&t.children&&e.jsx("div",{className:"flex flex-col",children:t.children.map(x=>e.jsx(ea,{item:x,level:s+1,...n&&{onSelect:n},...o&&{selectedId:o},...i&&{onDownload:i}},x.id))})]})}const ki=new vr;function Ti({className:t,provider:s=ki,onItemSelect:n,onDownload:o}){const[r,i]=l.useState([]),[a,c]=l.useState(),[u,d]=l.useState(!0),[m,p]=l.useState(),[g,x]=l.useState(0);l.useEffect(()=>{const f=setInterval(()=>{x(b=>b+1)},6e4);return()=>clearInterval(f)},[]),l.useEffect(()=>{(async()=>{try{d(!0);const b=await s.getRootItems();i(b),p(void 0)}catch(b){p(b instanceof Error?b.message:"Failed to load items")}finally{d(!1)}})()},[s]);const h=f=>{c(f.id),n?.(f)};return u?e.jsx("div",{className:y("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):m?e.jsx("div",{className:y("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",m]})}):r.length===0?e.jsxs("div",{className:y("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",t),children:[e.jsx(We,{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:y("flex flex-col",t),children:r.map(f=>e.jsx(ea,{item:f,onSelect:h,...a&&{selectedId:a},...o&&{onDownload:o}},f.id))})}const Lt=l.forwardRef(({source:t,isSelected:s,className:n,...o},r)=>{const i=t.usedIn??[],a=l.useCallback(u=>{document.querySelectorAll("[data-citation-highlight='true']").forEach(d=>{d.removeAttribute("data-citation-highlight"),d.classList.remove("ring-2","ring-ring","ring-offset-2","ring-offset-background")}),u.setAttribute("data-citation-highlight","true"),u.classList.add("ring-2","ring-ring","ring-offset-2","ring-offset-background"),window.setTimeout(()=>{u.getAttribute("data-citation-highlight")==="true"&&(u.removeAttribute("data-citation-highlight"),u.classList.remove("ring-2","ring-ring","ring-offset-2","ring-offset-background"))},1400)},[]),c=l.useCallback((u,d)=>{const p=Array.from(document.querySelectorAll(`[data-citation-anchor="true"][data-citation-source-id="${CSS.escape(u)}"]`))[d];return p?(p.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),window.setTimeout(()=>a(p),150),!0):!1},[a]);return e.jsxs("button",{ref:r,type:"button",className:y("group flex w-full text-left gap-2 items-start p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",s&&"bg-accent",n),onClick:()=>{window.open(t.url,"_blank","noopener,noreferrer")},...o,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-0.5 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]})]}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Referenced"}),Array.from({length:Math.min(i.length,12)},(u,d)=>d).map(u=>e.jsx("span",{role:"button",tabIndex:0,className:y("px-1.5 py-0.5 rounded-md","text-[10px] leading-none font-medium","bg-muted text-muted-foreground","hover:bg-accent hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark","cursor-pointer select-none"),onClick:d=>{d.preventDefault(),d.stopPropagation(),c(t.id,u)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),d.stopPropagation(),c(t.id,u))},"aria-label":`Scroll to citation ${u+1}`,children:u+1},`${t.id}-use-${u}`)),i.length>12&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",i.length-12," more"]})]})]})]})});Lt.displayName="SourceListItem";const Zt=za,He=l.forwardRef(({className:t,...s},n)=>e.jsx(Os,{ref:n,className:y("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));He.displayName=Os.displayName;const Ue=l.forwardRef(({className:t,...s},n)=>e.jsx(Fs,{ref:n,className:y("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-paragraph-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...s}));Ue.displayName=Fs.displayName;const pe=l.forwardRef(({className:t,...s},n)=>e.jsx(Bs,{ref:n,className:y("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));pe.displayName=Bs.displayName;const ta=l.forwardRef(({todo:t,className:s,...n},o)=>{const r=t.status==="completed";return e.jsxs("div",{ref:o,className:y("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,...n,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(Rt,{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(Tt,{className:"size-4 text-foreground"})}),e.jsx("p",{className:y("flex-1 text-foreground",r&&"line-through text-muted-foreground",t.status==="in_progress"&&"font-medium"),children:t.text})]})});ta.displayName="TodoListItem";function Ii(){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(_t,{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 es=l.forwardRef(({client:t,todos:s,className:n,...o},r)=>{const i=s||[];return i.length===0?e.jsx("div",{ref:r,className:y("h-full",n),...o,children:e.jsx(Ii,{})}):e.jsx("div",{ref:r,className:y("space-y-2 overflow-y-auto",n),...o,children:i.map(a=>e.jsx(ta,{todo:a},a.id))})});es.displayName="TodoList";const ts=l.forwardRef(({todos:t=[],className:s,...n},o)=>e.jsx("div",{ref:o,className:y("h-full",s),...n,children:e.jsx(es,{todos:t,className:"h-full"})}));ts.displayName="TodoTabContent";const ss=l.forwardRef(({files:t=[],provider:s,sessionId:n,agentApiUrl:o,client:r,onFileSelect:i,className:a,...c},u)=>{const[d,m]=l.useState(0),p=l.useRef(void 0),g=l.useCallback(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{m(f=>f+1)},300)},[]);l.useEffect(()=>!n||!r?void 0:r.onFileSystemChange(n,b=>{console.log("Files changed:",b),g()}),[n,r,g]);const x=l.useMemo(()=>{if(s)return s;if(n&&o)return new Si({sessionId:n,apiUrl:o})},[s,n,o]),h=l.useCallback(async f=>{if(f.type==="folder"){console.warn("Cannot download folders");return}if(!n||!o){console.error("Cannot download: missing sessionId or agentApiUrl");return}try{const b=`${o}/sandbox/download?sessionId=${encodeURIComponent(n)}&path=${encodeURIComponent(f.path||f.name)}`,N=document.createElement("a");N.href=b,N.download=f.name,document.body.appendChild(N),N.click(),document.body.removeChild(N)}catch(b){console.error("Failed to download file:",b)}},[n,o]);return e.jsx("div",{ref:u,className:y("h-full",a),...c,children:e.jsx(Ti,{...x&&{provider:x},onItemSelect:f=>{f.type==="file"&&i&&i(f.path||f.name)},onDownload:h,className:"h-full"},d)})});ss.displayName="FilesTabContent";const ns=l.forwardRef(({sources:t=[],highlightedSourceId:s,className:n,...o},r)=>{const{usedSources:i,consultedSources:a}=l.useMemo(()=>{const m=[],p=[];for(const g of t)g.usedIn&&g.usedIn.length>0?m.push(g):p.push(g);return{usedSources:m,consultedSources:p}},[t]),c=i.length>0?"used":"consulted",[u,d]=l.useState(c);return l.useEffect(()=>{d(c)},[c]),t.length===0?e.jsxs("div",{ref:r,className:y("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",n),...o,children:[e.jsx(tn,{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.jsxs(Zt,{value:u,onValueChange:m=>d(m),className:y("flex flex-col gap-2",n),children:[e.jsx("div",{className:y("sticky top-0 z-10 -mx-4 -mt-4 mb-4 px-4 bg-card border-b border-border","before:content-[''] before:absolute before:left-0 before:right-0 before:-top-4 before:h-4 before:bg-card before:pointer-events-none"),children:e.jsxs(He,{className:"w-full h-auto p-0 bg-transparent rounded-none justify-start",children:[e.jsxs(Ue,{value:"used",disabled:i.length===0,className:y("flex-1 !text-xs !px-2 !py-2 rounded-none","bg-transparent shadow-none","border-b-2 border-transparent -mb-px","text-muted-foreground hover:text-foreground","data-[state=active]:bg-transparent data-[state=active]:shadow-none","data-[state=active]:text-foreground data-[state=active]:border-foreground"),children:["Referenced (",i.length,")"]}),e.jsxs(Ue,{value:"consulted",disabled:a.length===0,className:y("flex-1 !text-xs !px-2 !py-2 rounded-none","bg-transparent shadow-none","border-b-2 border-transparent -mb-px","text-muted-foreground hover:text-foreground","data-[state=active]:bg-transparent data-[state=active]:shadow-none","data-[state=active]:text-foreground data-[state=active]:border-foreground"),children:["Reviewed (",a.length,")"]})]})}),e.jsx(pe,{value:"used",className:"mt-0",children:i.length>0?e.jsx("div",{ref:r,className:"space-y-2",...o,children:i.map(m=>e.jsx(Lt,{source:m,isSelected:m.id===s},m.id))}):e.jsx("div",{ref:r,className:"text-xs text-muted-foreground",...o,children:"No referenced sources yet."})}),e.jsx(pe,{value:"consulted",className:"mt-0",children:a.length>0?e.jsx("div",{ref:r,className:"space-y-2",...o,children:a.map(m=>e.jsx(Lt,{source:m,isSelected:m.id===s},m.id))}):e.jsx("div",{ref:r,className:"text-xs text-muted-foreground",...o,children:"No reviewed sources."})})]})});ns.displayName="SourcesTabContent";const Ri=l.forwardRef(({data:t,className:s,...n},o)=>e.jsxs("div",{ref:o,className:y("space-y-4",s),...n,children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Database"}),e.jsxs("div",{className:"text-paragraph-sm text-muted-foreground",children:[e.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),e.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[e.jsx("p",{children:"Your large data table would go here"}),t&&typeof t=="object"?e.jsx("pre",{className:"mt-2 text-caption overflow-auto",children:JSON.stringify(t,null,2)}):null]})]})]}));Ri.displayName="DatabaseTabContent";const _i=({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(n=>n.prettyName||n.name).join(", ")]})]})},sa=l.forwardRef(({tools:t=[],mcps:s=[],subagents:n=[],className:o,...r},i)=>e.jsxs("div",{ref:i,className:y("space-y-6",o),...r,children:[e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Tools"}),t.length>0?e.jsx("div",{className:"space-y-2",children:t.map(a=>e.jsx(_i,{tool:a},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No tools available"})]}),e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"MCP Servers"}),s.length>0?e.jsx("div",{className:"space-y-2",children:s.map(a=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:a.name}),e.jsxs("div",{className:"text-caption text-muted-foreground mt-1",children:["Transport: ",a.transport]})]},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No MCP servers connected"})]}),e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Subagents"}),n.length>0?e.jsx("div",{className:"space-y-2",children:n.map(a=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:a.name}),e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-2",children:a.description})]},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No subagents available"})]})]}));sa.displayName="SettingsTabContent";const Mi=l.forwardRef(({client:t,todos:s,variant:n="animated",showIcons:o=!1,visibleTabs:r=["todo","files","database"],className:i,...a},c)=>{const u=s||[],[d,m]=l.useState(r[0]||"todo"),p=l.useRef(null),g=l.useRef(null);l.useEffect(()=>{const b=setTimeout(()=>{const N=p.current;if(d&&N){const v=g.current;if(v){const C=N.getBoundingClientRect(),U=v.getBoundingClientRect(),B=U.left-C.left,D=U.width,I=B/C.width*100,_=100-(B+D)/C.width*100;N.style.clipPath=`inset(0 ${_.toFixed(2)}% 0 ${I.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(b)},[d]);const h=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:_t},{id:"files",label:"Files",icon:We},{id:"database",label:"Database",icon:sn},{id:"sources",label:"Sources",icon:nn}].filter(f=>r.includes(f.id));return e.jsx("div",{ref:c,className:y("select-none",i),...a,children:e.jsxs(Zt,{value:d,onValueChange:m,className:"w-full",children:[n==="pills"?e.jsx(He,{className:y("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:h.map(f=>{const b=f.icon;return e.jsxs(Ue,{value:f.id,className:y("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&b&&e.jsx(b,{className:"size-4"}),f.label]},f.id)})}):e.jsxs("div",{className:"relative mb-4 border-border",children:[e.jsx(He,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:h.map(f=>e.jsx(Ue,{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(He,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:h.map(f=>e.jsx(Ue,{value:f.id,ref:d===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(pe,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?e.jsx(ts,{todos:u}):e.jsx(es,{todos:u})}),e.jsx(pe,{value:"files",className:n==="pills"?"mt-0":"",children:e.jsx(ss,{})}),e.jsx(pe,{value:"database",className:n==="pills"?"mt-0":"",children:e.jsx("div",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})}),e.jsx(pe,{value:"sources",className:n==="pills"?"mt-0":"",children:e.jsx(ns,{})})]})})});Mi.displayName="ChatSecondaryPanel";const Ei=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex h-full flex-col",t),...n,children:s}));Ei.displayName="ChatSidebar.Root";const Ai=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("border-b border-border px-4 py-3",t),...n,children:s}));Ai.displayName="ChatSidebar.Header";const Pi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex-1 overflow-y-auto p-4",t),...n,children:s}));Pi.displayName="ChatSidebar.Content";const Di=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("border-t border-border px-4 py-3",t),...n,children:s}));Di.displayName="ChatSidebar.Footer";const Ui=l.forwardRef(({children:t,className:s,...n},o)=>{const[r,i]=l.useState(t),[a,c]=l.useState(!1),u=l.useRef(t),d=l.useRef(!0);return l.useEffect(()=>{if(d.current){d.current=!1,u.current=t;return}if(u.current===t)return;c(!0);const m=setTimeout(()=>{i(t),u.current=t,requestAnimationFrame(()=>{c(!1)})},150);return()=>{clearTimeout(m)}},[t]),e.jsx("span",{ref:o,className:y("text-sm text-foreground opacity-60 transition-opacity duration-300",a?"opacity-0":"opacity-60",s),...n,children:r})});Ui.displayName="ChatStatus";let Ns=!1,st=null;const rt=[];let nt=null;const Qe={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)},Ee=ue("gui-console");function Ge(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 zi(t){if(rt.push(t),t.level==="error"||t.level==="fatal"){Cs();return}nt||(nt=setTimeout(()=>{nt=null,Cs()},500))}async function Cs(){if(rt.length===0||!st)return;const t=rt.splice(0);try{await fetch(`${st}/logs/browser`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({logs:t})})}catch{}}function $i(t){Ns||(Ns=!0,st=t,console.log=(...s)=>{Qe.log(...s),Ee.info(Ge(s))},console.info=(...s)=>{Qe.info(...s),Ee.info(Ge(s))},console.warn=(...s)=>{Qe.warn(...s),Ee.warn(Ge(s))},console.error=(...s)=>{Qe.error(...s),Ee.error(Ge(s))},console.debug=(...s)=>{Qe.debug(...s),Ee.debug(Ge(s))},window.onerror=(s,n,o,r,i)=>(Ee.error(String(s),{source:n,line:o,col:r,stack:i?.stack}),!1),window.onunhandledrejection=s=>{const n=s.reason instanceof Error?`${s.reason.name}: ${s.reason.message}`:String(s.reason);Ee.error(`Unhandled rejection: ${n}`,{stack:s.reason?.stack})},No(s=>{s.service==="gui-console"&&zi(s)}),window.addEventListener("beforeunload",()=>{nt&&clearTimeout(nt),rt.length>0&&st&&navigator.sendBeacon(`${st}/logs/browser`,JSON.stringify({logs:rt}))}))}const Li=500;function Oi(t){const s=H(r=>r.isStreaming),n=l.useRef(null),o=l.useRef(0);l.useEffect(()=>{t&&!s&&(document.title=t)},[t,s]),l.useEffect(()=>{if(!t)return;const r=()=>{const i=".".repeat(o.current);document.title=`${t}${i}`,o.current=(o.current+1)%4};if(s)return o.current=0,r(),n.current=setInterval(r,Li),()=>{n.current&&(clearInterval(n.current),n.current=null),document.title=t}},[s,t])}const Se=ue("gui");function Fi({children:t}){const{setPanelSize:s,setActiveTab:n,panelSize:o,activeTab:r}=Me(),i=()=>{o!=="hidden"&&r==="files"?s("hidden"):(s("small"),n("files"))},a=()=>{o!=="hidden"&&r==="settings"?s("hidden"):(s("small"),n("settings"))};return e.jsx(e.Fragment,{children:t({openFiles:i,openSettings:a})})}function Bi({client:t,startSession:s,placeholder:n,commandMenuItems:o,onCancel:r,promptParameters:i}){const a=H(m=>m.input.attachedFiles),c=H(m=>m.addFileAttachment),u=H(m=>m.removeFileAttachment),d=m=>{for(const p of m)c(p)};return e.jsxs(Ln,{client:t,startSession:s,onCancel:r,children:[e.jsx(Kn,{commands:o}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border-b border-border",children:a.map((m,p)=>e.jsxs("div",{className:"relative group rounded-md overflow-hidden border border-border",children:[e.jsx("img",{src:`data:${m.mimeType};base64,${m.data}`,alt:m.name,className:"h-20 w-20 object-cover"}),e.jsx("button",{type:"button",onClick:()=>u(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(It,{className:"size-3"})})]},`attached-${m.name}-${m.data.slice(0,20)}`))}),e.jsx(On,{placeholder:n,autoFocus:!0,onFilesDropped:d}),e.jsxs(Hn,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Wn,{}),e.jsx(Vn,{onFilesSelected:d}),i&&i.length>0&&e.jsx(yi,{parameters:i})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(qn,{}),e.jsx(Bn,{}),e.jsx(Fn,{children:e.jsx(so,{className:"size-4"})})]})]})]})}function Hi({todos:t,sources:s,tools:n,mcps:o,subagents:r,sessionId:i,agentApiUrl:a,client:c}){const{activeTab:u,setActiveTab:d}=Me();return e.jsxs(Zt,{value:u,onValueChange:m=>d(m),className:"flex flex-col h-full",children:[e.jsx("div",{className:y("border-b border-border bg-card","px-4 py-2 h-16","flex items-center","sticky top-0 z-10 shrink-0"),children:e.jsx(fa,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(pe,{value:"todo",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ts,{todos:t})}),e.jsx(pe,{value:"files",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ss,{sessionId:i,agentApiUrl:a,client:c})}),e.jsx(pe,{value:"sources",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ns,{sources:s})}),e.jsx(pe,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(sa,{tools:n??[],mcps:o??[],subagents:r??[]})})]})}function Wi({agentName:t,showHeader:s,sessionId:n,debuggerUrl:o}){const{togglePanel:r,panelOpen:i}=Me(),a=o?n?`${o}/sessions/${n}`:o:null;return e.jsx(Un,{className:y("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(Wl,{}),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(oa,{}),o&&e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx(Re,{"aria-label":"View session in debugger",disabled:!a,asChild:!!a,children:a?e.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:e.jsx(ls,{className:"size-4 text-muted-foreground"})}):e.jsx(ls,{className:"size-4 text-muted-foreground"})})}),e.jsx(be,{children:e.jsx("p",{children:n?"View session in debugger":"Open debugger"})})]})}),e.jsx(Re,{"aria-label":"Toggle panel",onClick:r,"data-state":i?"open":"closed",children:e.jsx(to,{className:"size-4 text-muted-foreground"})})]})]})})}function Vi({client:t,initialSessionId:s,error:n,debuggerUrl:o}){const{connectionStatus:r,connect:i,sessionId:a,startSession:c}=ar(t,s),{messages:u,sendMessage:d,editAndResend:m,cancel:p}=gn(t,c);ir(t);const g=H(R=>R.error),[x,h]=l.useState(void 0),[f,b]=l.useState(void 0),[N,v]=l.useState(void 0),[C,U]=l.useState([]),[B,D]=l.useState([]),[I,_]=l.useState([]),[M,E]=l.useState([]),[K,Y]=l.useState("Type a message or / for commands..."),[z,W]=l.useState(!1),[V,T]=l.useState(null),k=H(sr);H(R=>R.latestContextSize);const{resolvedTheme:S,setTheme:P}=Xt(),j=l.useMemo(()=>{const R=new Map,A=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g,J=G=>G.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"");for(let G=0;G<u.length;G++){const Ie=u[G];if(!Ie?.content)continue;const ne=J(Ie.content);A.lastIndex=0;let le,oe=0;for(;(le=A.exec(ne))!==null;){const ve=le[1]??le[2];if(!ve)continue;const ze=R.get(ve)??[];ze.push({messageId:Ie.id,messageIndex:G,citationIndex:oe}),R.set(ve,ze),oe++}}return R},[u]),O=l.useMemo(()=>{const R=new Map;for(const A of u)if(A.sources)for(const J of A.sources)R.has(J.id)||R.set(J.id,{id:J.id,title:J.title,url:J.url,snippet:J.snippet||"",sourceName:J.sourceName||"",favicon:J.favicon||""});for(const[A,J]of j.entries()){const G=R.get(A);G&&(G.usedIn=J)}return Array.from(R.values())},[u,j]);Oi(x),l.useEffect(()=>{if(t){const R=t.getBaseUrl();R&&$i(R)}},[t]),l.useEffect(()=>{Se.debug("Connection status changed",{status:r}),r==="error"&&g&&Se.error("Connection error occurred",{error:g})},[r,g]),l.useEffect(()=>{if(t&&r==="connected"){const R=t.getCurrentSession();R?.metadata?.agentName&&h(R.metadata.agentName);const A=t.getAgentInfo();A.displayName?h(A.displayName):A.name&&h(A.name),b(A.description||"Start a conversation below to begin working with this agent."),A.suggestedPrompts&&A.suggestedPrompts.length>0?v(A.suggestedPrompts):v([]),A.tools&&A.tools.length>0&&(U(A.tools),Se.info("Agent tools loaded",{tools:A.tools})),A.mcps&&A.mcps.length>0&&(D(A.mcps),Se.info("Agent MCPs loaded",{mcps:A.mcps})),A.subagents&&A.subagents.length>0&&(_(A.subagents),Se.info("Agent subagents loaded",{subagents:A.subagents})),A.promptParameters&&A.promptParameters.length>0&&(E(A.promptParameters),Se.info("Agent prompt parameters loaded",{promptParameters:A.promptParameters})),A.uiConfig?.hideTopBar&&W(!0)}},[t,r]);const Q=R=>{Y(R)},$=()=>{Y("Type a message or / for commands...")};if(n)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:e.jsxs("div",{className:"text-center p-8 max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-destructive mb-4",children:"Initialization Error"}),e.jsx("p",{className:"text-foreground mb-4",children:n}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})});const X=[{id:"dark-mode",label:S==="dark"?"Light Mode":"Dark Mode",description:`Switch to ${S==="dark"?"light":"dark"} theme`,icon:S==="dark"?e.jsx(Zs,{className:"h-4 w-4"}):e.jsx(en,{className:"h-4 w-4"}),category:"action",onSelect:()=>{P(S==="dark"?"light":"dark"),Se.info("User toggled theme",{newTheme:S==="dark"?"light":"dark"})}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx(Ht,{className:"h-4 w-4"}),category:"action",onSelect:()=>{Se.info("User opened settings")}}];return e.jsxs(Nn,{defaultOpen:!1,children:[e.jsx(di,{client:t,currentSessionId:a}),e.jsx(Sn,{children:e.jsxs(Yn,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsxs(Qn,{children:[!z&&e.jsx(Wi,{agentName:x,showHeader:u.length>0,sessionId:a,...o&&{debuggerUrl:o}}),r==="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:i,className:"rounded-lg bg-destructive px-4 py-2 text-paragraph-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive-hover",children:"Retry"})]})}),e.jsxs(Gn,{children:[e.jsx(Xn,{children:u.length===0?x!==void 0?e.jsx(Fi,{children:({openFiles:R,openSettings:A})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Dn,{title:x,description:f??"",suggestedPrompts:N??[],onPromptClick:J=>{const G=H.getState().input.selectedPromptParameters;d(J,void 0,G&&Object.keys(G).length>0?G:void 0),Y("Type a message or / for commands..."),Se.info("Prompt clicked",{prompt:J})},onPromptHover:Q,onPromptLeave:$,onOpenFiles:R,onOpenSettings:A,toolsAndMcpsCount:C.length+B.length+I.length})})}):null:e.jsx("div",{className:"flex flex-col px-4 py-4",children:u.map((R,A)=>{const J=u.some(ne=>ne.isStreaming),G=R.role==="user"?u.slice(0,A+1).filter(ne=>ne.role==="user").length-1:-1,Ie=V!==null&&A>V;return e.jsx(ia,{message:R,className:y("group",Ie&&"opacity-50"),isLastMessage:A===u.length-1,children:e.jsx("div",{className:"flex flex-col w-full min-w-0",children:R.role==="user"?e.jsx(el,{message:R,messageIndex:G,isStreaming:J,onEditAndResend:m,sticky:!0,onEditingChange:ne=>{T(ne?A:null)}}):e.jsxs(e.Fragment,{children:[e.jsx(pa,{message:R,thinkingDisplayStyle:"collapsible"}),e.jsx(il,{message:R,isStreaming:R.isStreaming,onSendMessage:d,isLastAssistantMessage:A===u.findLastIndex(ne=>ne.role==="assistant"),onRedo:()=>{let ne=null,le=-1;for(let oe=A-1;oe>=0;oe--)if(u[oe]?.role==="user"){ne=u[oe],le=u.slice(0,oe+1).filter(ve=>ve.role==="user").length-1;break}if(ne?.content&&le>=0){const oe=ne.images?.map((ve,ze)=>({name:`image-${ze}`,path:"",size:0,mimeType:ve.mimeType,data:ve.data}));m(le,ne.content,oe)}}})]})})},R.id)})})}),e.jsx(Jn,{children:e.jsx(Bi,{client:t,startSession:c,placeholder:K,commandMenuItems:X,onCancel:p,promptParameters:M})})]})]}),e.jsx(Zn,{breakpoint:"md",children:e.jsx(Hi,{todos:k,sources:O,tools:C,mcps:B,subagents:I,sessionId:a,agentApiUrl:t?.getBaseUrl(),client:t})})]})})]})}const Ot=l.forwardRef(({sourceId:t,sources:s,className:n},o)=>{const r=s.find(u=>u.id===t);let i=null;try{i=Me()}catch{}const a=l.useCallback(u=>{u.preventDefault(),u.stopPropagation(),i&&(i.setPanelSize("small"),i.setActiveTab("sources")),r?.url&&window.open(r.url,"_blank","noopener,noreferrer")},[i,r?.url]);if(!r)return e.jsxs("span",{ref:o,className:y("inline-flex items-center px-1.5 py-0.5 text-xs font-medium","bg-muted text-muted-foreground rounded-md","cursor-default",n),children:["[",t,"]"]});const c=r.sourceName||qi(r.url);return e.jsx(ge,{delayDuration:200,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsxs("span",{ref:o,role:"button",tabIndex:0,onClick:a,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&a(u)},className:y("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",n),children:[r.favicon&&e.jsx("img",{src:r.favicon,alt:"",className:"size-3 rounded-sm",onError:u=>{u.target.style.display="none"}}),e.jsx("span",{children:c})]})}),e.jsx(be,{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:[r.favicon&&e.jsx("img",{src:r.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:r.title}),r.snippet&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3 mb-2",children:r.snippet}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(no,{className:"size-3"}),e.jsx("span",{children:"Click to open"})]})]})})]})})});Ot.displayName="CitationChip";function qi(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}const Ki=2e5;function as(t){const s=Math.max(t.totalEstimated,t.llmReportedInputTokens??0),n=t.modelContextWindow??Ki,o=s/n*100,r=`${o.toFixed(1)}%`,i=Math.min(100,Math.max(0,o)),c=(f=>f<50?"text-foreground":f<75?"text-yellow-500":"text-red-500")(o),u=f=>s===0?"0.0%":`${(f/s*100).toFixed(1)}%`,d=16,m=2,p=(d-m)/2,g=d/2,x=2*Math.PI*p,h=x-i/100*x;return{actualTokens:s,formattedPercentage:r,percentage:o,clampedPercentage:i,colorClass:c,calculatePercentage:u,size:d,strokeWidth:m,radius:p,center:g,circumference:x,offset:h}}function na({contextSize:t}){const{actualTokens:s,formattedPercentage:n,colorClass:o,calculatePercentage:r}=as(t);return e.jsx(be,{side:"top",align:"center",className:"p-3",children:e.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"System Prompt:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.systemPromptTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.systemPromptTokens),")"]})]})]}),t.toolOverheadTokens!==void 0&&t.toolOverheadTokens>0&&e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tools Definition:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.toolOverheadTokens),")"]})]})]}),t.mcpOverheadTokens!==void 0&&t.mcpOverheadTokens>0&&e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"MCPs Definition:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.mcpOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.mcpOverheadTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"User Messages:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.userMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.userMessagesTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Assistant Messages:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.assistantMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.assistantMessagesTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tool Inputs:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolInputTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.toolInputTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tool Results:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolResultsTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.toolResultsTokens),")"]})]})]})]}),e.jsx("div",{className:"border-t border-border pt-2",children:e.jsxs("div",{className:y("flex justify-end gap-2 font-semibold",o),children:[e.jsx("span",{children:s.toLocaleString()}),e.jsxs("span",{children:["(",n,")"]})]})})]})})}function aa({contextSize:t,className:s,size:n=12}){if(t==null)return null;const{colorClass:o,clampedPercentage:r}=as(t),i=2,a=(n-i)/2,c=n/2,u=2*Math.PI*a,d=u-r/100*u;return e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{className:y("inline-flex items-center justify-center rounded-full cursor-default",o,s),role:"img","aria-label":"Context usage indicator",children:e.jsxs("svg",{width:n,height:n,viewBox:`0 0 ${n} ${n}`,className:"transform -rotate-90",children:[e.jsx("title",{children:"Context usage indicator"}),e.jsx("circle",{cx:c,cy:c,r:a,stroke:"currentColor",strokeWidth:i,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:c,cy:c,r:a,stroke:"currentColor",strokeWidth:i,fill:"transparent",strokeDasharray:u,strokeDashoffset:d,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(na,{contextSize:t})]})})}const oa=l.forwardRef(({className:t,contextSize:s,...n},o)=>{const r=H(x=>x.latestContextSize),i=s??r;if(i==null)return null;const{colorClass:a,size:c,center:u,radius:d,strokeWidth:m,circumference:p,offset:g}=as(i);return e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx(re,{ref:o,type:"button",variant:"ghost",size:"icon",className:y("rounded-full cursor-default",a,t),...n,children:e.jsxs("svg",{width:c,height:c,viewBox:`0 0 ${c} ${c}`,className:"transform -rotate-90",children:[e.jsx("title",{children:"Context usage indicator"}),e.jsx("circle",{cx:u,cy:u,r:d,stroke:"currentColor",strokeWidth:m,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:u,cy:u,r:d,stroke:"currentColor",strokeWidth:m,fill:"transparent",strokeDasharray:p,strokeDashoffset:g,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(na,{contextSize:i})]})})});oa.displayName="ContextUsageButton";const Yi=l.forwardRef(({autoScroll:t=!0,isStreaming:s=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:r=!0,scrollButton:i,className:a,children:c,...u},d)=>{const m=l.useRef(null),[p,g]=l.useState(!0),[x,h]=l.useState(!1),f=l.useRef(0);l.useImperativeHandle(d,()=>{if(!m.current)throw new Error("Container ref not initialized");return m.current});const b=l.useCallback(()=>{const v=m.current;if(!v)return;const{scrollTop:C,scrollHeight:U,clientHeight:B}=v,I=U-C-B<o;g(I),h(!I&&r),f.current=C},[o,r]),N=l.useCallback((v=n)=>{const C=m.current;C&&C.scrollTo({top:C.scrollHeight,behavior:v})},[n]);return l.useEffect(()=>{!t||!m.current||(s&&p?N("auto"):!s&&p&&N())},[t,s,p,N]),l.useEffect(()=>{const v=m.current;if(!v)return;const C=()=>{b()};return v.addEventListener("scroll",C,{passive:!0}),b(),()=>{v.removeEventListener("scroll",C)}},[b]),l.useEffect(()=>{const v=m.current;if(!v)return;const C=new ResizeObserver(()=>{p&&t&&N("auto")});return C.observe(v),()=>{C.disconnect()}},[p,t,N]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx("div",{ref:m,className:y("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",a),...u,children:e.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:c})}),x&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||e.jsxs("button",{type:"button",onClick:()=>N(),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"]})})]})});Yi.displayName="Conversation";const Qi=Hs,ra=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{ref:n,className:y("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s}));ra.displayName=Nt.displayName;const Gi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Qi,{children:[e.jsx(ra,{}),e.jsxs(Ct,{ref:o,className:y("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[s,e.jsxs(Ws,{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(It,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Gi.displayName=Ct.displayName;const Xi=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:y("text-subheading font-semibold leading-none tracking-tight",t),...s}));Xi.displayName=St.displayName;const Ji=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:y("text-paragraph-sm text-muted-foreground",t),...s}));Ji.displayName=kt.displayName;function Zi({message:t,messageIndex:s,isStreaming:n,onEditAndResend:o,sticky:r=!1,onEditingChange:i}){const[a,c]=l.useState(!1),[u,d]=l.useState(!1),m=l.useRef(null),p=l.useRef(null);l.useEffect(()=>{i?.(a)},[a,i]);const g=l.useCallback(()=>{if(!r||!m.current)return;let v=m.current.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(v){m.current.getBoundingClientRect(),v.getBoundingClientRect();const C=m.current.offsetTop;v.scrollTo({top:C-16,behavior:"smooth"})}},[r]),x=l.useCallback(async()=>{if(!t.content){me.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),d(!0),me.success("Copied to clipboard!"),setTimeout(()=>{d(!1)},2e3)}catch{me.error("Failed to copy to clipboard")}},[t.content]),h=l.useCallback(()=>{c(!0)},[]);l.useEffect(()=>{if(a&&p.current){p.current.focus();const v=document.createRange(),C=window.getSelection();v.selectNodeContents(p.current),v.collapse(!1),C?.removeAllRanges(),C?.addRange(v)}},[a]);const f=l.useCallback(()=>{c(!1),p.current&&(p.current.textContent=t.content||"")},[t.content]),b=l.useCallback(()=>{const v=p.current?.textContent||"";if(!v.trim())return;const C=t.images?.map((U,B)=>({name:`image-${B}`,path:"",size:0,mimeType:U.mimeType,data:U.data}));o(s,v.trim(),C),c(!1)},[s,t.images,o]),N=l.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),b()),v.key==="Escape"&&(v.preventDefault(),f())},[b,f]);return e.jsxs("div",{ref:m,className:"w-full group/user-message",children:[e.jsx("div",{className:y("w-full rounded-2xl bg-secondary px-4 py-4 transition-colors",r&&"sticky top-0 z-10 bg-secondary cursor-pointer",a&&"ring-2 ring-primary/20 focus-within:ring-primary/40 transition-all bg-transparent"),onClick:r&&!a?g:void 0,onKeyDown:r&&!a?v=>{(v.key==="Enter"||v.key===" ")&&g()}:void 0,role:r&&!a?"button":void 0,tabIndex:r&&!a?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,C)=>e.jsx("img",{src:`data:${v.mimeType};base64,${v.data}`,alt:`Attachment ${C+1}`,className:y("max-w-[200px] max-h-[200px] rounded-lg object-cover",a&&"opacity-50")},`image-${v.mimeType}-${v.data.slice(0,20)}`))}),t.content&&e.jsx("div",{ref:p,role:"textbox",tabIndex:a?0:-1,contentEditable:a,onKeyDown:a?N:void 0,suppressContentEditableWarning:!0,className:y("whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-foreground leading-relaxed outline-none",a&&"cursor-text",!a&&"cursor-default"),children:t.content})]})}),!n&&t.content&&e.jsx(Gt,{className:y("mt-2 transition-opacity justify-end",a?"opacity-100":"opacity-0 group-hover/user-message:opacity-100"),children:a?e.jsxs(e.Fragment,{children:[e.jsx(re,{variant:"ghost",size:"sm",onClick:f,className:"h-7 px-2 text-xs text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsx(re,{size:"sm",onClick:b,className:"h-7 px-3 text-xs",children:"Send"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{onClick:x,tooltip:u?"Copied!":"Copy",children:u?e.jsx(lt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),e.jsx(Ve,{onClick:h,tooltip:"Edit",children:e.jsx(ao,{className:"size-4"})})]})})]})}const el=l.memo(Zi,(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 tl(t,s,n,o,r){const i=n==="triggered",a=o==="no_action_needed";return t==="context_size"?i?{icon:ce,title:"Compacting Context..."}:{icon:ce,title:a?"Context Check":"Context Compacted"}:t==="tool_response"?s==="mid_turn_compaction"||r===!0?i?{icon:ce,title:"Compacting Context..."}:{icon:ce,title:a?"Context Check":"Context Compacted"}:i?{icon:ce,title:"Compacting Response..."}:{icon:ce,title:a?"Response Check":"Tool Response Compacted"}:{icon:ce,title:i?"Running Hook...":"Hook Executed"}}function Ae(t){return t.toLocaleString()}function sl(t){if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return s>0?`${s}h ${n}m ${o}s`:`${n}m ${o}s`}function Pt({notification:t}){const[s,n]=l.useState(!1),[o,r]=l.useState(0),{icon:i,title:a}=tl(t.hookType,t.callback,t.status,t.metadata?.action,t.metadata?.midTurn),c=t.status==="triggered",u=t.status==="completed",d=t.status==="error";l.useEffect(()=>{if(!c||!t.triggeredAt)return;const x=()=>{const f=(Date.now()-t.triggeredAt)/1e3;r(f)};x();const h=setInterval(x,100);return()=>clearInterval(h)},[c,t.triggeredAt]);const m=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(u&&t.metadata?.tokensSaved!==void 0){const{tokensSaved:x,originalTokens:h,messagesRemoved:f}=t.metadata;if(m)p=`${f!==void 0?`${Ae(f)} messages summarized, `:""}${Ae(x??0)} tokens saved`;else if(h!==void 0&&h>0)p=`${((x??0)/h*100).toFixed(0)}% reduced`;else if(t.currentPercentage!==void 0&&t.currentPercentage>0){const N=t.currentPercentage/100*2e5;p=`${((x??0)/N*100).toFixed(1)}% context freed`}else p=`${Ae(x)} tokens saved`}else d&&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:()=>n(!s),"aria-expanded":s,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("div",{className:d?"text-destructive":"text-muted-foreground",children:e.jsx(i,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:a}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Vt,{className:"h-3 w-3 text-muted-foreground animate-spin"}),e.jsxs("span",{className:"text-muted-foreground/70 tabular-nums",children:[o.toFixed(1),"s"]})]}),u&&e.jsx(Rt,{className:"h-3 w-3 text-green-500"}),d&&e.jsx(wt,{className:"h-3 w-3 text-destructive"}),!c&&e.jsx(fe,{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 ${d?"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:Ae(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:Ae(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:[Ae(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:[Ae(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(oo,{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:"," ",sl((t.completedAt-t.triggeredAt)/1e3)]})]})]})})]})]})}const nl=l.forwardRef(({className:t,...s},n)=>e.jsx(Vs,{ref:n,className:y("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));nl.displayName=Vs.displayName;function Dt({content:t,className:s}){if(!t)return null;const n={table:({node:o,...r})=>e.jsx("div",{className:"overflow-x-auto my-4",children:e.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...r})}),thead:({node:o,...r})=>e.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:o,...r})=>e.jsx("tbody",{...r}),tr:({node:o,...r})=>e.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:o,...r})=>e.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...r}),td:({node:o,...r})=>e.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:o,checked:r,...i})=>i.type==="checkbox"?e.jsx("input",{type:"checkbox",checked:r||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...i}):e.jsx("input",{...i}),code:({node:o,...r})=>r.className?.includes("language-")?e.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-code text-foreground",...r}):e.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code text-foreground",...r}),pre:({node:o,...r})=>e.jsx("pre",{className:"my-4",...r}),h1:({node:o,...r})=>e.jsx("h1",{className:"text-heading-3 mt-6 mb-4 text-foreground",...r}),h2:({node:o,...r})=>e.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground",...r}),h3:({node:o,...r})=>e.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...r}),ul:({node:o,...r})=>{const i=o?.children?.some(a=>typeof a=="object"&&a!==null&&"type"in a&&a.type==="element"&&"tagName"in a&&a.tagName==="li"&&"children"in a&&Array.isArray(a.children)&&a.children.some(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:y("my-2 space-y-1 text-foreground",i?"list-none space-y-2":"list-disc list-inside"),...r})},ol:({node:o,...r})=>e.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...r}),li:({node:o,...r})=>{const i=o?.children?.some(a=>typeof a=="object"&&a!==null&&"type"in a&&a.type==="element"&&"tagName"in a&&a.tagName==="input"&&"properties"in a&&typeof a.properties=="object"&&a.properties!==null&&"type"in a.properties&&a.properties.type==="checkbox");return e.jsx("li",{className:y("flex items-start",i?"gap-2":"ml-2"),...r})},a:({node:o,...r})=>e.jsx("a",{className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:o,...r})=>e.jsx("p",{className:"my-2 text-foreground leading-relaxed",...r}),blockquote:({node:o,...r})=>e.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2",...r})};return e.jsx("div",{className:y("markdown-content prose prose-sm max-w-none dark:prose-invert",s),children:e.jsx(ya,{remarkPlugins:[on],components:n,children:t})})}const al=Te("flex min-w-0 animate-fadeIn",{variants:{role:{user:"max-w-[80%] self-end ml-auto",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"}}),ia=l.forwardRef(({message:t,role:s,layout:n,className:o,children:r,messageId:i,autoScroll:a,isLastMessage:c=!1,...u},d)=>{const m=t?t.role:s||"assistant",p=t?t.id:i,g=l.useRef(null),[x,h]=l.useState(void 0);return l.useImperativeHandle(d,()=>g.current),l.useEffect(()=>{if(!c||m!=="assistant"){h(void 0);return}const f=()=>{const N=g.current;if(!N)return;let v=N.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(!v)return;const C=N.previousElementSibling;if(!C||C.getAttribute("aria-label")!=="user message"){h(void 0);return}const U=v.clientHeight,B=C.offsetHeight,I=Math.max(0,U-B-32);h(I)};f();const b=new ResizeObserver(f);if(g.current){b.observe(g.current);let N=g.current.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;N&&b.observe(N)}return()=>b.disconnect()},[c,m]),l.useEffect(()=>{if((a!==void 0?a:m==="user")&&g.current){const b=setTimeout(()=>{g.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(b)}},[m,a]),e.jsx("article",{ref:g,id:p?`message-${p}`:void 0,"aria-label":`${m} message`,"data-message-id":p,className:y(al({role:m,layout:n}),o),style:{minHeight:x!==void 0?`${x}px`:void 0},...u,children:r})});ia.displayName="Message";const ol=[{id:"pdf",label:"PDF",icon:We},{id:"excel",label:"Excel",icon:cs},{id:"csv",label:"CSV",icon:cs},{id:"text",label:"Text",icon:io},{id:"markdown",label:"Markdown",icon:We}];function rl({message:t,isStreaming:s,onRedo:n,onSendMessage:o,isLastAssistantMessage:r=!1}){const[i,a]=l.useState(!1);if(s||t.role!=="assistant"||!t.content)return null;const c=r?"":"opacity-0 group-hover:opacity-100 transition-opacity",u=async()=>{if(!t.content){me.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),a(!0),me.success("Copied to clipboard!"),setTimeout(()=>{a(!1)},2e3)}catch{me.error("Failed to copy to clipboard")}},d=()=>{n?n():me.info("Regenerate not available")},m=p=>{o?o(`produce an artifact as ${p} for this session`):me.info("Export not available")};return e.jsxs(Gt,{className:y(c),children:[e.jsx(Ve,{onClick:u,tooltip:i?"Copied!":"Copy",children:i?e.jsx(lt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),e.jsx(Ve,{onClick:d,tooltip:"Redo",children:e.jsx(ro,{className:"size-4"})}),e.jsxs(ut,{children:[e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx(mt,{asChild:!0,children:e.jsxs(re,{className:y("relative size-7 p-1.5 text-muted-foreground hover:text-foreground"),size:"sm",type:"button",variant:"ghost",children:[e.jsx(an,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Export"})]})})}),e.jsx(be,{children:e.jsx("p",{children:"Export"})})]})}),e.jsx(qe,{align:"start",children:ol.map(p=>e.jsxs(je,{onClick:()=>m(p.label),children:[e.jsx(p.icon,{className:"size-4 mr-2"}),p.label]},p.id))})]})]})}const il=l.memo(rl,(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)),ll={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 cl(t,s){if(!s||!t.rawInput)return null;const n=t.rawInput[s];return typeof n=="string"?n:null}function dl(t,s){let n=t;for(const[o,r]of Object.entries(s))n=n.replace(`{${o}}`,r);return n}function ul(t,s){return t.length<=s?t:`${t.substring(0,s-1)}…`}function jt(t,s){const n=t.verbiage||ll[t.title];if(!n){const r=t.prettyName||t.title;return s==="active"?`Using ${r}`:`Used ${r}`}const o=s==="active"?n.active:n.past;if(n.paramKey){const r=cl(t,n.paramKey);if(r){const i=ul(r,50);let a="value";return n.paramKey.includes("file")||n.paramKey.includes("path")?a="file":n.paramKey.includes("query")||n.paramKey.includes("pattern")?a="query":n.paramKey.includes("command")?a="command":n.paramKey.includes("directory")&&(a="directory"),dl(o,{[a]:i})}}if(t.subline){const r=o.split("{")[0];return r?`${r.trim()} ${t.subline}`:t.subline}return o.replace(/\s*\{[^}]+\}/g,"")}function ml(t){return t.prettyName||t.title}function De(t){return t.status==="pending"&&(!t.rawInput||Object.keys(t.rawInput).length===0)}function gt(t){return t.status==="failed"||t.error?"failed":!!(t.subagentMessages&&t.subagentMessages.length>0)&&t.subagentCompleted||t.status==="completed"?"completed":De(t)?"selecting":(t.status==="pending"||t.status==="in_progress","executing")}function la(t){switch(gt(t)){case"selecting":return`Selecting ${t.prettyName||t.title}`;case"executing":return jt(t,"active");case"completed":return jt(t,"past");case"failed":return`Failed to use ${t.prettyName||t.title}`;default:return t.prettyName||t.title}}function pl(t){return t.every(s=>gt(s)==="completed")}function fl(t){return t.some(s=>gt(s)==="failed")}function gl(t){return fl(t)?"failed":pl(t)?"completed":t.every(s=>De(s))?"selecting":"executing"}const Ss=Te("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"}}),hl=Te("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),ca=l.forwardRef(({content:t,isStreaming:s=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:r=!1,autoCollapse:i=!0,autoCollapseDelay:a=2e3,label:c="Thinking",variant:u,className:d},m)=>{const[p,g]=l.useState(n==="inline"?!0:o),[x,h]=l.useState(!1);return l.useEffect(()=>{if(i&&!s&&t&&n==="collapsible"){const f=setTimeout(()=>{h(!0),g(!1)},a);return()=>clearTimeout(f)}},[s,t,i,a,n]),l.useEffect(()=>{r&&s&&n==="collapsible"&&!x&&g(!0)},[r,s,n,x]),!t&&!s?null:n==="inline"?e.jsxs("div",{ref:m,className:y(Ss({variant:u}),"p-3",d),children:[e.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[e.jsx("span",{className:"text-caption font-medium text-foreground opacity-60 uppercase tracking-wide",children: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:m,className:y("mb-3",d),children:[e.jsxs("button",{type:"button",onClick:()=>{g(!p),h(!1)},className:"w-full flex items-center justify-between p-2.5 rounded-lg bg-card border border-border hover:bg-card/80 hover:shadow-sm transition-all text-left","aria-expanded":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(fe,{className:hl({expanded:p}),"aria-hidden":"true"})]}),p&&e.jsx("div",{className:y(Ss({variant:u}),"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:"..."})]})})]})});ca.displayName="Reasoning";function xl(){return t=>{Ta(t,"text",(s,n,o)=>{if(!o||n===void 0)return;const r=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g,i=s.value;if(!r.test(i))return;r.lastIndex=0;const a=[];let c=0,u;for(;(u=r.exec(i))!==null;){u.index>c&&a.push({type:"text",value:i.slice(c,u.index)});const d=u[1]??u[2]??"";a.push({type:"citation",data:{hName:"span",hProperties:{"data-citation-id":d,className:"citation-marker"}},sourceId:d}),c=u.index+u[0].length}c<i.length&&a.push({type:"text",value:i.slice(c)}),a.length>0&&o.children.splice(n,1,...a)})}}const Ut=ue("Response","debug");function bl(t){const s=/[",\n\r]/.test(t),n=t.replaceAll('"','""');return s?`"${n}"`:n}function ks(t){return Array.from(t.querySelectorAll("tr")).map(n=>Array.from(n.querySelectorAll("th,td")).map(r=>bl((r.textContent||"").trim())).join(",")).join(`
9
- `)}function yl(t,s,n){const o=new Blob([s],{type:n}),r=URL.createObjectURL(o),i=document.createElement("a");i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}function vl(t){const{className:s,...n}=t,o=l.useRef(null),[r,i]=l.useState(!1),a=l.useCallback(async()=>{const u=o.current;if(u)try{const d=ks(u);await navigator.clipboard.writeText(d),i(!0),me.success("Copied table as CSV"),setTimeout(()=>i(!1),1500)}catch{me.error("Failed to copy table")}},[]),c=l.useCallback(()=>{const u=o.current;if(!u)return;const d=ks(u);yl("table.csv",d,"text/csv;charset=utf-8"),me.success("Downloaded table.csv")},[]);return e.jsxs("div",{className:"group/table",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{ref:o,className:y("min-w-full border-collapse border border-border rounded-md",s),...n})}),e.jsxs(Gt,{className:y("mt-2 flex justify-end","opacity-0 group-hover/table:opacity-100 transition-opacity","pointer-events-none group-hover/table:pointer-events-auto"),children:[e.jsx(Ve,{onClick:a,tooltip:r?"Copied!":"Copy",children:r?e.jsx(lt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),e.jsx(Ve,{onClick:c,tooltip:"Download CSV",children:e.jsx(an,{className:"size-4"})})]})]})}const Fe=l.memo(l.forwardRef(({content:t,isStreaming:s=!1,showEmpty:n=!0,emptyMessage:o="",sources:r=[],messageId:i,citationIndexOffset:a=0,className:c,...u},d)=>{const[m,p]=l.useState(0);Ut.info("Response render",{contentLength:t.length,contentPreview:t.slice(0,100),sourcesCount:r.length,sourceIds:r.map(h=>h.id),remountKey:m}),l.useEffect(()=>{p(h=>(Ut.info("Sources changed, incrementing remountKey",{sourcesCount:r.length,sourceIds:r.map(f=>f.id),oldRemountKey:h}),h+1))},[r]);const g=l.useMemo(()=>[on,xl],[]),x=l.useMemo(()=>{const h={current:0};return{table:f=>e.jsx(vl,{...f}),thead:f=>e.jsx("thead",{className:y("bg-card border-b border-border",f.className),...f}),tr:f=>e.jsx("tr",{className:y("border-b border-border hover:bg-card transition-colors",f.className),...f}),th:f=>e.jsx("th",{className:y("px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",f.className),...f}),td:f=>e.jsx("td",{className:y("px-4 py-2 text-foreground border-r border-border last:border-r-0",f.className),...f}),span:f=>{const{className:b,class:N,"data-citation-id":v,children:C,...U}=f,B=b||N;if(B==="citation-marker"&&v){const D=a+h.current++;return Ut.info("Rendering citation marker",{citationId:v,sourcesAvailable:r.length,sourceIds:r.map(I=>I.id),foundSource:r.find(I=>I.id===v)?"yes":"no"}),i?e.jsx("span",{id:`citation-${i}-${D}`,"data-citation-source-id":v,"data-citation-anchor":"true",className:"inline-flex rounded-md",children:e.jsx(Ot,{sourceId:v,sources:r})}):e.jsx(Ot,{sourceId:v,sources:r})}return e.jsx("span",{className:B,...U,children:C})}}},[r,i,a]);return!t&&s&&n?e.jsx("div",{ref:d,className:y("opacity-70 italic text-paragraph-sm",c),...u,children:o}):t?e.jsx("div",{ref:d,...u,children:e.jsx(Ia,{className:y("size-full","[&>*:first-child]:mt-0 [&>*:last-child]:mb-0","[&_code]:whitespace-pre-wrap [&_code]:break-words","[&_pre]:max-w-full [&_pre]:overflow-x-auto",c),remarkPlugins:g,components:x,children:t},`streamdown-${m}`)}):null}),(t,s)=>t.content===s.content&&t.sources===s.sources);Fe.displayName="Response";function wl(t){if(!t.rawInput)return null;const s=["query","search_term","pattern","target_file","file_path","command","target_directory"];for(const n of s){const o=t.rawInput[n];if(typeof o=="string"&&o.trim())return o.trim()}return t.subline?t.subline:null}function Ft(t,s=3){if(t.length===0)return"";if(t.length===1)return t[0];if(t.length<=s)return`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`;const n=t.slice(0,s),o=t.length-s;return`${n.join(", ")} and ${o} more`}function jl(t){if(t.length===0)return null;const s=t[0],n=s.lastIndexOf("/");if(n===-1)return null;const o=s.substring(0,n);return t.every(i=>i.startsWith(`${o}/`))?o:null}function Nl(t,s){if(t.length===0)return"";if(t.length===1)return jt(t[0],s);const n=t[0],o=n.title,r=t.map(wl).filter(d=>d!==null);if((o==="Read"||o==="Write"||o==="read_file"||o==="write"||o==="search_replace"||o==="delete_file")&&r.length>0){const d=jl(r);if(d){const p=s==="active"?"working on":"worked on";return`${p.charAt(0).toUpperCase()+p.slice(1)} ${r.length} files in ${d}`}return`${o==="Read"||o==="read_file"?s==="active"?"Reading":"Read":o==="Write"||o==="write"?s==="active"?"Writing":"Wrote":o==="search_replace"?s==="active"?"Editing":"Edited":s==="active"?"Deleting":"Deleted"} ${Ft(r)}`}if((o==="WebSearch"||o==="Grep"||o==="web_search"||o==="codebase_search"||o==="grep")&&r.length>0)return`${o==="WebSearch"||o==="web_search"?s==="active"?"Searching the web for":"Searched the web for":o==="codebase_search"?s==="active"?"Searching codebase for":"Searched codebase for":s==="active"?"Searching for":"Searched for"} ${Ft(r)}`;const c=ml(n);return`${s==="active"?"Using":"Used"} ${c} ${t.length} times`}function Cl(t,s){if(t.length===0)return"";if(t.length===1)return jt(t[0],s);if([...new Set(t.map(i=>i.title))].length===1)return Nl(t,s);const o=t.map(i=>i.prettyName||i.title).filter((i,a,c)=>c.indexOf(i)===a);return`${s==="active"?"Running":"Ran"} ${Ft(o)}`}const Sl=50;function da({parentStatus:t,agentName:s,query:n,isExpanded:o,onExpandChange:r,storedMessages:i}){const[a,c]=l.useState(!1),u=o??a,[d,m]=l.useState(!0),[p,g]=l.useState(!0),x=l.useRef(null),h=i||[],f=t==="in_progress"||t==="pending",b=h[h.length-1],N=b&&(b.content||b.toolCalls&&b.toolCalls.length>0||b.contentBlocks&&b.contentBlocks.length>0),v=l.useRef(f);l.useEffect(()=>{v.current&&!f&&m(!1),v.current=f},[f]);const C=l.useCallback(()=>{const _=x.current;if(!_)return;const{scrollTop:M,scrollHeight:E,clientHeight:K}=_,Y=E-M-K;g(Y<Sl)},[]),U=l.useCallback(()=>{const _=x.current;_&&(_.scrollTop=_.scrollHeight)},[]);l.useEffect(()=>{p&&(f||N)&&U()},[p,f,N,U]),l.useEffect(()=>{const _=x.current;if(!_)return;const M=()=>C();return _.addEventListener("scroll",M,{passive:!0}),C(),()=>_.removeEventListener("scroll",M)},[C]),l.useEffect(()=>{d&&(g(!0),requestAnimationFrame(()=>{U()}))},[d,U]);const B=b?.content&&b.content.split(`
8
+ `);if(k.key==="ArrowUp"&&(P||!c||!O)){const Q=C(c);if(Q!==null){k.preventDefault(),u(Q),setTimeout(()=>{D.current&&(D.current.selectionStart=Q.length,D.current.selectionEnd=Q.length)},0);return}}else if(k.key==="ArrowDown"&&(j||!c||!O)){const Q=U();if(Q!==null){k.preventDefault(),u(Q),setTimeout(()=>{D.current&&(D.current.selectionStart=Q.length,D.current.selectionEnd=Q.length)},0);return}}}g&&k.key==="Enter"&&!k.shiftKey&&(c.trim()&&!p&&!m?(k.preventDefault(),d()):(p||m)&&k.preventDefault()),n?.(k)},onDrop:async k=>{k.preventDefault(),_(!1);const S=k.dataTransfer.files;if(!S||S.length===0||!o)return;const P=[];for(const j of Array.from(S))if(j.type.startsWith("image/"))try{const O=await A(j);P.push({name:j.name,path:j.name,size:j.size,mimeType:j.type,data:O})}catch(O){console.error("Failed to process dropped file:",j.name,O)}P.length>0&&o(P)},onDragOver:k=>{k.preventDefault(),_(!0)},onDragLeave:k=>{k.preventDefault(),_(!1)},disabled:m,...i};return t&&l.isValidElement(r)?l.cloneElement(r,T):e.jsx("textarea",{...T,rows:1,className:y("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 max-h-[6lh] min-h-[44px]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-paragraph-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",I&&"ring-2 ring-primary ring-offset-2",s)})});On.displayName="ChatInput.Field";const Fn=l.forwardRef(({asChild:t=!1,className:s,disabled:n,children:o,...r},i)=>{const{value:a,disabled:c,isSubmitting:u}=ft();if(u)return null;const d=n||c||!a.trim(),m=t?ye:re;return e.jsx(m,{ref:i,type:"submit",disabled:d,variant:t?void 0:"default",size:"icon",className:y(!t&&"gap-1.5 rounded-full",s),...r,children:o})});Fn.displayName="ChatInput.Submit";const Bn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const{onCancel:i,isSubmitting:a}=ft(),c=t?ye:re;return a?e.jsx(c,{ref:r,type:"button",onClick:()=>i?.(),variant:t?void 0:"default",size:"icon",className:y(!t&&"gap-1.5 rounded-full",s),...o,children:n||e.jsx(qa,{className:"size-4 fill-current"})}):null});Bn.displayName="ChatInput.Stop";const Hn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex items-center justify-between p-2",t),...n,children:s}));Hn.displayName="ChatInput.Toolbar";const Wn=l.forwardRef(({asChild:t=!1,className:s,children:n,onClick:o,...r},i)=>{const{value:a,onChange:c,setShowCommandMenu:u,setCommandMenuQuery:d}=ft(),m=g=>{a.startsWith("/")||(c("/"),u(!0),d("")),o?.(g)},p=t?ye:re;return e.jsx(p,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:m,...r,children:n||e.jsx(Ka,{className:"size-4"})})});Wn.displayName="ChatInput.Actions";const Vn=l.forwardRef(({asChild:t=!1,className:s,children:n,onFilesSelected:o,...r},i)=>{const a=l.useRef(null),c=p=>new Promise((g,x)=>{const h=new FileReader;h.readAsDataURL(p),h.onload=()=>{const f=h.result.split(",")[1];g(f||"")},h.onerror=f=>x(f)}),u=async p=>{const g=p.target.files;if(!g||g.length===0)return;const x=[];for(const h of Array.from(g))if(h.type.startsWith("image/"))try{const f=await c(h);x.push({name:h.name,path:h.name,size:h.size,mimeType:h.type,data:f})}catch(f){console.error("Failed to process file:",h.name,f)}x.length>0&&o&&o(x),a.current&&(a.current.value="")},d=p=>{p.preventDefault(),a.current?.click()},m=t?ye:re;return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:a,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:u}),e.jsx(m,{ref:i,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),onClick:d,...r,children:n||e.jsx(Ya,{className:"size-4"})})]})});Vn.displayName="ChatInput.Attachment";const qn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const i=t?ye:re;return e.jsx(i,{ref:r,type:"button",variant:"ghost",size:"icon",className:y("rounded-full",s),...o,children:n||e.jsx(Qa,{className:"size-4"})})});qn.displayName="ChatInput.VoiceInput";const Kn=l.forwardRef(({commands:t=[],className:s,onChange:n,...o},r)=>{const{showCommandMenu:i,commandMenuQuery:a,selectedMenuIndex:c,setSelectedMenuIndex:u,setMenuItemCount:d,triggerCounter:m,onChange:p,setShowCommandMenu:g,setCommandMenuQuery:x}=ft();return e.jsx(zn,{ref:r,commands:t,showCommandMenu:i,commandMenuQuery:a,selectedMenuIndex:c,setSelectedMenuIndex:u,setMenuItemCount:d,triggerCounter:m,onChange:p,onClose:()=>{g(!1),x("")},className:s,...o})});Kn.displayName="ChatInput.CommandMenu";function yi({parameters:t,className:s}){const n=H(c=>c.input.selectedPromptParameters),o=H(c=>c.setSelectedPromptParameters),r=l.useCallback(c=>c.defaultOptionId??c.options[0]?.id??"",[]);l.useEffect(()=>{if(!n||Object.keys(n).length===0){const c={};for(const u of t)c[u.id]=r(u);Object.keys(c).length>0&&o(c)}},[t,n,o,r]);const i=l.useCallback((c,u)=>{const d={...n,[c]:u};o(d)},[n,o]);if(t.length===0)return null;const a=t.map(c=>{const u=n?.[c.id],d=r(c),m=c.options.find(g=>g.id===u);return{param:c,selectedOption:m,isNonDefault:u&&u!==d}}).filter(c=>c.selectedOption);return e.jsx("div",{className:y("flex items-center gap-1",s),children:a.map(({param:c,selectedOption:u,isNonDefault:d})=>e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsxs("button",{type:"button",className:y("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",d?"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:u?.label}),e.jsx(fe,{className:"h-4 w-4 opacity-50"})]})}),e.jsx(qe,{align:"start",className:"min-w-[160px]",children:c.options.map(m=>e.jsx(je,{onClick:()=>i(c.id,m.id),className:y(n?.[c.id]===m.id&&"bg-accent"),children:m.label},m.id))})]},c.id))})}function vi(t){const[s,n]=l.useState({width:0,height:0});return l.useEffect(()=>{const o=t.current;if(!o)return;const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const c=a[0];if(!c)return;const{width:u,height:d}=c.contentRect;n({width:u,height:d})});r.observe(o);const i=o.getBoundingClientRect();return n({width:i.width,height:i.height}),()=>{r.disconnect()}},[t]),s}function wi(){const t=l.useRef(null),s=l.useRef(null),[n,o]=l.useState(!0),r=l.useRef(!0),i=l.useRef(!1),[a,c]=l.useState(!1),[u,d]=l.useState(!1),[m,p]=l.useState(0),[g,x]=l.useState(0),h=l.useRef(-1),f=l.useRef(!1),b=l.useRef(null);l.useEffect(()=>{r.current=n},[n]);const N=l.useCallback(()=>{if(!t.current)return!0;const{scrollTop:z,scrollHeight:W,clientHeight:V}=t.current;return z+V>=W-100},[]),v=l.useCallback(()=>{if(!t.current)return[];const z=t.current.querySelectorAll('[aria-label="user message"]');return Array.from(z)},[]),C=l.useCallback(()=>{const z=t.current;if(!z)return[];const W=z.getBoundingClientRect();return v().map((T,k)=>{const P=T.getBoundingClientRect().bottom<W.top+50,j=T.textContent||"",O=j.slice(0,100)+(j.length>100?"...":"");return{index:k,preview:O,element:T,isAboveFold:P}}).filter(({isAboveFold:T})=>T).map(({index:T,preview:k,element:S})=>({index:T,preview:k,element:S}))},[v]),U=l.useCallback((z,W="smooth")=>{const V=v();if(z<0||z>=V.length)return;const T=V[z];if(T){f.current=!0,b.current&&clearTimeout(b.current),T.scrollIntoView({behavior:W,block:"start"}),h.current=z,p(z);const k=V.length-1-z;x(k),d(k>0),b.current=setTimeout(()=>{f.current=!1},500)}},[v]),B=l.useCallback(()=>{const z=t.current;if(!z)return[];const W=z.getBoundingClientRect();return v().filter(T=>T.getBoundingClientRect().bottom<W.top+50)},[v]);l.useCallback(()=>B().length>0,[B]);const D=l.useCallback(()=>{const z=t.current;if(!z)return-1;const W=z.getBoundingClientRect(),V=v();for(let T=0;T<V.length;T++){const k=V[T]?.getBoundingClientRect();if(k&&(k.top>=W.top-50&&k.top<W.top+150||k.top<W.top&&k.bottom>W.top+50))return T}for(let T=V.length-1;T>=0;T--){const k=V[T]?.getBoundingClientRect();if(k&&k.bottom<W.top+50)return T}return-1},[v]);l.useCallback(()=>{const z=v(),W=h.current!==-1?h.current:D();return W===-1?!1:W<z.length-1},[v,D]);const I=l.useCallback((z="smooth")=>{t.current&&(t.current.scrollTo({top:t.current.scrollHeight,behavior:z}),h.current=-1)},[]),_=l.useCallback((z="smooth")=>{const W=t.current;if(!W)return;const V=v();if(V.length===0)return;const T=W.getBoundingClientRect(),k=[];for(let P=0;P<V.length;P++){const j=V[P]?.getBoundingClientRect();j&&j.bottom<T.top+50&&k.push(P)}if(k.length===0)return;let S;if(h.current===-1){const P=k[k.length-1];if(P===void 0)return;S=P}else{const P=k.filter(j=>j<h.current);if(P.length>0){const j=P[P.length-1];if(j===void 0)return;S=j}else{const j=k[0];if(j===void 0)return;S=j}}if(S>=0&&S<V.length){const P=V[S];if(P){f.current=!0,b.current&&clearTimeout(b.current),P.scrollIntoView({behavior:z,block:"start"}),h.current=S,p(S);const j=V.length-1-S;x(j),d(j>0),b.current=setTimeout(()=>{f.current=!1},500)}}},[v]),M=l.useCallback((z="smooth")=>{if(!t.current)return;const V=v();if(V.length!==0&&h.current!==-1){const T=h.current+1;if(T<V.length){const k=V[T];if(k){f.current=!0,b.current&&clearTimeout(b.current),k.scrollIntoView({behavior:z,block:"start"}),h.current=T,p(T);const S=V.length-1-T;x(S),d(S>0),b.current=setTimeout(()=>{f.current=!1},500)}}}},[v]);l.useCallback(()=>h.current>0?!0:B().length>0,[B]),l.useCallback(()=>{const z=v();return h.current===-1?!1:h.current<z.length-1},[v]);const A=l.useCallback(()=>{h.current=-1},[]);l.useEffect(()=>{const z=t.current;if(!z)return;let W;const V=()=>{i.current=!0,clearTimeout(W);const T=N();o(T),r.current=T;const k=B(),S=k.length>0;if(c(S),!f.current){const P=D();P!==-1&&(h.current=P);const j=v();p(k.length);const O=h.current!==-1?h.current:P,Q=O!==-1&&O<j.length-1?j.length-1-O:0;x(Q),d(Q>0)}W=setTimeout(()=>{i.current=!1},150)};return z.addEventListener("scroll",V,{passive:!0}),()=>{z.removeEventListener("scroll",V),clearTimeout(W)}},[N,D,v,B]),l.useEffect(()=>{const z=t.current;if(!z)return;const W=()=>{r.current&&!i.current&&requestAnimationFrame(()=>{z.scrollTo({top:z.scrollHeight,behavior:"instant"}),o(!0),r.current=!0})},V=new MutationObserver(W);V.observe(z,{childList:!0,subtree:!0,characterData:!0});const T=new ResizeObserver(W);return T.observe(z),Array.from(z.children).forEach(k=>{T.observe(k)}),()=>{V.disconnect(),T.disconnect()}},[]);function K(){o(!0),r.current=!0}function Y(){o(!1),r.current=!1}return{containerRef:t,endRef:s,isAtBottom:n,scrollToBottom:I,onViewportEnter:K,onViewportLeave:Y,isUserMessageAboveFold:a,hasMoreUserMessagesBelow:u,userMessagesAboveCount:m,userMessagesBelowCount:g,scrollToPreviousUserMessage:_,scrollToNextUserMessage:M,scrollToUserMessageByIndex:U,getUserMessagePreviews:C,resetUserMessageCycle:A}}const ji=({...t})=>e.jsx(ka,{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}),Jt=l.createContext(void 0),Me=()=>{const t=l.useContext(Jt);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},Yn=l.forwardRef(({defaultSidebarOpen:t=!1,defaultPanelSize:s="hidden",defaultActiveTab:n="todo",className:o,children:r,...i},a)=>{const[c,u]=l.useState(t),[d,m]=l.useState(s),[p,g]=l.useState(n),x=l.useMemo(()=>d!=="hidden",[d]),h=l.useRef(!1),[f,b]=l.useState(!1),[N,v]=l.useState(bn),[C,U]=l.useState(0),B=l.useCallback(()=>{h.current||(h.current=!0,m(I=>I==="hidden"?"large":"hidden"),setTimeout(()=>{h.current=!1},350))},[]),D=l.useCallback(I=>{m(I?"large":"hidden")},[]);return l.useEffect(()=>{const I=_=>{_.key.toLowerCase()==="b"&&(_.metaKey||_.ctrlKey)&&!_.shiftKey&&(_.preventDefault(),B())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[B]),e.jsx(Jt.Provider,{value:{sidebarOpen:c,setSidebarOpen:u,panelSize:d,setPanelSize:I=>{m(I),D(I!=="hidden")},activeTab:p,setActiveTab:g,panelOpen:x,setPanelOpen:D,togglePanel:B,isDraggingAside:f,setIsDraggingAside:b,asideWidth:N,setAsideWidth:v,mainWidth:C,setMainWidth:U},children:e.jsx("div",{ref:a,"data-panel-state":x?"expanded":"collapsed",className:y("flex h-screen flex-row bg-background text-foreground overflow-hidden",o),...i,children:r})})});Yn.displayName="ChatLayout.Root";const Ni=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("relative z-10 border-b border-border bg-card shrink-0",t),...n,children:s}));Ni.displayName="ChatLayout.Header";const Qn=l.forwardRef(({className:t,children:s},n)=>{const{panelOpen:o,isDraggingAside:r,asideWidth:i,setMainWidth:a}=Me(),c=l.useRef(null),{width:u}=vi(c);return l.useEffect(()=>{a(u)},[u,a]),l.useImperativeHandle(n,()=>c.current),e.jsx("div",{ref:c,className:y("flex flex-1 flex-col overflow-hidden h-full min-w-0",!r&&"transition-[padding] duration-250",t),style:{paddingRight:o?i:0},children:s})});Qn.displayName="ChatLayout.Main";const Gn=l.forwardRef(({showToaster:t=!0,className:s,children:n,...o},r)=>e.jsxs("div",{ref:r,className:y("relative flex flex-1 flex-col overflow-hidden",s),...o,children:[n,t&&e.jsx(ji,{})]}));Gn.displayName="ChatLayout.Body";const Xn=l.forwardRef(({className:t,children:s,onScrollChange:n,showScrollToBottom:o=!0,initialScrollToBottom:r=!0,...i},a)=>{const{mainWidth:c}=Me(),{containerRef:u,endRef:d,isAtBottom:m,scrollToBottom:p,userMessagesAboveCount:g,scrollToUserMessageByIndex:x}=wi(),h=l.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=l.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}}}),[]),[b,N]=l.useState(!1),[v,C]=l.useState([]),[U,B]=l.useState(null),[D,I]=l.useState(0),_=l.useRef(null),M=l.useRef(null),A=l.useRef(null),K=l.useRef(0),Y=l.useCallback(()=>{const $=u.current;if(!$)return[];const X=$.querySelectorAll('[aria-label="user message"]');return Array.from(X).map((R,E)=>{const J=R.textContent||"",G=J.slice(0,100)+(J.length>100?"...":"");return{index:E,preview:G}})},[u]);l.useEffect(()=>{const $=u.current;if(!$)return;const X=()=>{const E=Y();C(E)};X();const R=new MutationObserver(X);return R.observe($,{childList:!0,subtree:!0}),()=>{R.disconnect()}},[u,Y]),l.useEffect(()=>()=>{_.current&&clearTimeout(_.current),M.current&&clearTimeout(M.current),A.current!==null&&cancelAnimationFrame(A.current)},[]);const z=c>Rr+Mr,W=v.length>1&&z,V=l.useCallback($=>{const R=$.currentTarget.getBoundingClientRect(),E=$.clientY-R.top;K.current=E,A.current===null&&(A.current=requestAnimationFrame(()=>{I(K.current),A.current=null}))},[]),T=l.useCallback(()=>{M.current&&(clearTimeout(M.current),M.current=null),_.current=setTimeout(()=>{N(!0)},1500)},[]),k=l.useCallback(()=>{_.current&&(clearTimeout(_.current),_.current=null),M.current=setTimeout(()=>{N(!1),B(null)},500)},[]),S=l.useCallback($=>{B($)},[]),P=l.useCallback(()=>{B(null)},[]),j=l.useCallback($=>{x($,"smooth")},[x]),O=l.useRef(!1);l.useImperativeHandle(a,()=>u.current),l.useEffect(()=>{n?.(m)},[m,n]),l.useEffect(()=>{if(!r)return;const $=u.current;if($&&!O.current){const X=setTimeout(()=>{$.scrollTop=$.scrollHeight,O.current=!0},100);return()=>clearTimeout(X)}},[r,u]);const Q=!m&&o;return e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsxs("div",{ref:u,className:y("h-full overflow-y-auto flex flex-col",t),...i,children:[e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s}),e.jsx("div",{ref:d,className:"shrink-0"})]}),e.jsx(ot,{mode:"wait",children:W&&e.jsxs(ke.nav,{variants:h,initial:"hidden",animate:"visible",exit:"exit",className:"absolute p-4 left-0 top-1/2 -translate-y-1/2 z-10",onMouseEnter:T,onMouseMove:V,onMouseLeave:k,"aria-label":"User message navigation",children:[e.jsx("div",{className:"flex flex-col",children:v.map(({index:$})=>{const X=$===g,R=U===$;return e.jsx("button",{type:"button",onClick:()=>j($),onMouseEnter:()=>S($),onMouseLeave:P,className:"py-2 px-1 group","aria-label":`Go to user message ${$+1}`,children:e.jsx("div",{className:y("w-4 h-[2px] rounded-full bg-primary transition-opacity duration-200",X?"opacity-80":"opacity-10",R&&"opacity-60",!R&&"group-hover:opacity-60")})},$)})}),e.jsx(ot,{children:b&&v.length>0&&U!==null&&(()=>{const R=40*Math.min(3,v.length)+10,E=40,J=40*U,G=E-J,Ie=0,ne=R-40*v.length-10,le=Math.max(ne,Math.min(Ie,G));return e.jsx(ke.div,{variants:f,initial:"hidden",animate:"visible",exit:"exit",className:y("absolute left-12 pointer-events-none","w-72 overflow-hidden","bg-card border border-border rounded-lg shadow-xl"),style:{top:`${D}px`,y:"-50%",height:`${R}px`,willChange:"transform"},children:e.jsx("div",{className:"p-1",style:{transform:`translateY(${le}px)`,transition:"transform 0.15s cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:v.map(({index:oe,preview:ve})=>{const ze=oe===U;return e.jsx("div",{className:y("w-full text-left px-3 py-2 rounded-md","text-sm text-muted-foreground","transition-colors duration-100","truncate",ze&&"bg-accent text-foreground"),style:{height:"40px"},children:ve},oe)})})},"hover-menu")})()})]},"toc")}),Q&&e.jsx("button",{type:"button",onClick:()=>p("smooth"),className:y("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:e.jsx(Ga,{className:"size-4"})})]})});Xn.displayName="ChatLayout.Messages";const Jn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("bg-linear-to-t from-background to-transparent px-4 pb-4",t),...n,children:e.jsx("div",{className:"mx-auto max-w-chat",children:s})}));Jn.displayName="ChatLayout.Footer";const Ci=l.forwardRef(({className:t,children:s,...n},o)=>{const{sidebarOpen:r}=Me();return r?e.jsx("div",{ref:o,className:y("border-r border-border bg-card w-64 overflow-y-auto",t),...n,children:s}):null});Ci.displayName="ChatLayout.Sidebar";const Zn=l.forwardRef(({breakpoint:t="md",onClose:s,className:n,children:o},r)=>{const{panelSize:i,togglePanel:a,setIsDraggingAside:c,setAsideWidth:u}=Me(),[d,m]=l.useState(bn),[p,g]=l.useState(d),[x,h]=l.useState(!1),f=l.useRef(0),b=l.useRef(d),N=i!=="hidden",[v,C]=l.useState(!1);l.useEffect(()=>{if(!N){C(!1);return}const A=requestAnimationFrame(()=>{C(!0)});return()=>cancelAnimationFrame(A)},[N]);const U=vn();yn(U&&N),l.useEffect(()=>{g(d)},[d]),l.useEffect(()=>{N&&u(x?p:d)},[N,x,p,d,u]);const B=l.useCallback(A=>{A.preventDefault(),h(!0),c(!0),f.current=A.clientX,b.current=d,A.target.setPointerCapture(A.pointerId)},[d,c]),D=l.useCallback(A=>{if(!x)return;const K=A.clientX-f.current,Y=Math.max(bs,Math.min(ys,b.current-K));g(Y)},[x]),I=l.useCallback(A=>{if(!x)return;const K=A.clientX-f.current,Y=Math.max(bs,Math.min(ys,b.current-K));m(Y),g(Y),h(!1),c(!1),A.target.releasePointerCapture(A.pointerId)},[x,c]),_=N&&U,M=N&&!U;return e.jsxs(ot,{initial:!1,children:[_&&e.jsx(ke.aside,{variants:Ur,initial:"initial",animate:"animate",exit:"exit",transition:Lr,className:y("fixed inset-0 z-50 bg-card","flex flex-col","block md:hidden",n),"data-aside":"aside","data-mobile":"true",children:e.jsxs(ke.div,{className:"flex flex-col h-full",variants:zr,initial:"initial",animate:"animate",transition:$r,children:[e.jsx("div",{className:"flex justify-end px-4 pt-3 shrink-0",children:e.jsx(Re,{onClick:()=>{s?.(),a()},"aria-label":"Close panel",children:e.jsx(It,{className:"size-4"})})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:o})]})},"aside-mobile"),M&&e.jsx("aside",{ref:r,style:{width:x?p:v?d:0,transition:x?"none":"width 0.25s cubic-bezier(0.25, 0.1, 0.25, 1)"},className:y("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",n),"data-aside":"aside",children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{onPointerDown:B,onPointerMove:D,onPointerUp:I,className:y("absolute left-0 inset-y-0 w-2 -ml-1 cursor-col-resize z-10","group flex items-center justify-center","hover:bg-primary/5 transition-colors delay-300",x&&"bg-primary/10")}),e.jsx("div",{className:y("h-full overflow-y-auto",x?"w-full":void 0),style:x?void 0:{width:`${d}px`},children:o})]})},"aside-desktop")]})});Zn.displayName="ChatLayout.Aside";class Si{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:n}=await s.json();return n.map(this.toFileSystemItem)}catch(s){return console.error("Error fetching sandbox root items:",s),[]}}async getItemChildren(s){try{const n=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=${encodeURIComponent(s)}`);if(!n.ok)return console.error("Failed to fetch sandbox directory:",await n.text()),[];const{files:o}=await n.json();return o.map(this.toFileSystemItem)}catch(n){return console.error("Error fetching sandbox item children:",n),[]}}async getItemDetails(s){try{const n=s.substring(0,s.lastIndexOf("/")),o=await fetch(`${this.connection.apiUrl}/sandbox/files?sessionId=${this.connection.sessionId}&path=${encodeURIComponent(n||"/")}`);if(!o.ok)throw new Error(`Failed to fetch file details: ${await o.text()}`);const{files:r}=await o.json(),i=r.find(a=>a.path===s);if(!i)throw new Error(`File not found: ${s}`);return this.toFileSystemItem(i)}catch(n){throw console.error("Error fetching sandbox item details:",n),n}}toFileSystemItem=s=>{const n=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),...n!==void 0&&{extension:n}}}}function ea({item:t,level:s=0,onSelect:n,selectedId:o,isDropTarget:r=!1,onDownload:i}){const[a,c]=l.useState(!0),u=o===t.id,d=()=>{t.type==="folder"&&c(!a)},m=()=>{n?.(t),t.type==="folder"&&d()},p=x=>{x.key==="Enter"||x.key===" "?(x.preventDefault(),m()):x.key==="ArrowRight"&&t.type==="folder"&&!a?(x.preventDefault(),c(!0)):x.key==="ArrowLeft"&&t.type==="folder"&&a&&(x.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"?a:void 0,className:y("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",u&&"bg-accent",r&&["bg-accent","border border-dashed border-border-dark"]),onClick:m,onKeyDown:p,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:t.type==="folder"?a?e.jsx(Xa,{className:"size-4"}):e.jsx(Ja,{className:"size-4"}):e.jsx(Za,{className:"size-4"})}),e.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:t.name}),e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsx("button",{className:y("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:x=>{x.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(eo,{className:"size-4"})})}),e.jsx(qe,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:x=>x.stopPropagation(),children:i&&e.jsx(je,{onClick:x=>{x.stopPropagation(),i(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(fe,{className:y("size-4 transition-transform",!a&&"-rotate-90")})})]}),t.type==="folder"&&a&&t.children&&e.jsx("div",{className:"flex flex-col",children:t.children.map(x=>e.jsx(ea,{item:x,level:s+1,...n&&{onSelect:n},...o&&{selectedId:o},...i&&{onDownload:i}},x.id))})]})}const ki=new vr;function Ti({className:t,provider:s=ki,onItemSelect:n,onDownload:o}){const[r,i]=l.useState([]),[a,c]=l.useState(),[u,d]=l.useState(!0),[m,p]=l.useState(),[g,x]=l.useState(0);l.useEffect(()=>{const f=setInterval(()=>{x(b=>b+1)},6e4);return()=>clearInterval(f)},[]),l.useEffect(()=>{(async()=>{try{d(!0);const b=await s.getRootItems();i(b),p(void 0)}catch(b){p(b instanceof Error?b.message:"Failed to load items")}finally{d(!1)}})()},[s]);const h=f=>{c(f.id),n?.(f)};return u?e.jsx("div",{className:y("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):m?e.jsx("div",{className:y("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",m]})}):r.length===0?e.jsxs("div",{className:y("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",t),children:[e.jsx(We,{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:y("flex flex-col",t),children:r.map(f=>e.jsx(ea,{item:f,onSelect:h,...a&&{selectedId:a},...o&&{onDownload:o}},f.id))})}const Lt=l.forwardRef(({source:t,isSelected:s,className:n,...o},r)=>{const i=t.usedIn??[],a=l.useCallback(u=>{document.querySelectorAll("[data-citation-highlight='true']").forEach(d=>{d.removeAttribute("data-citation-highlight"),d.classList.remove("ring-2","ring-ring","ring-offset-2","ring-offset-background")}),u.setAttribute("data-citation-highlight","true"),u.classList.add("ring-2","ring-ring","ring-offset-2","ring-offset-background"),window.setTimeout(()=>{u.getAttribute("data-citation-highlight")==="true"&&(u.removeAttribute("data-citation-highlight"),u.classList.remove("ring-2","ring-ring","ring-offset-2","ring-offset-background"))},1400)},[]),c=l.useCallback((u,d)=>{const p=Array.from(document.querySelectorAll(`[data-citation-anchor="true"][data-citation-source-id="${CSS.escape(u)}"]`))[d];return p?(p.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),window.setTimeout(()=>a(p),150),!0):!1},[a]);return e.jsxs("button",{ref:r,type:"button",className:y("group flex w-full text-left gap-2 items-start p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",s&&"bg-accent",n),onClick:()=>{window.open(t.url,"_blank","noopener,noreferrer")},...o,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-0.5 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]})]}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Referenced"}),Array.from({length:Math.min(i.length,12)},(u,d)=>d).map(u=>e.jsx("span",{role:"button",tabIndex:0,className:y("px-1.5 py-0.5 rounded-md","text-[10px] leading-none font-medium","bg-muted text-muted-foreground","hover:bg-accent hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark","cursor-pointer select-none"),onClick:d=>{d.preventDefault(),d.stopPropagation(),c(t.id,u)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),d.stopPropagation(),c(t.id,u))},"aria-label":`Scroll to citation ${u+1}`,children:u+1},`${t.id}-use-${u}`)),i.length>12&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",i.length-12," more"]})]})]})]})});Lt.displayName="SourceListItem";const Zt=za,He=l.forwardRef(({className:t,...s},n)=>e.jsx(Os,{ref:n,className:y("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));He.displayName=Os.displayName;const Ue=l.forwardRef(({className:t,...s},n)=>e.jsx(Fs,{ref:n,className:y("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-paragraph-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...s}));Ue.displayName=Fs.displayName;const pe=l.forwardRef(({className:t,...s},n)=>e.jsx(Bs,{ref:n,className:y("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));pe.displayName=Bs.displayName;const ta=l.forwardRef(({todo:t,className:s,...n},o)=>{const r=t.status==="completed";return e.jsxs("div",{ref:o,className:y("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,...n,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(Rt,{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(Tt,{className:"size-4 text-foreground"})}),e.jsx("p",{className:y("flex-1 text-foreground",r&&"line-through text-muted-foreground",t.status==="in_progress"&&"font-medium"),children:t.text})]})});ta.displayName="TodoListItem";function Ii(){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(_t,{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 es=l.forwardRef(({client:t,todos:s,className:n,...o},r)=>{const i=s||[];return i.length===0?e.jsx("div",{ref:r,className:y("h-full",n),...o,children:e.jsx(Ii,{})}):e.jsx("div",{ref:r,className:y("space-y-2 overflow-y-auto",n),...o,children:i.map(a=>e.jsx(ta,{todo:a},a.id))})});es.displayName="TodoList";const ts=l.forwardRef(({todos:t=[],className:s,...n},o)=>e.jsx("div",{ref:o,className:y("h-full",s),...n,children:e.jsx(es,{todos:t,className:"h-full"})}));ts.displayName="TodoTabContent";const ss=l.forwardRef(({files:t=[],provider:s,sessionId:n,agentApiUrl:o,client:r,onFileSelect:i,className:a,...c},u)=>{const[d,m]=l.useState(0),p=l.useRef(void 0),g=l.useCallback(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{m(f=>f+1)},300)},[]);l.useEffect(()=>!n||!r?void 0:r.onFileSystemChange(n,b=>{console.log("Files changed:",b),g()}),[n,r,g]);const x=l.useMemo(()=>{if(s)return s;if(n&&o)return new Si({sessionId:n,apiUrl:o})},[s,n,o]),h=l.useCallback(async f=>{if(f.type==="folder"){console.warn("Cannot download folders");return}if(!n||!o){console.error("Cannot download: missing sessionId or agentApiUrl");return}try{const b=`${o}/sandbox/download?sessionId=${encodeURIComponent(n)}&path=${encodeURIComponent(f.path||f.name)}`,N=document.createElement("a");N.href=b,N.download=f.name,document.body.appendChild(N),N.click(),document.body.removeChild(N)}catch(b){console.error("Failed to download file:",b)}},[n,o]);return e.jsx("div",{ref:u,className:y("h-full",a),...c,children:e.jsx(Ti,{...x&&{provider:x},onItemSelect:f=>{f.type==="file"&&i&&i(f.path||f.name)},onDownload:h,className:"h-full"},d)})});ss.displayName="FilesTabContent";const ns=l.forwardRef(({sources:t=[],highlightedSourceId:s,className:n,...o},r)=>{const{usedSources:i,consultedSources:a}=l.useMemo(()=>{const m=[],p=[];for(const g of t)g.usedIn&&g.usedIn.length>0?m.push(g):p.push(g);return{usedSources:m,consultedSources:p}},[t]),c=i.length>0?"used":"consulted",[u,d]=l.useState(c);return l.useEffect(()=>{d(c)},[c]),t.length===0?e.jsxs("div",{ref:r,className:y("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",n),...o,children:[e.jsx(tn,{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.jsxs(Zt,{value:u,onValueChange:m=>d(m),className:y("flex flex-col gap-2",n),children:[e.jsx("div",{className:y("sticky top-0 z-10 -mx-4 -mt-4 mb-4 px-4 bg-card border-b border-border","before:content-[''] before:absolute before:left-0 before:right-0 before:-top-4 before:h-4 before:bg-card before:pointer-events-none"),children:e.jsxs(He,{className:"w-full h-auto p-0 bg-transparent rounded-none justify-start",children:[e.jsxs(Ue,{value:"used",disabled:i.length===0,className:y("flex-1 !text-xs !px-2 !py-2 rounded-none","bg-transparent shadow-none","border-b-2 border-transparent -mb-px","text-muted-foreground hover:text-foreground","data-[state=active]:bg-transparent data-[state=active]:shadow-none","data-[state=active]:text-foreground data-[state=active]:border-foreground"),children:["Referenced (",i.length,")"]}),e.jsxs(Ue,{value:"consulted",disabled:a.length===0,className:y("flex-1 !text-xs !px-2 !py-2 rounded-none","bg-transparent shadow-none","border-b-2 border-transparent -mb-px","text-muted-foreground hover:text-foreground","data-[state=active]:bg-transparent data-[state=active]:shadow-none","data-[state=active]:text-foreground data-[state=active]:border-foreground"),children:["Reviewed (",a.length,")"]})]})}),e.jsx(pe,{value:"used",className:"mt-0",children:i.length>0?e.jsx("div",{ref:r,className:"space-y-2",...o,children:i.map(m=>e.jsx(Lt,{source:m,isSelected:m.id===s},m.id))}):e.jsx("div",{ref:r,className:"text-xs text-muted-foreground",...o,children:"No referenced sources yet."})}),e.jsx(pe,{value:"consulted",className:"mt-0",children:a.length>0?e.jsx("div",{ref:r,className:"space-y-2",...o,children:a.map(m=>e.jsx(Lt,{source:m,isSelected:m.id===s},m.id))}):e.jsx("div",{ref:r,className:"text-xs text-muted-foreground",...o,children:"No reviewed sources."})})]})});ns.displayName="SourcesTabContent";const Ri=l.forwardRef(({data:t,className:s,...n},o)=>e.jsxs("div",{ref:o,className:y("space-y-4",s),...n,children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Database"}),e.jsxs("div",{className:"text-paragraph-sm text-muted-foreground",children:[e.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),e.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[e.jsx("p",{children:"Your large data table would go here"}),t&&typeof t=="object"?e.jsx("pre",{className:"mt-2 text-caption overflow-auto",children:JSON.stringify(t,null,2)}):null]})]})]}));Ri.displayName="DatabaseTabContent";const _i=({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(n=>n.prettyName||n.name).join(", ")]})]})},sa=l.forwardRef(({tools:t=[],mcps:s=[],subagents:n=[],className:o,...r},i)=>e.jsxs("div",{ref:i,className:y("space-y-6",o),...r,children:[e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Tools"}),t.length>0?e.jsx("div",{className:"space-y-2",children:t.map(a=>e.jsx(_i,{tool:a},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No tools available"})]}),e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"MCP Servers"}),s.length>0?e.jsx("div",{className:"space-y-2",children:s.map(a=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:a.name}),e.jsxs("div",{className:"text-caption text-muted-foreground mt-1",children:["Transport: ",a.transport]})]},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No MCP servers connected"})]}),e.jsxs("div",{className:"space-y-3 p-2",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Subagents"}),n.length>0?e.jsx("div",{className:"space-y-2",children:n.map(a=>e.jsxs("div",{className:"p-3 border border-border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"font-medium text-paragraph-sm",children:a.name}),e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-2",children:a.description})]},a.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No subagents available"})]})]}));sa.displayName="SettingsTabContent";const Mi=l.forwardRef(({client:t,todos:s,variant:n="animated",showIcons:o=!1,visibleTabs:r=["todo","files","database"],className:i,...a},c)=>{const u=s||[],[d,m]=l.useState(r[0]||"todo"),p=l.useRef(null),g=l.useRef(null);l.useEffect(()=>{const b=setTimeout(()=>{const N=p.current;if(d&&N){const v=g.current;if(v){const C=N.getBoundingClientRect(),U=v.getBoundingClientRect(),B=U.left-C.left,D=U.width,I=B/C.width*100,_=100-(B+D)/C.width*100;N.style.clipPath=`inset(0 ${_.toFixed(2)}% 0 ${I.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(b)},[d]);const h=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:_t},{id:"files",label:"Files",icon:We},{id:"database",label:"Database",icon:sn},{id:"sources",label:"Sources",icon:nn}].filter(f=>r.includes(f.id));return e.jsx("div",{ref:c,className:y("select-none",i),...a,children:e.jsxs(Zt,{value:d,onValueChange:m,className:"w-full",children:[n==="pills"?e.jsx(He,{className:y("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:h.map(f=>{const b=f.icon;return e.jsxs(Ue,{value:f.id,className:y("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&b&&e.jsx(b,{className:"size-4"}),f.label]},f.id)})}):e.jsxs("div",{className:"relative mb-4 border-border",children:[e.jsx(He,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:h.map(f=>e.jsx(Ue,{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(He,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:h.map(f=>e.jsx(Ue,{value:f.id,ref:d===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(pe,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?e.jsx(ts,{todos:u}):e.jsx(es,{todos:u})}),e.jsx(pe,{value:"files",className:n==="pills"?"mt-0":"",children:e.jsx(ss,{})}),e.jsx(pe,{value:"database",className:n==="pills"?"mt-0":"",children:e.jsx("div",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})}),e.jsx(pe,{value:"sources",className:n==="pills"?"mt-0":"",children:e.jsx(ns,{})})]})})});Mi.displayName="ChatSecondaryPanel";const Ai=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex h-full flex-col",t),...n,children:s}));Ai.displayName="ChatSidebar.Root";const Ei=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("border-b border-border px-4 py-3",t),...n,children:s}));Ei.displayName="ChatSidebar.Header";const Pi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("flex-1 overflow-y-auto p-4",t),...n,children:s}));Pi.displayName="ChatSidebar.Content";const Di=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:y("border-t border-border px-4 py-3",t),...n,children:s}));Di.displayName="ChatSidebar.Footer";const Ui=l.forwardRef(({children:t,className:s,...n},o)=>{const[r,i]=l.useState(t),[a,c]=l.useState(!1),u=l.useRef(t),d=l.useRef(!0);return l.useEffect(()=>{if(d.current){d.current=!1,u.current=t;return}if(u.current===t)return;c(!0);const m=setTimeout(()=>{i(t),u.current=t,requestAnimationFrame(()=>{c(!1)})},150);return()=>{clearTimeout(m)}},[t]),e.jsx("span",{ref:o,className:y("text-sm text-foreground opacity-60 transition-opacity duration-300",a?"opacity-0":"opacity-60",s),...n,children:r})});Ui.displayName="ChatStatus";let Ns=!1,st=null;const rt=[];let nt=null;const Qe={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)},Ae=ue("gui-console");function Ge(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 zi(t){if(rt.push(t),t.level==="error"||t.level==="fatal"){Cs();return}nt||(nt=setTimeout(()=>{nt=null,Cs()},500))}async function Cs(){if(rt.length===0||!st)return;const t=rt.splice(0);try{await fetch(`${st}/logs/browser`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({logs:t})})}catch{}}function $i(t){Ns||(Ns=!0,st=t,console.log=(...s)=>{Qe.log(...s),Ae.info(Ge(s))},console.info=(...s)=>{Qe.info(...s),Ae.info(Ge(s))},console.warn=(...s)=>{Qe.warn(...s),Ae.warn(Ge(s))},console.error=(...s)=>{Qe.error(...s),Ae.error(Ge(s))},console.debug=(...s)=>{Qe.debug(...s),Ae.debug(Ge(s))},window.onerror=(s,n,o,r,i)=>(Ae.error(String(s),{source:n,line:o,col:r,stack:i?.stack}),!1),window.onunhandledrejection=s=>{const n=s.reason instanceof Error?`${s.reason.name}: ${s.reason.message}`:String(s.reason);Ae.error(`Unhandled rejection: ${n}`,{stack:s.reason?.stack})},No(s=>{s.service==="gui-console"&&zi(s)}),window.addEventListener("beforeunload",()=>{nt&&clearTimeout(nt),rt.length>0&&st&&navigator.sendBeacon(`${st}/logs/browser`,JSON.stringify({logs:rt}))}))}const Li=500;function Oi(t){const s=H(r=>r.isStreaming),n=l.useRef(null),o=l.useRef(0);l.useEffect(()=>{t&&!s&&(document.title=t)},[t,s]),l.useEffect(()=>{if(!t)return;const r=()=>{const i=".".repeat(o.current);document.title=`${t}${i}`,o.current=(o.current+1)%4};if(s)return o.current=0,r(),n.current=setInterval(r,Li),()=>{n.current&&(clearInterval(n.current),n.current=null),document.title=t}},[s,t])}const Se=ue("gui");function Fi({children:t}){const{setPanelSize:s,setActiveTab:n,panelSize:o,activeTab:r}=Me(),i=()=>{o!=="hidden"&&r==="files"?s("hidden"):(s("small"),n("files"))},a=()=>{o!=="hidden"&&r==="settings"?s("hidden"):(s("small"),n("settings"))};return e.jsx(e.Fragment,{children:t({openFiles:i,openSettings:a})})}function Bi({client:t,startSession:s,placeholder:n,commandMenuItems:o,onCancel:r,promptParameters:i}){const a=H(m=>m.input.attachedFiles),c=H(m=>m.addFileAttachment),u=H(m=>m.removeFileAttachment),d=m=>{for(const p of m)c(p)};return e.jsxs(Ln,{client:t,startSession:s,onCancel:r,children:[e.jsx(Kn,{commands:o}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border-b border-border",children:a.map((m,p)=>e.jsxs("div",{className:"relative group rounded-md overflow-hidden border border-border",children:[e.jsx("img",{src:`data:${m.mimeType};base64,${m.data}`,alt:m.name,className:"h-20 w-20 object-cover"}),e.jsx("button",{type:"button",onClick:()=>u(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(It,{className:"size-3"})})]},`attached-${m.name}-${m.data.slice(0,20)}`))}),e.jsx(On,{placeholder:n,autoFocus:!0,onFilesDropped:d}),e.jsxs(Hn,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Wn,{}),e.jsx(Vn,{onFilesSelected:d}),i&&i.length>0&&e.jsx(yi,{parameters:i})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(qn,{}),e.jsx(Bn,{}),e.jsx(Fn,{children:e.jsx(so,{className:"size-4"})})]})]})]})}function Hi({todos:t,sources:s,tools:n,mcps:o,subagents:r,sessionId:i,agentApiUrl:a,client:c}){const{activeTab:u,setActiveTab:d}=Me();return e.jsxs(Zt,{value:u,onValueChange:m=>d(m),className:"flex flex-col h-full",children:[e.jsx("div",{className:y("border-b border-border bg-card","px-4 py-2 h-16","flex items-center","sticky top-0 z-10 shrink-0"),children:e.jsx(fa,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(pe,{value:"todo",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ts,{todos:t})}),e.jsx(pe,{value:"files",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ss,{sessionId:i,agentApiUrl:a,client:c})}),e.jsx(pe,{value:"sources",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ns,{sources:s})}),e.jsx(pe,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(sa,{tools:n??[],mcps:o??[],subagents:r??[]})})]})}function Wi({agentName:t,showHeader:s,sessionId:n,debuggerUrl:o}){const{togglePanel:r,panelOpen:i}=Me(),a=o?n?`${o}/sessions/${n}`:o:null;return e.jsx(Un,{className:y("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(Wl,{}),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(oa,{}),o&&e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx(Re,{"aria-label":"View session in debugger",disabled:!a,asChild:!!a,children:a?e.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:e.jsx(ls,{className:"size-4 text-muted-foreground"})}):e.jsx(ls,{className:"size-4 text-muted-foreground"})})}),e.jsx(be,{children:e.jsx("p",{children:n?"View session in debugger":"Open debugger"})})]})}),e.jsx(Re,{"aria-label":"Toggle panel",onClick:r,"data-state":i?"open":"closed",children:e.jsx(to,{className:"size-4 text-muted-foreground"})})]})]})})}function Vi({client:t,initialSessionId:s,error:n,debuggerUrl:o}){const{connectionStatus:r,connect:i,sessionId:a,startSession:c}=ar(t,s),{messages:u,sendMessage:d,editAndResend:m,cancel:p}=gn(t,c);ir(t);const g=H(R=>R.error),[x,h]=l.useState(void 0),[f,b]=l.useState(void 0),[N,v]=l.useState(void 0),[C,U]=l.useState([]),[B,D]=l.useState([]),[I,_]=l.useState([]),[M,A]=l.useState([]),[K,Y]=l.useState("Type a message or / for commands..."),[z,W]=l.useState(!1),[V,T]=l.useState(null),k=H(sr);H(R=>R.latestContextSize);const{resolvedTheme:S,setTheme:P}=Xt(),j=l.useMemo(()=>{const R=new Map,E=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g,J=G=>G.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"");for(let G=0;G<u.length;G++){const Ie=u[G];if(!Ie?.content)continue;const ne=J(Ie.content);E.lastIndex=0;let le,oe=0;for(;(le=E.exec(ne))!==null;){const ve=le[1]??le[2];if(!ve)continue;const ze=R.get(ve)??[];ze.push({messageId:Ie.id,messageIndex:G,citationIndex:oe}),R.set(ve,ze),oe++}}return R},[u]),O=l.useMemo(()=>{const R=new Map;for(const E of u)if(E.sources)for(const J of E.sources)R.has(J.id)||R.set(J.id,{id:J.id,title:J.title,url:J.url,snippet:J.snippet||"",sourceName:J.sourceName||"",favicon:J.favicon||""});for(const[E,J]of j.entries()){const G=R.get(E);G&&(G.usedIn=J)}return Array.from(R.values())},[u,j]);Oi(x),l.useEffect(()=>{if(t){const R=t.getBaseUrl();R&&$i(R)}},[t]),l.useEffect(()=>{Se.debug("Connection status changed",{status:r}),r==="error"&&g&&Se.error("Connection error occurred",{error:g})},[r,g]),l.useEffect(()=>{if(t&&r==="connected"){const R=t.getCurrentSession();R?.metadata?.agentName&&h(R.metadata.agentName);const E=t.getAgentInfo();E.displayName?h(E.displayName):E.name&&h(E.name),b(E.description||"Start a conversation below to begin working with this agent."),E.suggestedPrompts&&E.suggestedPrompts.length>0?v(E.suggestedPrompts):v([]),E.tools&&E.tools.length>0&&(U(E.tools),Se.info("Agent tools loaded",{tools:E.tools})),E.mcps&&E.mcps.length>0&&(D(E.mcps),Se.info("Agent MCPs loaded",{mcps:E.mcps})),E.subagents&&E.subagents.length>0&&(_(E.subagents),Se.info("Agent subagents loaded",{subagents:E.subagents})),E.promptParameters&&E.promptParameters.length>0&&(A(E.promptParameters),Se.info("Agent prompt parameters loaded",{promptParameters:E.promptParameters})),E.uiConfig?.hideTopBar&&W(!0)}},[t,r]);const Q=R=>{Y(R)},$=()=>{Y("Type a message or / for commands...")};if(n)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:e.jsxs("div",{className:"text-center p-8 max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-destructive mb-4",children:"Initialization Error"}),e.jsx("p",{className:"text-foreground mb-4",children:n}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})});const X=[{id:"dark-mode",label:S==="dark"?"Light Mode":"Dark Mode",description:`Switch to ${S==="dark"?"light":"dark"} theme`,icon:S==="dark"?e.jsx(Zs,{className:"h-4 w-4"}):e.jsx(en,{className:"h-4 w-4"}),category:"action",onSelect:()=>{P(S==="dark"?"light":"dark"),Se.info("User toggled theme",{newTheme:S==="dark"?"light":"dark"})}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx(Ht,{className:"h-4 w-4"}),category:"action",onSelect:()=>{Se.info("User opened settings")}}];return e.jsxs(Nn,{defaultOpen:!1,children:[e.jsx(di,{client:t,currentSessionId:a}),e.jsx(Sn,{children:e.jsxs(Yn,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsxs(Qn,{children:[!z&&e.jsx(Wi,{agentName:x,showHeader:u.length>0,sessionId:a,...o&&{debuggerUrl:o}}),r==="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:i,className:"rounded-lg bg-destructive px-4 py-2 text-paragraph-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive-hover",children:"Retry"})]})}),e.jsxs(Gn,{children:[e.jsx(Xn,{children:u.length===0?x!==void 0?e.jsx(Fi,{children:({openFiles:R,openSettings:E})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Dn,{title:x,description:f??"",suggestedPrompts:N??[],onPromptClick:J=>{const G=H.getState().input.selectedPromptParameters;d(J,void 0,G&&Object.keys(G).length>0?G:void 0),Y("Type a message or / for commands..."),Se.info("Prompt clicked",{prompt:J})},onPromptHover:Q,onPromptLeave:$,onOpenFiles:R,onOpenSettings:E,toolsAndMcpsCount:C.length+B.length+I.length})})}):null:e.jsx("div",{className:"flex flex-col px-4 py-4",children:u.map((R,E)=>{const J=u.some(ne=>ne.isStreaming),G=R.role==="user"?u.slice(0,E+1).filter(ne=>ne.role==="user").length-1:-1,Ie=V!==null&&E>V;return e.jsx(ia,{message:R,className:y("group",Ie&&"opacity-50"),isLastMessage:E===u.length-1,children:e.jsx("div",{className:"flex flex-col w-full min-w-0",children:R.role==="user"?e.jsx(el,{message:R,messageIndex:G,isStreaming:J,onEditAndResend:m,sticky:!0,onEditingChange:ne=>{T(ne?E:null)}}):e.jsxs(e.Fragment,{children:[e.jsx(pa,{message:R,thinkingDisplayStyle:"collapsible"}),e.jsx(il,{message:R,isStreaming:R.isStreaming,onSendMessage:d,isLastAssistantMessage:E===u.findLastIndex(ne=>ne.role==="assistant"),onRedo:()=>{let ne=null,le=-1;for(let oe=E-1;oe>=0;oe--)if(u[oe]?.role==="user"){ne=u[oe],le=u.slice(0,oe+1).filter(ve=>ve.role==="user").length-1;break}if(ne?.content&&le>=0){const oe=ne.images?.map((ve,ze)=>({name:`image-${ze}`,path:"",size:0,mimeType:ve.mimeType,data:ve.data}));m(le,ne.content,oe)}}})]})})},R.id)})})}),e.jsx(Jn,{children:e.jsx(Bi,{client:t,startSession:c,placeholder:K,commandMenuItems:X,onCancel:p,promptParameters:M})})]})]}),e.jsx(Zn,{breakpoint:"md",children:e.jsx(Hi,{todos:k,sources:O,tools:C,mcps:B,subagents:I,sessionId:a,agentApiUrl:t?.getBaseUrl(),client:t})})]})})]})}const Ot=l.forwardRef(({sourceId:t,sources:s,className:n},o)=>{const r=s.find(u=>u.id===t);let i=null;try{i=Me()}catch{}const a=l.useCallback(u=>{u.preventDefault(),u.stopPropagation(),i&&(i.setPanelSize("small"),i.setActiveTab("sources")),r?.url&&window.open(r.url,"_blank","noopener,noreferrer")},[i,r?.url]);if(!r)return e.jsxs("span",{ref:o,className:y("inline-flex items-center px-1.5 py-0.5 text-xs font-medium","bg-muted text-muted-foreground rounded-md","cursor-default",n),children:["[",t,"]"]});const c=r.sourceName||qi(r.url);return e.jsx(ge,{delayDuration:200,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsxs("span",{ref:o,role:"button",tabIndex:0,onClick:a,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&a(u)},className:y("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",n),children:[r.favicon&&e.jsx("img",{src:r.favicon,alt:"",className:"size-3 rounded-sm",onError:u=>{u.target.style.display="none"}}),e.jsx("span",{children:c})]})}),e.jsx(be,{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:[r.favicon&&e.jsx("img",{src:r.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:r.title}),r.snippet&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3 mb-2",children:r.snippet}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(no,{className:"size-3"}),e.jsx("span",{children:"Click to open"})]})]})})]})})});Ot.displayName="CitationChip";function qi(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}const Ki=2e5;function as(t){const s=Math.max(t.totalEstimated,t.llmReportedInputTokens??0),n=t.modelContextWindow??Ki,o=s/n*100,r=`${o.toFixed(1)}%`,i=Math.min(100,Math.max(0,o)),c=(f=>f<50?"text-foreground":f<75?"text-yellow-500":"text-red-500")(o),u=f=>s===0?"0.0%":`${(f/s*100).toFixed(1)}%`,d=16,m=2,p=(d-m)/2,g=d/2,x=2*Math.PI*p,h=x-i/100*x;return{actualTokens:s,formattedPercentage:r,percentage:o,clampedPercentage:i,colorClass:c,calculatePercentage:u,size:d,strokeWidth:m,radius:p,center:g,circumference:x,offset:h}}function na({contextSize:t}){const{actualTokens:s,formattedPercentage:n,colorClass:o,calculatePercentage:r}=as(t);return e.jsx(be,{side:"top",align:"center",className:"p-3",children:e.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"System Prompt:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.systemPromptTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.systemPromptTokens),")"]})]})]}),t.toolOverheadTokens!==void 0&&t.toolOverheadTokens>0&&e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tools Definition:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.toolOverheadTokens),")"]})]})]}),t.mcpOverheadTokens!==void 0&&t.mcpOverheadTokens>0&&e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"MCPs Definition:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.mcpOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.mcpOverheadTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"User Messages:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.userMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.userMessagesTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Assistant Messages:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.assistantMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.assistantMessagesTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tool Inputs:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolInputTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.toolInputTokens),")"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tool Results:"}),e.jsxs("div",{className:"flex gap-1 items-baseline",children:[e.jsx("span",{children:t.toolResultsTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",r(t.toolResultsTokens),")"]})]})]})]}),e.jsx("div",{className:"border-t border-border pt-2",children:e.jsxs("div",{className:y("flex justify-end gap-2 font-semibold",o),children:[e.jsx("span",{children:s.toLocaleString()}),e.jsxs("span",{children:["(",n,")"]})]})})]})})}function aa({contextSize:t,className:s,size:n=12}){if(t==null)return null;const{colorClass:o,clampedPercentage:r}=as(t),i=2,a=(n-i)/2,c=n/2,u=2*Math.PI*a,d=u-r/100*u;return e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{className:y("inline-flex items-center justify-center rounded-full cursor-default",o,s),role:"img","aria-label":"Context usage indicator",children:e.jsxs("svg",{width:n,height:n,viewBox:`0 0 ${n} ${n}`,className:"transform -rotate-90",children:[e.jsx("title",{children:"Context usage indicator"}),e.jsx("circle",{cx:c,cy:c,r:a,stroke:"currentColor",strokeWidth:i,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:c,cy:c,r:a,stroke:"currentColor",strokeWidth:i,fill:"transparent",strokeDasharray:u,strokeDashoffset:d,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(na,{contextSize:t})]})})}const oa=l.forwardRef(({className:t,contextSize:s,...n},o)=>{const r=H(x=>x.latestContextSize),i=s??r;if(i==null)return null;const{colorClass:a,size:c,center:u,radius:d,strokeWidth:m,circumference:p,offset:g}=as(i);return e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx(re,{ref:o,type:"button",variant:"ghost",size:"icon",className:y("rounded-full cursor-default",a,t),...n,children:e.jsxs("svg",{width:c,height:c,viewBox:`0 0 ${c} ${c}`,className:"transform -rotate-90",children:[e.jsx("title",{children:"Context usage indicator"}),e.jsx("circle",{cx:u,cy:u,r:d,stroke:"currentColor",strokeWidth:m,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:u,cy:u,r:d,stroke:"currentColor",strokeWidth:m,fill:"transparent",strokeDasharray:p,strokeDashoffset:g,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(na,{contextSize:i})]})})});oa.displayName="ContextUsageButton";const Yi=l.forwardRef(({autoScroll:t=!0,isStreaming:s=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:r=!0,scrollButton:i,className:a,children:c,...u},d)=>{const m=l.useRef(null),[p,g]=l.useState(!0),[x,h]=l.useState(!1),f=l.useRef(0);l.useImperativeHandle(d,()=>{if(!m.current)throw new Error("Container ref not initialized");return m.current});const b=l.useCallback(()=>{const v=m.current;if(!v)return;const{scrollTop:C,scrollHeight:U,clientHeight:B}=v,I=U-C-B<o;g(I),h(!I&&r),f.current=C},[o,r]),N=l.useCallback((v=n)=>{const C=m.current;C&&C.scrollTo({top:C.scrollHeight,behavior:v})},[n]);return l.useEffect(()=>{!t||!m.current||(s&&p?N("auto"):!s&&p&&N())},[t,s,p,N]),l.useEffect(()=>{const v=m.current;if(!v)return;const C=()=>{b()};return v.addEventListener("scroll",C,{passive:!0}),b(),()=>{v.removeEventListener("scroll",C)}},[b]),l.useEffect(()=>{const v=m.current;if(!v)return;const C=new ResizeObserver(()=>{p&&t&&N("auto")});return C.observe(v),()=>{C.disconnect()}},[p,t,N]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx("div",{ref:m,className:y("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",a),...u,children:e.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:c})}),x&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||e.jsxs("button",{type:"button",onClick:()=>N(),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"]})})]})});Yi.displayName="Conversation";const Qi=Hs,ra=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{ref:n,className:y("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s}));ra.displayName=Nt.displayName;const Gi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Qi,{children:[e.jsx(ra,{}),e.jsxs(Ct,{ref:o,className:y("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[s,e.jsxs(Ws,{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(It,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Gi.displayName=Ct.displayName;const Xi=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:y("text-subheading font-semibold leading-none tracking-tight",t),...s}));Xi.displayName=St.displayName;const Ji=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:y("text-paragraph-sm text-muted-foreground",t),...s}));Ji.displayName=kt.displayName;function Zi({message:t,messageIndex:s,isStreaming:n,onEditAndResend:o,sticky:r=!1,onEditingChange:i}){const[a,c]=l.useState(!1),[u,d]=l.useState(!1),m=l.useRef(null),p=l.useRef(null);l.useEffect(()=>{i?.(a)},[a,i]);const g=l.useCallback(()=>{if(!r||!m.current)return;let v=m.current.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(v){m.current.getBoundingClientRect(),v.getBoundingClientRect();const C=m.current.offsetTop;v.scrollTo({top:C-16,behavior:"smooth"})}},[r]),x=l.useCallback(async()=>{if(!t.content){me.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),d(!0),me.success("Copied to clipboard!"),setTimeout(()=>{d(!1)},2e3)}catch{me.error("Failed to copy to clipboard")}},[t.content]),h=l.useCallback(()=>{c(!0)},[]);l.useEffect(()=>{if(a&&p.current){p.current.focus();const v=document.createRange(),C=window.getSelection();v.selectNodeContents(p.current),v.collapse(!1),C?.removeAllRanges(),C?.addRange(v)}},[a]);const f=l.useCallback(()=>{c(!1),p.current&&(p.current.textContent=t.content||"")},[t.content]),b=l.useCallback(()=>{const v=p.current?.textContent||"";if(!v.trim())return;const C=t.images?.map((U,B)=>({name:`image-${B}`,path:"",size:0,mimeType:U.mimeType,data:U.data}));o(s,v.trim(),C),c(!1)},[s,t.images,o]),N=l.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),b()),v.key==="Escape"&&(v.preventDefault(),f())},[b,f]);return e.jsxs("div",{ref:m,className:"w-full group/user-message",children:[e.jsx("div",{className:y("w-full rounded-2xl bg-secondary px-4 py-4 transition-colors",r&&"sticky top-0 z-10 bg-secondary cursor-pointer",a&&"ring-2 ring-primary/20 focus-within:ring-primary/40 transition-all bg-transparent"),onClick:r&&!a?g:void 0,onKeyDown:r&&!a?v=>{(v.key==="Enter"||v.key===" ")&&g()}:void 0,role:r&&!a?"button":void 0,tabIndex:r&&!a?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,C)=>e.jsx("img",{src:`data:${v.mimeType};base64,${v.data}`,alt:`Attachment ${C+1}`,className:y("max-w-[200px] max-h-[200px] rounded-lg object-cover",a&&"opacity-50")},`image-${v.mimeType}-${v.data.slice(0,20)}`))}),t.content&&e.jsx("div",{ref:p,role:"textbox",tabIndex:a?0:-1,contentEditable:a,onKeyDown:a?N:void 0,suppressContentEditableWarning:!0,className:y("whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-foreground leading-relaxed outline-none",a&&"cursor-text",!a&&"cursor-default"),children:t.content})]})}),!n&&t.content&&e.jsx(Gt,{className:y("mt-2 transition-opacity justify-end",a?"opacity-100":"opacity-0 group-hover/user-message:opacity-100"),children:a?e.jsxs(e.Fragment,{children:[e.jsx(re,{variant:"ghost",size:"sm",onClick:f,className:"h-7 px-2 text-xs text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsx(re,{size:"sm",onClick:b,className:"h-7 px-3 text-xs",children:"Send"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{onClick:x,tooltip:u?"Copied!":"Copy",children:u?e.jsx(lt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),e.jsx(Ve,{onClick:h,tooltip:"Edit",children:e.jsx(ao,{className:"size-4"})})]})})]})}const el=l.memo(Zi,(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 tl(t,s,n,o,r){const i=n==="triggered",a=o==="no_action_needed";return t==="context_size"?i?{icon:ce,title:"Compacting Context..."}:{icon:ce,title:a?"Context Check":"Context Compacted"}:t==="tool_response"?s==="mid_turn_compaction"||r===!0?i?{icon:ce,title:"Compacting Context..."}:{icon:ce,title:a?"Context Check":"Context Compacted"}:i?{icon:ce,title:"Compacting Response..."}:{icon:ce,title:a?"Response Check":"Tool Response Compacted"}:{icon:ce,title:i?"Running Hook...":"Hook Executed"}}function Ee(t){return t.toLocaleString()}function sl(t){if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return s>0?`${s}h ${n}m ${o}s`:`${n}m ${o}s`}function Pt({notification:t}){const[s,n]=l.useState(!1),[o,r]=l.useState(0),{icon:i,title:a}=tl(t.hookType,t.callback,t.status,t.metadata?.action,t.metadata?.midTurn),c=t.status==="triggered",u=t.status==="completed",d=t.status==="error";l.useEffect(()=>{if(!c||!t.triggeredAt)return;const x=()=>{const f=(Date.now()-t.triggeredAt)/1e3;r(f)};x();const h=setInterval(x,100);return()=>clearInterval(h)},[c,t.triggeredAt]);const m=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(u&&t.metadata?.tokensSaved!==void 0){const{tokensSaved:x,originalTokens:h,messagesRemoved:f}=t.metadata;if(m)p=`${f!==void 0?`${Ee(f)} messages summarized, `:""}${Ee(x??0)} tokens saved`;else if(h!==void 0&&h>0)p=`${((x??0)/h*100).toFixed(0)}% reduced`;else if(t.currentPercentage!==void 0&&t.currentPercentage>0){const N=t.currentPercentage/100*2e5;p=`${((x??0)/N*100).toFixed(1)}% context freed`}else p=`${Ee(x)} tokens saved`}else d&&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:()=>n(!s),"aria-expanded":s,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("div",{className:d?"text-destructive":"text-muted-foreground",children:e.jsx(i,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:a}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Vt,{className:"h-3 w-3 text-muted-foreground animate-spin"}),e.jsxs("span",{className:"text-muted-foreground/70 tabular-nums",children:[o.toFixed(1),"s"]})]}),u&&e.jsx(Rt,{className:"h-3 w-3 text-green-500"}),d&&e.jsx(wt,{className:"h-3 w-3 text-destructive"}),!c&&e.jsx(fe,{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 ${d?"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:Ee(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:Ee(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:[Ee(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:[Ee(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(oo,{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:"," ",sl((t.completedAt-t.triggeredAt)/1e3)]})]})]})})]})]})}const nl=l.forwardRef(({className:t,...s},n)=>e.jsx(Vs,{ref:n,className:y("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));nl.displayName=Vs.displayName;function Dt({content:t,className:s}){if(!t)return null;const n={table:({node:o,...r})=>e.jsx("div",{className:"overflow-x-auto my-4",children:e.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...r})}),thead:({node:o,...r})=>e.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:o,...r})=>e.jsx("tbody",{...r}),tr:({node:o,...r})=>e.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:o,...r})=>e.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...r}),td:({node:o,...r})=>e.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:o,checked:r,...i})=>i.type==="checkbox"?e.jsx("input",{type:"checkbox",checked:r||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...i}):e.jsx("input",{...i}),code:({node:o,...r})=>r.className?.includes("language-")?e.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-code text-foreground",...r}):e.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code text-foreground",...r}),pre:({node:o,...r})=>e.jsx("pre",{className:"my-4",...r}),h1:({node:o,...r})=>e.jsx("h1",{className:"text-heading-3 mt-6 mb-4 text-foreground",...r}),h2:({node:o,...r})=>e.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground",...r}),h3:({node:o,...r})=>e.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...r}),ul:({node:o,...r})=>{const i=o?.children?.some(a=>typeof a=="object"&&a!==null&&"type"in a&&a.type==="element"&&"tagName"in a&&a.tagName==="li"&&"children"in a&&Array.isArray(a.children)&&a.children.some(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:y("my-2 space-y-1 text-foreground",i?"list-none space-y-2":"list-disc list-inside"),...r})},ol:({node:o,...r})=>e.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...r}),li:({node:o,...r})=>{const i=o?.children?.some(a=>typeof a=="object"&&a!==null&&"type"in a&&a.type==="element"&&"tagName"in a&&a.tagName==="input"&&"properties"in a&&typeof a.properties=="object"&&a.properties!==null&&"type"in a.properties&&a.properties.type==="checkbox");return e.jsx("li",{className:y("flex items-start",i?"gap-2":"ml-2"),...r})},a:({node:o,...r})=>e.jsx("a",{className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:o,...r})=>e.jsx("p",{className:"my-2 text-foreground leading-relaxed",...r}),blockquote:({node:o,...r})=>e.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2",...r})};return e.jsx("div",{className:y("markdown-content prose prose-sm max-w-none dark:prose-invert",s),children:e.jsx(ya,{remarkPlugins:[on],components:n,children:t})})}const al=Te("flex min-w-0 animate-fadeIn",{variants:{role:{user:"max-w-[80%] self-end ml-auto",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"}}),ia=l.forwardRef(({message:t,role:s,layout:n,className:o,children:r,messageId:i,autoScroll:a,isLastMessage:c=!1,...u},d)=>{const m=t?t.role:s||"assistant",p=t?t.id:i,g=l.useRef(null),[x,h]=l.useState(void 0);return l.useImperativeHandle(d,()=>g.current),l.useEffect(()=>{if(!c||m!=="assistant"){h(void 0);return}const f=()=>{const N=g.current;if(!N)return;let v=N.parentElement;for(;v&&!v.classList.contains("overflow-y-auto");)v=v.parentElement;if(!v)return;const C=N.previousElementSibling;if(!C||C.getAttribute("aria-label")!=="user message"){h(void 0);return}const U=v.clientHeight,B=C.offsetHeight,I=Math.max(0,U-B-32);h(I)};f();const b=new ResizeObserver(f);if(g.current){b.observe(g.current);let N=g.current.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;N&&b.observe(N)}return()=>b.disconnect()},[c,m]),l.useEffect(()=>{if((a!==void 0?a:m==="user")&&g.current){const b=setTimeout(()=>{g.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(b)}},[m,a]),e.jsx("article",{ref:g,id:p?`message-${p}`:void 0,"aria-label":`${m} message`,"data-message-id":p,className:y(al({role:m,layout:n}),o),style:{minHeight:x!==void 0?`${x}px`:void 0},...u,children:r})});ia.displayName="Message";const ol=[{id:"pdf",label:"PDF",icon:We},{id:"excel",label:"Excel",icon:cs},{id:"csv",label:"CSV",icon:cs},{id:"text",label:"Text",icon:io},{id:"markdown",label:"Markdown",icon:We}];function rl({message:t,isStreaming:s,onRedo:n,onSendMessage:o,isLastAssistantMessage:r=!1}){const[i,a]=l.useState(!1);if(s||t.role!=="assistant"||!t.content)return null;const c=r?"":"opacity-0 group-hover:opacity-100 transition-opacity",u=async()=>{if(!t.content){me.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),a(!0),me.success("Copied to clipboard!"),setTimeout(()=>{a(!1)},2e3)}catch{me.error("Failed to copy to clipboard")}},d=()=>{n?n():me.info("Regenerate not available")},m=p=>{o?o(`produce an artifact as ${p} for this session`):me.info("Export not available")};return e.jsxs(Gt,{className:y(c),children:[e.jsx(Ve,{onClick:u,tooltip:i?"Copied!":"Copy",children:i?e.jsx(lt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),e.jsx(Ve,{onClick:d,tooltip:"Redo",children:e.jsx(ro,{className:"size-4"})}),e.jsxs(ut,{children:[e.jsx(ge,{children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx(mt,{asChild:!0,children:e.jsxs(re,{className:y("relative size-7 p-1.5 text-muted-foreground hover:text-foreground"),size:"sm",type:"button",variant:"ghost",children:[e.jsx(an,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Export"})]})})}),e.jsx(be,{children:e.jsx("p",{children:"Export"})})]})}),e.jsx(qe,{align:"start",children:ol.map(p=>e.jsxs(je,{onClick:()=>m(p.label),children:[e.jsx(p.icon,{className:"size-4 mr-2"}),p.label]},p.id))})]})]})}const il=l.memo(rl,(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)),ll={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 cl(t,s){if(!s||!t.rawInput)return null;const n=t.rawInput[s];return typeof n=="string"?n:null}function dl(t,s){let n=t;for(const[o,r]of Object.entries(s))n=n.replace(`{${o}}`,r);return n}function ul(t,s){return t.length<=s?t:`${t.substring(0,s-1)}…`}function jt(t,s){const n=t.verbiage||ll[t.title];if(!n){const r=t.prettyName||t.title;return s==="active"?`Using ${r}`:`Used ${r}`}const o=s==="active"?n.active:n.past;if(n.paramKey){const r=cl(t,n.paramKey);if(r){const i=ul(r,50);let a="value";return n.paramKey.includes("file")||n.paramKey.includes("path")?a="file":n.paramKey.includes("query")||n.paramKey.includes("pattern")?a="query":n.paramKey.includes("command")?a="command":n.paramKey.includes("directory")&&(a="directory"),dl(o,{[a]:i})}}if(t.subline){const r=o.split("{")[0];return r?`${r.trim()} ${t.subline}`:t.subline}return o.replace(/\s*\{[^}]+\}/g,"")}function ml(t){return t.prettyName||t.title}function De(t){return t.status==="pending"&&(!t.rawInput||Object.keys(t.rawInput).length===0)}function gt(t){return t.status==="failed"||t.error?"failed":!!(t.subagentMessages&&t.subagentMessages.length>0)&&t.subagentCompleted||t.status==="completed"?"completed":De(t)?"selecting":(t.status==="pending"||t.status==="in_progress","executing")}function la(t){switch(gt(t)){case"selecting":return`Selecting ${t.prettyName||t.title}`;case"executing":return jt(t,"active");case"completed":return jt(t,"past");case"failed":return`Failed to use ${t.prettyName||t.title}`;default:return t.prettyName||t.title}}function pl(t){return t.every(s=>gt(s)==="completed")}function fl(t){return t.some(s=>gt(s)==="failed")}function gl(t){return fl(t)?"failed":pl(t)?"completed":t.every(s=>De(s))?"selecting":"executing"}const Ss=Te("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"}}),hl=Te("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),ca=l.forwardRef(({content:t,isStreaming:s=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:r=!1,autoCollapse:i=!0,autoCollapseDelay:a=2e3,label:c="Thinking",variant:u,className:d},m)=>{const[p,g]=l.useState(n==="inline"?!0:o),[x,h]=l.useState(!1);return l.useEffect(()=>{if(i&&!s&&t&&n==="collapsible"){const f=setTimeout(()=>{h(!0),g(!1)},a);return()=>clearTimeout(f)}},[s,t,i,a,n]),l.useEffect(()=>{r&&s&&n==="collapsible"&&!x&&g(!0)},[r,s,n,x]),!t&&!s?null:n==="inline"?e.jsxs("div",{ref:m,className:y(Ss({variant:u}),"p-3",d),children:[e.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[e.jsx("span",{className:"text-caption font-medium text-foreground opacity-60 uppercase tracking-wide",children: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:m,className:y("mb-3",d),children:[e.jsxs("button",{type:"button",onClick:()=>{g(!p),h(!1)},className:"w-full flex items-center justify-between p-2.5 rounded-lg bg-card border border-border hover:bg-card/80 hover:shadow-sm transition-all text-left","aria-expanded":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(fe,{className:hl({expanded:p}),"aria-hidden":"true"})]}),p&&e.jsx("div",{className:y(Ss({variant:u}),"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:"..."})]})})]})});ca.displayName="Reasoning";function xl(){return t=>{Ta(t,"text",(s,n,o)=>{if(!o||n===void 0)return;const r=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g,i=s.value;if(!r.test(i))return;r.lastIndex=0;const a=[];let c=0,u;for(;(u=r.exec(i))!==null;){u.index>c&&a.push({type:"text",value:i.slice(c,u.index)});const d=u[1]??u[2]??"";a.push({type:"citation",data:{hName:"span",hProperties:{"data-citation-id":d,className:"citation-marker"}},sourceId:d}),c=u.index+u[0].length}c<i.length&&a.push({type:"text",value:i.slice(c)}),a.length>0&&o.children.splice(n,1,...a)})}}const Ut=ue("Response","debug");function bl(t){const s=/[",\n\r]/.test(t),n=t.replaceAll('"','""');return s?`"${n}"`:n}function ks(t){return Array.from(t.querySelectorAll("tr")).map(n=>Array.from(n.querySelectorAll("th,td")).map(r=>bl((r.textContent||"").trim())).join(",")).join(`
9
+ `)}function yl(t,s,n){const o=new Blob([s],{type:n}),r=URL.createObjectURL(o),i=document.createElement("a");i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}function vl(t){const{className:s,...n}=t,o=l.useRef(null),[r,i]=l.useState(!1),a=l.useCallback(async()=>{const u=o.current;if(u)try{const d=ks(u);await navigator.clipboard.writeText(d),i(!0),me.success("Copied table as CSV"),setTimeout(()=>i(!1),1500)}catch{me.error("Failed to copy table")}},[]),c=l.useCallback(()=>{const u=o.current;if(!u)return;const d=ks(u);yl("table.csv",d,"text/csv;charset=utf-8"),me.success("Downloaded table.csv")},[]);return e.jsxs("div",{className:"group/table",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{ref:o,className:y("min-w-full border-collapse border border-border rounded-md",s),...n})}),e.jsxs(Gt,{className:y("mt-2 flex justify-end","opacity-0 group-hover/table:opacity-100 transition-opacity","pointer-events-none group-hover/table:pointer-events-auto"),children:[e.jsx(Ve,{onClick:a,tooltip:r?"Copied!":"Copy",children:r?e.jsx(lt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),e.jsx(Ve,{onClick:c,tooltip:"Download CSV",children:e.jsx(an,{className:"size-4"})})]})]})}const Fe=l.memo(l.forwardRef(({content:t,isStreaming:s=!1,showEmpty:n=!0,emptyMessage:o="",sources:r=[],messageId:i,citationIndexOffset:a=0,className:c,...u},d)=>{const[m,p]=l.useState(0);Ut.info("Response render",{contentLength:t.length,contentPreview:t.slice(0,100),sourcesCount:r.length,sourceIds:r.map(h=>h.id),remountKey:m}),l.useEffect(()=>{p(h=>(Ut.info("Sources changed, incrementing remountKey",{sourcesCount:r.length,sourceIds:r.map(f=>f.id),oldRemountKey:h}),h+1))},[r]);const g=l.useMemo(()=>[on,xl],[]),x=l.useMemo(()=>{const h={current:0};return{table:f=>e.jsx(vl,{...f}),thead:f=>e.jsx("thead",{className:y("bg-card border-b border-border",f.className),...f}),tr:f=>e.jsx("tr",{className:y("border-b border-border hover:bg-card transition-colors",f.className),...f}),th:f=>e.jsx("th",{className:y("px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",f.className),...f}),td:f=>e.jsx("td",{className:y("px-4 py-2 text-foreground border-r border-border last:border-r-0",f.className),...f}),span:f=>{const{className:b,class:N,"data-citation-id":v,children:C,...U}=f,B=b||N;if(B==="citation-marker"&&v){const D=a+h.current++;return Ut.info("Rendering citation marker",{citationId:v,sourcesAvailable:r.length,sourceIds:r.map(I=>I.id),foundSource:r.find(I=>I.id===v)?"yes":"no"}),i?e.jsx("span",{id:`citation-${i}-${D}`,"data-citation-source-id":v,"data-citation-anchor":"true",className:"inline-flex rounded-md",children:e.jsx(Ot,{sourceId:v,sources:r})}):e.jsx(Ot,{sourceId:v,sources:r})}return e.jsx("span",{className:B,...U,children:C})}}},[r,i,a]);return!t&&s&&n?e.jsx("div",{ref:d,className:y("opacity-70 italic text-paragraph-sm",c),...u,children:o}):t?e.jsx("div",{ref:d,...u,children:e.jsx(Ia,{className:y("size-full","[&>*:first-child]:mt-0 [&>*:last-child]:mb-0","[&_code]:whitespace-pre-wrap [&_code]:break-words","[&_pre]:max-w-full [&_pre]:overflow-x-auto",c),remarkPlugins:g,components:x,children:t},`streamdown-${m}`)}):null}),(t,s)=>t.content===s.content&&t.sources===s.sources);Fe.displayName="Response";function wl(t){if(!t.rawInput)return null;const s=["query","search_term","pattern","target_file","file_path","command","target_directory"];for(const n of s){const o=t.rawInput[n];if(typeof o=="string"&&o.trim())return o.trim()}return t.subline?t.subline:null}function Ft(t,s=3){if(t.length===0)return"";if(t.length===1)return t[0];if(t.length<=s)return`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`;const n=t.slice(0,s),o=t.length-s;return`${n.join(", ")} and ${o} more`}function jl(t){if(t.length===0)return null;const s=t[0],n=s.lastIndexOf("/");if(n===-1)return null;const o=s.substring(0,n);return t.every(i=>i.startsWith(`${o}/`))?o:null}function Nl(t,s){if(t.length===0)return"";if(t.length===1)return jt(t[0],s);const n=t[0],o=n.title,r=t.map(wl).filter(d=>d!==null);if((o==="Read"||o==="Write"||o==="read_file"||o==="write"||o==="search_replace"||o==="delete_file")&&r.length>0){const d=jl(r);if(d){const p=s==="active"?"working on":"worked on";return`${p.charAt(0).toUpperCase()+p.slice(1)} ${r.length} files in ${d}`}return`${o==="Read"||o==="read_file"?s==="active"?"Reading":"Read":o==="Write"||o==="write"?s==="active"?"Writing":"Wrote":o==="search_replace"?s==="active"?"Editing":"Edited":s==="active"?"Deleting":"Deleted"} ${Ft(r)}`}if((o==="WebSearch"||o==="Grep"||o==="web_search"||o==="codebase_search"||o==="grep")&&r.length>0)return`${o==="WebSearch"||o==="web_search"?s==="active"?"Searching the web for":"Searched the web for":o==="codebase_search"?s==="active"?"Searching codebase for":"Searched codebase for":s==="active"?"Searching for":"Searched for"} ${Ft(r)}`;const c=ml(n);return`${s==="active"?"Using":"Used"} ${c} ${t.length} times`}function Cl(t,s){if(t.length===0)return"";if(t.length===1)return jt(t[0],s);if([...new Set(t.map(i=>i.title))].length===1)return Nl(t,s);const o=t.map(i=>i.prettyName||i.title).filter((i,a,c)=>c.indexOf(i)===a);return`${s==="active"?"Running":"Ran"} ${Ft(o)}`}const Sl=50;function da({parentStatus:t,agentName:s,query:n,isExpanded:o,onExpandChange:r,storedMessages:i}){const[a,c]=l.useState(!1),u=o??a,[d,m]=l.useState(!0),[p,g]=l.useState(!0),x=l.useRef(null),h=i||[],f=t==="in_progress"||t==="pending",b=h[h.length-1],N=b&&(b.content||b.toolCalls&&b.toolCalls.length>0||b.contentBlocks&&b.contentBlocks.length>0),v=l.useRef(f);l.useEffect(()=>{v.current&&!f&&m(!1),v.current=f},[f]);const C=l.useCallback(()=>{const _=x.current;if(!_)return;const{scrollTop:M,scrollHeight:A,clientHeight:K}=_,Y=A-M-K;g(Y<Sl)},[]),U=l.useCallback(()=>{const _=x.current;_&&(_.scrollTop=_.scrollHeight)},[]);l.useEffect(()=>{p&&(f||N)&&U()},[p,f,N,U]),l.useEffect(()=>{const _=x.current;if(!_)return;const M=()=>C();return _.addEventListener("scroll",M,{passive:!0}),C(),()=>_.removeEventListener("scroll",M)},[C]),l.useEffect(()=>{d&&(g(!0),requestAnimationFrame(()=>{U()}))},[d,U]);const B=b?.content&&b.content.split(`
10
10
  `).filter(Boolean).pop()||"",D=B.length>100?`${B.slice(0,100)}...`:B,I=n?(n.split(`
11
- `)[0]??"").slice(0,100)+(n.length>100?"...":""):"";return e.jsxs("div",{children:[!u&&e.jsx("div",{className:"w-full max-w-md",children:b?._meta?.currentActivity?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:b._meta.currentActivity}):b?._meta?.statusGenerating?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate animate-pulse",children:"Determining status..."}):D?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:D}):I?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate",children:I}):null}),u&&e.jsxs("div",{className:"space-y-3",children:[(s||n)&&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:i?.[0]?._meta?.semanticName?"Task: ":"agentName: "}),i?.[0]?._meta?.semanticName?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-foreground font-medium",children:i[0]._meta.semanticName}),e.jsxs("span",{className:"text-muted-foreground text-[10px] ml-1",children:["(",s,")"]})]}):e.jsx("span",{className:"text-foreground",children:s})]}),n&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"query: "}),e.jsx("span",{className:"text-foreground",children:n})]})]})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>m(!d),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(fe,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${d?"rotate-180":""}`})]}),d&&e.jsxs("div",{ref:x,className:"mt-2 rounded-md overflow-hidden bg-muted/30 border border-border/50 max-h-[200px] overflow-y-auto",children:[!N&&f&&e.jsx("div",{className:"px-2 py-2 text-[11px] text-muted-foreground",children:"Waiting for sub-agent response..."}),b&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[b.contentBlocks&&b.contentBlocks.length>0?b.contentBlocks.map((_,M)=>_.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(Dt,{content:_.text})},`text-${_.text.slice(0,30)}-${M}`):e.jsx(kl,{toolCall:_.toolCall},_.toolCall.id)):b.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(Dt,{content:b.content})}),b.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!f&&b?.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(Dt,{content:b.content})})]})]})]})}function kl({toolCall:t}){const s={pending:"...",in_progress:"",completed:"",failed:""}[t.status],n={pending:"text-muted-foreground",in_progress:"text-blue-500",completed:"text-green-500",failed:"text-destructive"}[t.status];return e.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:n,children:s}),e.jsx("span",{className:"font-medium",children:t.prettyName||t.title}),t.status==="in_progress"&&e.jsx(Vt,{className:"h-2.5 w-2.5 animate-spin"})]})}function Tl({todos:t,className:s}){if(!t||t.length===0)return null;const n=l.useMemo(()=>{const r=t.find(a=>a.status==="in_progress");if(r)return r;const i=t.find(a=>a.status==="completed");return i||t[0]},[t]);if(!n)return null;const o=n.status==="in_progress"&&n.activeForm||n.content;return e.jsxs("span",{className:y("flex items-center gap-1.5",s),children:[n.status==="completed"?e.jsx(Rt,{className:"size-3 text-muted-foreground shrink-0"}):n.status==="pending"?e.jsx(Tt,{className:"size-3 text-foreground shrink-0"}):null,e.jsx("span",{className:"truncate",children:o})]})}const Ts={Globe:tn,Image:go,Link:fo,Cloud:po,CheckSquare:_t,Search:mo,FileText:We,Edit:uo,Wrench:co,BrainCircuit:lo,CircleDot:qt};function Il(t,s){const[n,o]=l.useState(0),r=l.useRef(null);return l.useEffect(()=>{if(!s||!t){o(0);return}const i=()=>{o((Date.now()-t)/1e3)};return i(),r.current=setInterval(i,100),()=>{r.current&&clearInterval(r.current)}},[t,s]),n}function ua(t){if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return s>0?`${s}h ${n}m ${o}s`:`${n}m ${o}s`}function Be({startTime:t,isRunning:s=!0}){const n=Il(t,s);return e.jsx("span",{className:"text-xs text-text-secondary/70 tabular-nums ml-1",children:ua(n)})}function Rl({compactionAction:t,originalTokens:s,finalTokens:n,originalContentPath:o}){const r=s&&n?s-n:void 0,i=s&&n?Math.round((1-n/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(ce,{className:"w-3.5 h-3.5 text-text-secondary"}):e.jsx(at,{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"]})]}),n!==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:[n.toLocaleString()," tokens"]})]}),r!==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:[r.toLocaleString()," tokens"]})]}),i!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] text-text-secondary uppercase tracking-wide font-sans mb-0.5",children:"Reduction"}),e.jsxs("div",{className:"text-[12px] font-medium text-foreground font-sans",children:[i,"%"]})]})]}),o&&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:o})]})]})}function Pe({toolCalls:t,isGrouped:s=!1,autoMinimize:n=!0,hookNotifications:o=[]}){const[r,i]=l.useState(!1),[a,c]=l.useState(!1),[u,d]=l.useState(!1),m=t.length===1?t[0]:null,p=m?.title==="todo_write",g=m?o.find(T=>T.toolCallId===m.id):void 0,x=!!(g?.status==="completed"&&g.metadata?.action&&g.metadata.action!=="no_action_needed"&&g.metadata.action!=="none"||m?._meta?.compactionAction),h=g?.metadata?.action==="truncated"||g?.metadata?.action==="compacted_then_truncated"||m?._meta?.compactionAction==="truncated",f=s?t.some(T=>T._meta?.compactionAction||o.some(k=>k.toolCallId===T.id&&k.status==="completed"&&k.metadata?.action&&k.metadata.action!=="no_action_needed"&&k.metadata.action!=="none")):!1,b=s?t.some(T=>T._meta?.compactionAction==="truncated"||o.some(k=>k.toolCallId===T.id&&(k.metadata?.action==="truncated"||k.metadata?.action==="compacted_then_truncated"))):!1,N=!!(m?.subagentMessages&&m.subagentMessages.length>0),C=et.useMemo(()=>{if(!m?.subagentMessages)return null;const T=m.subagentMessages;for(let k=T.length-1;k>=0;k--){const S=T[k],P=S?._meta?.context_size??S?.context_size;if(P!=null)return P}return null},[m?.subagentMessages]),[U,B]=l.useState(!1),D=et.useContext(Jt),I=s?gl(t):m?gt(m):"executing",_=I==="completed",M=I==="failed",E=I==="selecting";l.useEffect(()=>{if(n&&_&&!a&&!u){const T=setTimeout(()=>{c(!0),i(!1)},500);return()=>clearTimeout(T)}},[n,_,a,u]);const K=et.useCallback(()=>{p&&D&&m?D.panelSize!=="hidden"&&D.activeTab==="todo"?D.setPanelSize("hidden"):(D.setPanelSize("small"),D.setActiveTab("todo")):N?(d(!0),B(!U)):(d(!0),i(!r),a&&c(!1))},[p,D,r,a,m,N,U]),z=s?ds:m?.icon&&Ts[m.icon]?Ts[m.icon]:qt,V=s?Cl(t,_?"past":"active"):m?la(m):"Tool operation";if(E&&!s)return e.jsx("div",{className:"flex flex-col 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(z,{className:"h-3 w-3"})}),e.jsxs("span",{className:"text-paragraph-xs text-text-muted",children:[V,m?.startedAt&&e.jsx(Be,{startTime:m.startedAt,isRunning:!m.subagentCompleted})]})]})});if(E&&s){const T=(()=>{const S=t.map(P=>P.startedAt).filter(P=>P!=null);return S.length===0?null:Math.min(...S)})(),k=t.every(S=>S.subagentCompleted);return e.jsxs("div",{className:"flex flex-col 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(ds,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Selecting tools"}),T&&e.jsx(Be,{startTime:T,isRunning:!k}),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:V})]})}return e.jsxs("div",{className:"flex flex-col",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:K,"aria-expanded":p?void 0:r,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(z,{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&&V]}),N&&e.jsx(aa,{contextSize:C,size:12,className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors"}),!s&&m?.startedAt&&I==="executing"&&e.jsx(Be,{startTime:m.startedAt,isRunning:!m.subagentCompleted}),s&&I==="executing"&&(()=>{const T=t.map(P=>P.startedAt).filter(P=>P!=null);if(T.length===0)return null;const k=Math.min(...T),S=t.every(P=>P.status==="completed"&&(!P.subagentMessages||P.subagentCompleted));return e.jsx(Be,{startTime:k,isRunning:!S})})(),s&&e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-text-secondary/70",children:t.length}),M&&e.jsx("span",{title:s?`${t.filter(T=>T.status==="failed").length} of ${t.length} operations failed`:m?.error||"Operation failed",children:e.jsx(wt,{className:"h-3 w-3 text-destructive"})}),s&&f&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:b?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:b?"Some responses were truncated":"Some responses were compacted"})]})}),!s&&x&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:h?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:(()=>{const T=m?._meta,k=T?.originalTokens&&T?.finalTokens?Math.round((1-T.finalTokens/T.originalTokens)*100):null;return h?k?`Response truncated (${k}% reduction)`:"Response was truncated":k?`Response compacted (${k}% reduction)`:"Response was compacted"})()})]})}),p?e.jsx(tt,{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 ${r?"rotate-180":""}`,children:e.jsx(fe,{className:"h-3 w-3"})})]}),!s&&m&&(p&&m.rawInput?.todos?e.jsx(Tl,{todos:m.rawInput.todos,className:"text-paragraph-sm text-text-secondary/70 pl-4.5"}):m.subline?e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:m.subline}):null),!s&&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&&!r&&e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:V}),s&&o.length>0&&(()=>{const T=o.filter(S=>S.status==="completed"&&S.metadata?.action!=="no_action_needed").length,k=o.filter(S=>S.status==="triggered").length;return k>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:["Compacting ",k," response",k>1?"s":"","..."]}):T>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:[T," response",T>1?"s":""," ","compacted"]}):null})()]}),!p&&N&&m&&e.jsx("div",{className:"pl-4.5 mt-2",children:e.jsx(da,{parentStatus:m.status,agentName:m.rawInput?.agentName,query:m.rawInput?.query,isExpanded:U,onExpandChange:B,storedMessages:m.subagentMessages})}),!p&&r&&e.jsx("div",{className:"mt-1",children:s?e.jsx("div",{className:"flex flex-col gap-2 mt-1",children:t.map(T=>{const k=o.find(S=>S.toolCallId===T.id);return e.jsx(_l,{toolCall:T,...k?{hookNotification:k}:{}},T.id)})}):m&&e.jsx(ma,{toolCall:m,...g?{hookNotification:g}:{}})})]})}function _l({toolCall:t,hookNotification:s}){const[n,o]=l.useState(!1),r=!!(t.subagentMessages&&t.subagentMessages.length>0),a=et.useMemo(()=>{const p=t.subagentMessages??[];for(let g=p.length-1;g>=0;g--){const x=p[g],h=x?._meta?.context_size??x?.context_size;if(h!=null)return h}return null},[t.subagentMessages]),c=!!(s?.status==="completed"&&s.metadata?.action&&s.metadata.action!=="no_action_needed"&&s.metadata.action!=="none"||t._meta?.compactionAction),u=s?.metadata?.action==="truncated"||s?.metadata?.action==="compacted_then_truncated"||t._meta?.compactionAction==="truncated",d=t.status==="failed",m=(t.status==="pending"||t.status==="in_progress")&&!t.subagentCompleted;return r?e.jsxs("div",{className:"flex flex-col ml-5",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>o(!n),"aria-expanded":n,children:[e.jsx("div",{className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:e.jsx(qt,{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.subagentMessages?.[0]?._meta?.semanticName||t.rawInput?.agentName||"Subagent"}),t.subagentMessages?.[0]?._meta?.semanticName&&e.jsxs("span",{className:"text-muted-foreground text-[10px] ml-1",children:["(",t.rawInput?.agentName||"subagent",")"]}),e.jsx(aa,{contextSize:a,size:12,className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors"}),m&&t.startedAt&&e.jsx(Be,{startTime:t.startedAt}),d&&e.jsx("span",{title:t.error||"Operation failed",children:e.jsx(wt,{className:"h-3 w-3 text-destructive"})}),c&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:(()=>{const p=t._meta,g=p?.originalTokens&&p?.finalTokens?Math.round((1-p.finalTokens/p.originalTokens)*100):null;return u?g?`Response truncated (${g}% reduction)`:"Response was truncated":g?`Response compacted (${g}% reduction)`:"Response was compacted"})()})]})}),e.jsx(fe,{className:`h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors transition-transform duration-200 ${n?"rotate-180":""}`})]}),e.jsx("div",{className:"pl-4.5",children:e.jsx(da,{parentStatus:t.status,agentName:t.rawInput?.agentName,query:t.rawInput?.query,isExpanded:n,onExpandChange:o,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:()=>o(!n),"aria-expanded":n,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(Be,{startTime:t.startedAt}),d&&e.jsx("span",{title:t.error||"Operation failed",children:e.jsx(wt,{className:"h-3 w-3 text-destructive"})}),c&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:(()=>{const p=t._meta,g=p?.originalTokens&&p?.finalTokens?Math.round((1-p.finalTokens/p.originalTokens)*100):null;return u?g?`Response truncated (${g}% reduction)`:"Response was truncated":g?`Response compacted (${g}% reduction)`:"Response was compacted"})()})]})}),e.jsx(fe,{className:`h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors transition-transform duration-200 ${n?"rotate-180":""}`})]}),n&&e.jsx("div",{className:"mt-1",children:e.jsx(ma,{toolCall:t,...s?{hookNotification:s}:{}})})]})}function Ml(t){let s="",n="",o="";const r=t.match(/\[stderr\]\n?([\s\S]*?)(?=\[error\]|$)/),i=t.match(/\[error\]\s*([\s\S]*?)$/);r?.[1]&&(n=r[1].trim()),i?.[1]&&(o=i[1].trim());const a=Math.min(t.includes("[stderr]")?t.indexOf("[stderr]"):t.length,t.includes("[error]")?t.indexOf("[error]"):t.length);return s=t.substring(0,a).trim(),{stdout:s,stderr:n,error:o}}function zt(t){return t==="Sandbox_RunCode"||t==="Sandbox_RunBash"}function El({stdout:t,stderr:s}){const[n,o]=l.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:()=>o("stdout"),className:`px-3 py-1.5 text-[11px] font-mono transition-colors border-b-2 ${n==="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:()=>o("stderr"),className:`px-3 py-1.5 text-[11px] font-mono transition-colors border-b-2 flex items-center gap-1.5 ${n==="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:[n==="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)"})}),n==="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 ma({toolCall:t,hookNotification:s}){const{resolvedTheme:n}=Xt(),[o,r]=l.useState(!1);if(De(t))return e.jsx("div",{className:"text-paragraph-sm text-text-secondary/70 ml-2",children:la(t)});const i={fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit","--w-rjv-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-key-string":n==="dark"?"#fafafa":"#09090b","--w-rjv-background-color":"transparent","--w-rjv-line-color":n==="dark"?"#27272a":"#e4e4e7","--w-rjv-arrow-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-edit-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-info-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-update-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-success-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-curlybraces-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-colon-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-brackets-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-string-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-type-string-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-type-int-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-float-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-bigint-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-boolean-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-date-color":n==="dark"?"#ec4899":"#db2777","--w-rjv-type-url-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-null-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-nan-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-undefined-color":n==="dark"?"#ef4444":"#dc2626"};return e.jsxs("div",{className:"text-sm border border-border rounded-lg bg-card overflow-hidden w-full",children:[t.locations&&t.locations.length>0&&e.jsxs("div",{className:"p-3 border-b border-border",children:[e.jsx("div",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider mb-1.5 font-sans",children:"Files"}),e.jsx("ul",{className:"space-y-1",children:t.locations.map(a=>e.jsxs("li",{className:"font-mono text-[11px] text-foreground bg-muted px-1.5 py-0.5 rounded w-fit",children:[a.path,a.line!==null&&a.line!==void 0&&`:${a.line}`]},`${a.path}:${a.line??""}`))})]}),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(rs,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:i})})]}),t._meta?.compactionAction&&e.jsx(Rl,{compactionAction:t._meta.compactionAction,originalTokens:t._meta.originalTokens,finalTokens:t._meta.finalTokens,originalContentPath:t._meta.originalContentPath}),(t.content&&t.content.length>0||t.error)&&!zt(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((a,c)=>{const u=()=>a.type==="diff"&&"path"in a?`diff-${a.path}-${c}`:a.type==="terminal"&&"terminalId"in a?`terminal-${a.terminalId}`:a.type==="text"&&"text"in a?`text-${a.text.substring(0,20)}-${c}`:a.type==="content"&&"content"in a?`content-${a.content.text?.substring(0,20)}-${c}`:`block-${c}`,d=(p,g)=>{try{const x=JSON.parse(p);if(typeof x=="object"&&x!==null){const h={...x};return"_compactionMeta"in h&&delete h._compactionMeta,e.jsx("div",{className:"text-[11px]",children:e.jsx(rs,{value:h,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:i})},g)}}catch{}return e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-foreground overflow-x-auto",children:p},g)};if(zt(t.title)&&(a.type==="text"||a.type==="content"))return null;if(a.type==="content"&&"content"in a){const p=a.content;if(p.type==="text"&&p.text)return d(p.text,u())}if(a.type==="text"&&"text"in a)return d(a.text,u());if(a.type==="image"){const p=a.alt||"Generated image";let g;if("data"in a)g=`data:${a.mimeType||"image/png"};base64,${a.data}`;else if("url"in a)g=a.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"})},u())}return a.type==="diff"&&"path"in a&&"oldText"in a&&"newText"in a?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:[a.path,"line"in a&&a.line!==null&&a.line!==void 0&&`:${a.line}`]}),e.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"text-red-500 dark:text-red-400",children:["- ",a.oldText]}),e.jsxs("div",{className:"text-green-500 dark:text-green-400",children:["+ ",a.newText]})]})]},u()):null}),t.error&&e.jsxs("div",{className:"text-destructive font-mono text-[11px] mt-2",children:["Error: ",t.error]})]})]}),zt(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 u=Ml(c),d=[u.stderr,u.error].filter(Boolean).join(`
12
- `);return u.stdout||d?e.jsxs("div",{className:"border-b border-border last:border-0",children:[e.jsxs("button",{type:"button",onClick:()=>r(!o),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(ho,{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"}),u.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(fe,{className:`h-3.5 w-3.5 text-text-secondary transition-transform duration-200 ${o?"rotate-180":""}`})]}),o&&e.jsx(El,{stdout:u.stdout,stderr:d})]}):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:"," ",ua((t.completedAt-t.startedAt)/1e3)]})]})]})]})]})}const Al=Te("w-full min-w-0 rounded-2xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words [overflow-wrap:anywhere] transition-colors",{variants:{role:{user:"bg-secondary text-foreground px-4 py-4 text-paragraph",assistant:"text-foreground text-paragraph",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"}}),Is=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g;function bt(t){Is.lastIndex=0;let s=0;for(;Is.exec(t)!==null;)s++;return s}function Xe(t){return t.replace(/\n+$/g,"")}const pa=l.forwardRef(({role:t,variant:s,isStreaming:n,message:o,thinkingDisplayStyle:r="collapsible",className:i,children:a,...c},u)=>{const d=H(b=>b.streamingStartTime);H(b=>b.currentModel);const m=H(b=>b.sources),p=l.useMemo(()=>{const b=new Map;for(const N of m)b.set(N.id,N);if(o?.sources)for(const N of o.sources)b.set(N.id,N);return Array.from(b.values())},[m,o?.sources]),g=o&&!a,x=g?o.role:t||"assistant",h=g?o.isStreaming:n;let f=a;if(g){const b=o.metadata?.thinking,N=!!b,v=o.isStreaming&&!o.content&&o.role==="assistant";f=e.jsxs(e.Fragment,{children:[o.role==="assistant"&&N&&e.jsx("div",{children:e.jsx(ca,{content:b,isStreaming:o.isStreaming,mode:r,autoCollapse:!0})}),v&&d&&e.jsx("div",{className:"flex flex-col 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..."})})}),o.role==="assistant"?(()=>{const C=(o.toolCalls||[]).slice().sort((j,O)=>(j.contentPosition??1/0)-(O.contentPosition??1/0)),U=j=>{const O=[],Q=new Map;let $=[],X=[],R=null;const A=()=>{$.length>1?O.push({type:"selecting",toolCalls:$}):$.length===1&&O.push($[0]),$=[]},J=()=>{X.length>1?O.push({type:"batch",toolCalls:X}):X.length===1&&O.push(X[0]),X=[],R=null};for(const G of j){if(G.title==="todo_write"){A(),J(),O.push(G);continue}if(G.batchId){A(),J();const ne=Q.get(G.batchId);if(ne)ne.push(G);else{const le=[G];Q.set(G.batchId,le),O.push({type:"batch",toolCalls:le})}}else De(G)?(J(),$.push(G)):(A(),R===G.title?X.push(G):(J(),X=[G],R=G.title))}return A(),J(),O},B=(o.hookNotifications||[]).filter(j=>j.hookType==="tool_response"),D=()=>{const j=C.filter(O=>!De(O));return j.length===0?!1:j.every(O=>gt(O)==="completed")},I=o.isStreaming&&C.length>0&&D()&&o.content.trim().length<50,_=(j,O)=>{if(typeof j=="object"&&"type"in j&&j.type==="batch"){const X=B.filter(R=>j.toolCalls.some(A=>A.id===R.toolCallId));return e.jsx(Pe,{toolCalls:j.toolCalls,isGrouped:!0,hookNotifications:X},`batch-${j.toolCalls[0]?.batchId||O}`)}if(typeof j=="object"&&"type"in j&&j.type==="selecting")return e.jsx(Pe,{toolCalls:j.toolCalls,isGrouped:!0},`selecting-${j.toolCalls[0]?.id||O}`);const Q=j,$=B.filter(X=>X.toolCallId===Q.id);return e.jsx(Pe,{toolCalls:[Q],isGrouped:!1,hookNotifications:$},Q.id)},M=(o.hookNotifications||[]).filter(j=>j.hookType!=="tool_response").slice().sort((j,O)=>(j.contentPosition??1/0)-(O.contentPosition??1/0));if(C.length===0||!C.some(j=>j.contentPosition!==void 0)){const j=U(C);if(!M.some(R=>R.contentPosition!==void 0))return e.jsxs("div",{className:"flex flex-col gap-2",children:[M.length>0&&e.jsx("div",{className:"flex flex-col gap-2",children:M.map(R=>e.jsx(Pt,{notification:R},R.id))}),e.jsx("div",{children:e.jsx(Fe,{content:Xe(o.content),isStreaming:o.isStreaming,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:0})}),j.length>0&&e.jsx("div",{className:"flex flex-col gap-2",children:j.map((R,A)=>_(R,A))}),I&&e.jsx("div",{className:"flex flex-col rounded-md px-1 -mx-1 w-fit",children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Thinking..."})})})]});const Q=[];let $=0,X=0;if(M.forEach(R=>{const A=R.contentPosition??o.content.length;if(A>$){const J=o.content.slice($,A),G=Xe(J);G&&(Q.push(e.jsx("div",{children:e.jsx(Fe,{content:G,isStreaming:!1,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:X})},`text-before-hook-${R.id}`)),X+=bt(G))}Q.push(e.jsx(Pt,{notification:R},R.id)),$=A}),$<o.content.length){const R=o.content.slice($),A=Xe(R);A&&(Q.push(e.jsx("div",{children:e.jsx(Fe,{content:A,isStreaming:o.isStreaming,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:X})},"text-end-hooks")),X+=bt(A))}return j.length>0&&j.forEach((R,A)=>{Q.push(_(R,A))}),e.jsx("div",{className:"flex flex-col gap-2",children:Q})}const E=[],K=[],Y=C.filter(De);C.filter(j=>!De(j)).forEach(j=>{K.push({type:"toolCall",item:j,position:j.contentPosition??o.content.length})}),M.forEach(j=>{K.push({type:"hookNotification",item:j,position:j.contentPosition??0})}),K.sort((j,O)=>j.position-O.position);let W=0,V=0,T=[],k,S;const P=()=>{T.length>1?E.push(e.jsx(Pe,{toolCalls:T,isGrouped:!0},`group-${k||S}-${T[0]?.id}`)):T.length===1&&E.push(e.jsx("div",{children:e.jsx(Pe,{toolCalls:[T[0]],isGrouped:!1})},`tool-${T[0]?.id}`)),T=[],k=void 0,S=void 0};if(K.forEach((j,O)=>{const Q=j.position;if(Q>W){P();const $=o.content.slice(W,Q),X=Xe($);if(X){const R=(j.type==="toolCall",j.item.id);E.push(e.jsx("div",{children:e.jsx(Fe,{content:X,isStreaming:!1,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:V})},`text-before-${R}`)),V+=bt(X)}}if(j.type==="hookNotification")P(),E.push(e.jsx(Pt,{notification:j.item},j.item.id));else{const $=j.item;$.title==="todo_write"?(P(),T=[$],P()):$.batchId?k===$.batchId?T.push($):(P(),k=$.batchId,S=$.title,T=[$]):S===$.title&&!k?T.push($):(P(),S=$.title,T=[$])}W=Q,O===K.length-1&&P()}),W<o.content.length){const j=o.content.slice(W),O=Xe(j);O&&(E.push(e.jsx("div",{children:e.jsx(Fe,{content:O,isStreaming:o.isStreaming,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:V})},"text-end")),V+=bt(O))}return Y.length>0&&(Y.length>1?E.push(e.jsx(Pe,{toolCalls:Y,isGrouped:!0},`selecting-group-${Y[0]?.id}`)):E.push(e.jsx("div",{children:e.jsx(Pe,{toolCalls:[Y[0]],isGrouped:!1})},`tool-${Y[0]?.id}`))),I&&E.push(e.jsx("div",{className:"flex flex-col rounded-md px-1 -mx-1 w-fit",children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Thinking..."})})},"thinking-indicator")),e.jsx("div",{className:"flex flex-col gap-2",children:E})})():e.jsxs("div",{className:"flex flex-col gap-2",children:[o.images&&o.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:o.images.map((C,U)=>e.jsx("img",{src:`data:${C.mimeType};base64,${C.data}`,alt:`Attachment ${U+1}`,className:"max-w-[200px] max-h-[200px] rounded-lg object-cover"},`image-${C.mimeType}-${C.data.slice(0,20)}`))}),o.content&&e.jsx("div",{className:"whitespace-pre-wrap break-words [overflow-wrap:anywhere]",children:o.content})]})]})}return e.jsx("div",{ref:u,className:y(Al({role:x,variant:s}),h&&"animate-pulse-subtle",i),...c,children:f})});pa.displayName="MessageContent";const fa=l.forwardRef(({showIcons:t=!0,visibleTabs:s=["todo","files"],variant:n="default",className:o,...r},i)=>{const c=[{id:"todo",label:"To-do",icon:_t},{id:"files",label:"Files",icon:We},{id:"database",label:"Database",icon:sn},{id:"sources",label:"Sources",icon:nn},{id:"settings",label:"Settings",icon:Ht}].filter(d=>s.includes(d.id)),u=n==="compact"?"gap-[4px]":"gap-3";return e.jsx(He,{ref:i,className:y("w-full justify-start bg-transparent p-0 h-auto",u,o),...r,children:c.map(d=>{const m=d.icon;return e.jsxs(Ue,{value:d.id,className:y("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground hover:text-foreground transition-colors"),children:[t&&m&&e.jsx(m,{className:"size-4"}),d.label]},d.id)})})});fa.displayName="PanelTabsHeader";const Pl=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(qs,{ref:o,className:y("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-paragraph-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[s,e.jsx($a,{asChild:!0,children:e.jsx(xo,{className:"h-4 w-4 opacity-50"})})]}));Pl.displayName=qs.displayName;const ga=l.forwardRef(({className:t,...s},n)=>e.jsx(Ks,{ref:n,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(bo,{className:"h-4 w-4"})}));ga.displayName=Ks.displayName;const ha=l.forwardRef(({className:t,...s},n)=>e.jsx(Ys,{ref:n,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(fe,{className:"h-4 w-4"})}));ha.displayName=Ys.displayName;const Dl=l.forwardRef(({className:t,children:s,position:n="popper",...o},r)=>e.jsx(La,{children:e.jsxs(Qs,{ref:r,className:y("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...o,children:[e.jsx(ga,{}),e.jsx(Oa,{className:y("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(ha,{})]})}));Dl.displayName=Qs.displayName;const Ul=l.forwardRef(({className:t,...s},n)=>e.jsx(Gs,{ref:n,className:y("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));Ul.displayName=Gs.displayName;const zl=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Xs,{ref:o,className:y("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Fa,{children:e.jsx(lt,{className:"h-4 w-4"})})}),e.jsx(Ba,{children:s})]}));zl.displayName=Xs.displayName;const $l=l.forwardRef(({className:t,...s},n)=>e.jsx(Js,{ref:n,className:y("-mx-1 my-1 h-px bg-muted",t),...s}));$l.displayName=Js.displayName;const Ll=Hs,xa=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{className:y("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s,ref:n}));xa.displayName=Nt.displayName;const Ol=Te("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"}}),Fl=l.forwardRef(({side:t="right",className:s,children:n,...o},r)=>e.jsxs(Ll,{children:[e.jsx(xa,{}),e.jsxs(Ct,{ref:r,className:y(Ol({side:t}),s),...o,children:[n,e.jsxs(Ws,{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(It,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fl.displayName=Ct.displayName;const Bl=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:y("text-lg font-semibold text-foreground",t),...s}));Bl.displayName=St.displayName;const Hl=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:y("text-sm text-muted-foreground",t),...s}));Hl.displayName=kt.displayName;function Wl({className:t}){const{toggleSidebar:s,open:n}=_e();return e.jsx(Re,{className:y(t),"data-testid":"sidebar-toggle-button","data-state":n?"open":"closed",onClick:s,"aria-label":"Toggle sidebar",children:e.jsx(yo,{className:"size-4 text-muted-foreground"})})}const ba=l.forwardRef(({task:t,collapsible:s=!0,defaultExpanded:n=!1,onTaskClick:o,className:r,...i},a)=>{const[c,u]=l.useState(n),d=!!(t.details||t.files&&t.files.length>0),m={pending:Tt,in_progress:Vt,completed:Rt}[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=()=>{d&&s&&u(!c),o?.(t)};return e.jsxs("div",{ref:a,className:y("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",r),...i,children:[e.jsxs("button",{type:"button",onClick:g,className:y("w-full flex items-center gap-3 px-3 py-2.5 text-left",d&&s&&"cursor-pointer"),disabled:!d&&!s,children:[e.jsx(m,{className:y("w-4 h-4 shrink-0",p(),t.status==="in_progress"&&"animate-spin")}),e.jsx("span",{className:y("flex-1 text-paragraph-sm font-[var(--font-family)]",t.status==="completed"&&"line-through opacity-60",t.status==="in_progress"&&"font-medium"),children:t.text}),d&&s&&e.jsx(fe,{className:y("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",c&&"rotate-180"),"aria-hidden":"true"})]}),d&&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(x=>e.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:x},x))})]})]})]})});ba.displayName="Subagent";const Vl=l.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:n,emptyMessage:o="No subagents yet.",className:r,...i},a)=>e.jsx("div",{ref:a,className:y("space-y-2 max-h-96 overflow-y-auto",r),...i,children:t.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:o}):t.map(c=>e.jsx(ba,{task:c,collapsible:s,...n?{onTaskClick:n}:{}},c.id))}));Vl.displayName="SubagentList";const ql=Te("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"}}),Kl=l.forwardRef(({className:t,autoResize:s=!1,maxHeight:n=200,variant:o,...r},i)=>{const a=l.useRef(null),c=l.useCallback(d=>{a.current=d,typeof i=="function"?i(d):i&&(i.current=d)},[i]),u=l.useCallback(()=>{const d=a.current;if(!d||!s)return;d.style.height="auto";const m=Math.min(d.scrollHeight,n);d.style.height=`${m}px`,d.scrollHeight>n?d.style.overflowY="auto":d.style.overflowY="hidden"},[s,n]);return l.useEffect(()=>{u()},[u]),e.jsx("textarea",{className:y(ql({variant:o}),s&&"overflow-y-hidden",t),ref:c,...r})});Kl.displayName="Textarea";function Yl(){return"http://localhost:3100"}const Rs={agentServerUrl:Yl(),debuggerUrl:void 0};function Ql(){const{client:t,error:s,sessionId:n}=tr({serverUrl:Rs.agentServerUrl});return e.jsx(li,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(Vi,{client:t,initialSessionId:n,error:s,...Rs.debuggerUrl})})}const Gl="bibliotecha_auth";function Xl(t){return document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`))?.[2]??null}async function Jl(){new URLSearchParams(window.location.search).get("token"),Xl(Gl);const s=document.getElementById("root");if(!s)throw new Error("Root element not found");va.createRoot(s).render(e.jsx(et.StrictMode,{children:e.jsx(Ql,{})}))}Jl();
11
+ `)[0]??"").slice(0,100)+(n.length>100?"...":""):"";return e.jsxs("div",{children:[!u&&e.jsx("div",{className:"w-full max-w-md",children:b?._meta?.currentActivity?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:b._meta.currentActivity}):b?._meta?.statusGenerating?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate animate-pulse",children:"Determining status..."}):D?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:D}):I?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/50 truncate",children:I}):null}),u&&e.jsxs("div",{className:"space-y-3",children:[(s||n)&&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:i?.[0]?._meta?.semanticName?"Task: ":"agentName: "}),i?.[0]?._meta?.semanticName?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-foreground font-medium",children:i[0]._meta.semanticName}),e.jsxs("span",{className:"text-muted-foreground text-[10px] ml-1",children:["(",s,")"]})]}):e.jsx("span",{className:"text-foreground",children:s})]}),n&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"query: "}),e.jsx("span",{className:"text-foreground",children:n})]})]})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>m(!d),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(fe,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${d?"rotate-180":""}`})]}),d&&e.jsxs("div",{ref:x,className:"mt-2 rounded-md overflow-hidden bg-muted/30 border border-border/50 max-h-[200px] overflow-y-auto",children:[!N&&f&&e.jsx("div",{className:"px-2 py-2 text-[11px] text-muted-foreground",children:"Waiting for sub-agent response..."}),b&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[b.contentBlocks&&b.contentBlocks.length>0?b.contentBlocks.map((_,M)=>_.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(Dt,{content:_.text})},`text-${_.text.slice(0,30)}-${M}`):e.jsx(kl,{toolCall:_.toolCall},_.toolCall.id)):b.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(Dt,{content:b.content})}),b.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!f&&b?.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(Dt,{content:b.content})})]})]})]})}function kl({toolCall:t}){const s={pending:"...",in_progress:"",completed:"",failed:""}[t.status],n={pending:"text-muted-foreground",in_progress:"text-blue-500",completed:"text-green-500",failed:"text-destructive"}[t.status];return e.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:n,children:s}),e.jsx("span",{className:"font-medium",children:t.prettyName||t.title}),t.status==="in_progress"&&e.jsx(Vt,{className:"h-2.5 w-2.5 animate-spin"})]})}function Tl({todos:t,className:s}){if(!t||t.length===0)return null;const n=l.useMemo(()=>{const r=t.find(a=>a.status==="in_progress");if(r)return r;const i=t.find(a=>a.status==="completed");return i||t[0]},[t]);if(!n)return null;const o=n.status==="in_progress"&&n.activeForm||n.content;return e.jsxs("span",{className:y("flex items-center gap-1.5",s),children:[n.status==="completed"?e.jsx(Rt,{className:"size-3 text-muted-foreground shrink-0"}):n.status==="pending"?e.jsx(Tt,{className:"size-3 text-foreground shrink-0"}):null,e.jsx("span",{className:"truncate",children:o})]})}const Ts={Globe:tn,Image:go,Link:fo,Cloud:po,CheckSquare:_t,Search:mo,FileText:We,Edit:uo,Wrench:co,BrainCircuit:lo,CircleDot:qt};function Il(t,s){const[n,o]=l.useState(0),r=l.useRef(null);return l.useEffect(()=>{if(!s||!t){o(0);return}const i=()=>{o((Date.now()-t)/1e3)};return i(),r.current=setInterval(i,100),()=>{r.current&&clearInterval(r.current)}},[t,s]),n}function ua(t){if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return s>0?`${s}h ${n}m ${o}s`:`${n}m ${o}s`}function Be({startTime:t,isRunning:s=!0}){const n=Il(t,s);return e.jsx("span",{className:"text-xs text-text-secondary/70 tabular-nums ml-1",children:ua(n)})}function Rl({compactionAction:t,originalTokens:s,finalTokens:n,originalContentPath:o}){const r=s&&n?s-n:void 0,i=s&&n?Math.round((1-n/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(ce,{className:"w-3.5 h-3.5 text-text-secondary"}):e.jsx(at,{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"]})]}),n!==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:[n.toLocaleString()," tokens"]})]}),r!==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:[r.toLocaleString()," tokens"]})]}),i!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] text-text-secondary uppercase tracking-wide font-sans mb-0.5",children:"Reduction"}),e.jsxs("div",{className:"text-[12px] font-medium text-foreground font-sans",children:[i,"%"]})]})]}),o&&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:o})]})]})}function Pe({toolCalls:t,isGrouped:s=!1,autoMinimize:n=!0,hookNotifications:o=[]}){const[r,i]=l.useState(!1),[a,c]=l.useState(!1),[u,d]=l.useState(!1),m=t.length===1?t[0]:null,p=m?.title==="todo_write",g=m?o.find(T=>T.toolCallId===m.id):void 0,x=!!(g?.status==="completed"&&g.metadata?.action&&g.metadata.action!=="no_action_needed"&&g.metadata.action!=="none"||m?._meta?.compactionAction),h=g?.metadata?.action==="truncated"||g?.metadata?.action==="compacted_then_truncated"||m?._meta?.compactionAction==="truncated",f=s?t.some(T=>T._meta?.compactionAction||o.some(k=>k.toolCallId===T.id&&k.status==="completed"&&k.metadata?.action&&k.metadata.action!=="no_action_needed"&&k.metadata.action!=="none")):!1,b=s?t.some(T=>T._meta?.compactionAction==="truncated"||o.some(k=>k.toolCallId===T.id&&(k.metadata?.action==="truncated"||k.metadata?.action==="compacted_then_truncated"))):!1,N=!!(m?.subagentMessages&&m.subagentMessages.length>0),C=et.useMemo(()=>{if(!m?.subagentMessages)return null;const T=m.subagentMessages;for(let k=T.length-1;k>=0;k--){const S=T[k],P=S?._meta?.context_size??S?.context_size;if(P!=null)return P}return null},[m?.subagentMessages]),[U,B]=l.useState(!1),D=et.useContext(Jt),I=s?gl(t):m?gt(m):"executing",_=I==="completed",M=I==="failed",A=I==="selecting";l.useEffect(()=>{if(n&&_&&!a&&!u){const T=setTimeout(()=>{c(!0),i(!1)},500);return()=>clearTimeout(T)}},[n,_,a,u]);const K=et.useCallback(()=>{p&&D&&m?D.panelSize!=="hidden"&&D.activeTab==="todo"?D.setPanelSize("hidden"):(D.setPanelSize("small"),D.setActiveTab("todo")):N?(d(!0),B(!U)):(d(!0),i(!r),a&&c(!1))},[p,D,r,a,m,N,U]),z=s?ds:m?.icon&&Ts[m.icon]?Ts[m.icon]:qt,V=s?Cl(t,_?"past":"active"):m?la(m):"Tool operation";if(A&&!s)return e.jsx("div",{className:"flex flex-col 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(z,{className:"h-3 w-3"})}),e.jsxs("span",{className:"text-paragraph-xs text-text-muted",children:[V,m?.startedAt&&e.jsx(Be,{startTime:m.startedAt,isRunning:!m.subagentCompleted})]})]})});if(A&&s){const T=(()=>{const S=t.map(P=>P.startedAt).filter(P=>P!=null);return S.length===0?null:Math.min(...S)})(),k=t.every(S=>S.subagentCompleted);return e.jsxs("div",{className:"flex flex-col 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(ds,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Selecting tools"}),T&&e.jsx(Be,{startTime:T,isRunning:!k}),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:V})]})}return e.jsxs("div",{className:"flex flex-col",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:K,"aria-expanded":p?void 0:r,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(z,{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&&V]}),N&&e.jsx(aa,{contextSize:C,size:12,className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors"}),!s&&m?.startedAt&&I==="executing"&&e.jsx(Be,{startTime:m.startedAt,isRunning:!m.subagentCompleted}),s&&I==="executing"&&(()=>{const T=t.map(P=>P.startedAt).filter(P=>P!=null);if(T.length===0)return null;const k=Math.min(...T),S=t.every(P=>P.status==="completed"&&(!P.subagentMessages||P.subagentCompleted));return e.jsx(Be,{startTime:k,isRunning:!S})})(),s&&e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-text-secondary/70",children:t.length}),M&&e.jsx("span",{title:s?`${t.filter(T=>T.status==="failed").length} of ${t.length} operations failed`:m?.error||"Operation failed",children:e.jsx(wt,{className:"h-3 w-3 text-destructive"})}),s&&f&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:b?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:b?"Some responses were truncated":"Some responses were compacted"})]})}),!s&&x&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:h?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:(()=>{const T=m?._meta,k=T?.originalTokens&&T?.finalTokens?Math.round((1-T.finalTokens/T.originalTokens)*100):null;return h?k?`Response truncated (${k}% reduction)`:"Response was truncated":k?`Response compacted (${k}% reduction)`:"Response was compacted"})()})]})}),p?e.jsx(tt,{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 ${r?"rotate-180":""}`,children:e.jsx(fe,{className:"h-3 w-3"})})]}),!s&&m&&(p&&m.rawInput?.todos?e.jsx(Tl,{todos:m.rawInput.todos,className:"text-paragraph-sm text-text-secondary/70 pl-4.5"}):m.subline?e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:m.subline}):null),!s&&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&&!r&&e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:V}),s&&o.length>0&&(()=>{const T=o.filter(S=>S.status==="completed"&&S.metadata?.action!=="no_action_needed").length,k=o.filter(S=>S.status==="triggered").length;return k>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:["Compacting ",k," response",k>1?"s":"","..."]}):T>0?e.jsxs("span",{className:"text-paragraph-sm text-text-secondary/70 pl-4.5",children:[T," response",T>1?"s":""," ","compacted"]}):null})()]}),!p&&N&&m&&e.jsx("div",{className:"pl-4.5 mt-2",children:e.jsx(da,{parentStatus:m.status,agentName:m.rawInput?.agentName,query:m.rawInput?.query,isExpanded:U,onExpandChange:B,storedMessages:m.subagentMessages})}),!p&&r&&e.jsx("div",{className:"mt-1",children:s?e.jsx("div",{className:"flex flex-col gap-2 mt-1",children:t.map(T=>{const k=o.find(S=>S.toolCallId===T.id);return e.jsx(_l,{toolCall:T,...k?{hookNotification:k}:{}},T.id)})}):m&&e.jsx(ma,{toolCall:m,...g?{hookNotification:g}:{}})})]})}function _l({toolCall:t,hookNotification:s}){const[n,o]=l.useState(!1),r=!!(t.subagentMessages&&t.subagentMessages.length>0),a=et.useMemo(()=>{const p=t.subagentMessages??[];for(let g=p.length-1;g>=0;g--){const x=p[g],h=x?._meta?.context_size??x?.context_size;if(h!=null)return h}return null},[t.subagentMessages]),c=!!(s?.status==="completed"&&s.metadata?.action&&s.metadata.action!=="no_action_needed"&&s.metadata.action!=="none"||t._meta?.compactionAction),u=s?.metadata?.action==="truncated"||s?.metadata?.action==="compacted_then_truncated"||t._meta?.compactionAction==="truncated",d=t.status==="failed",m=(t.status==="pending"||t.status==="in_progress")&&!t.subagentCompleted;return r?e.jsxs("div",{className:"flex flex-col ml-5",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>o(!n),"aria-expanded":n,children:[e.jsx("div",{className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors",children:e.jsx(qt,{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.subagentMessages?.[0]?._meta?.semanticName||t.rawInput?.agentName||"Subagent"}),t.subagentMessages?.[0]?._meta?.semanticName&&e.jsxs("span",{className:"text-muted-foreground text-[10px] ml-1",children:["(",t.rawInput?.agentName||"subagent",")"]}),e.jsx(aa,{contextSize:a,size:12,className:"text-text-secondary/70 group-hover:text-text-secondary transition-colors"}),m&&t.startedAt&&e.jsx(Be,{startTime:t.startedAt}),d&&e.jsx("span",{title:t.error||"Operation failed",children:e.jsx(wt,{className:"h-3 w-3 text-destructive"})}),c&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:(()=>{const p=t._meta,g=p?.originalTokens&&p?.finalTokens?Math.round((1-p.finalTokens/p.originalTokens)*100):null;return u?g?`Response truncated (${g}% reduction)`:"Response was truncated":g?`Response compacted (${g}% reduction)`:"Response was compacted"})()})]})}),e.jsx(fe,{className:`h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors transition-transform duration-200 ${n?"rotate-180":""}`})]}),e.jsx("div",{className:"pl-4.5",children:e.jsx(da,{parentStatus:t.status,agentName:t.rawInput?.agentName,query:t.rawInput?.query,isExpanded:n,onExpandChange:o,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:()=>o(!n),"aria-expanded":n,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(Be,{startTime:t.startedAt}),d&&e.jsx("span",{title:t.error||"Operation failed",children:e.jsx(wt,{className:"h-3 w-3 text-destructive"})}),c&&e.jsx(ge,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(xe,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(ce,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(be,{children:(()=>{const p=t._meta,g=p?.originalTokens&&p?.finalTokens?Math.round((1-p.finalTokens/p.originalTokens)*100):null;return u?g?`Response truncated (${g}% reduction)`:"Response was truncated":g?`Response compacted (${g}% reduction)`:"Response was compacted"})()})]})}),e.jsx(fe,{className:`h-3 w-3 text-text-secondary/70 group-hover:text-text-secondary transition-colors transition-transform duration-200 ${n?"rotate-180":""}`})]}),n&&e.jsx("div",{className:"mt-1",children:e.jsx(ma,{toolCall:t,...s?{hookNotification:s}:{}})})]})}function Ml(t){let s="",n="",o="";const r=t.match(/\[stderr\]\n?([\s\S]*?)(?=\[error\]|$)/),i=t.match(/\[error\]\s*([\s\S]*?)$/);r?.[1]&&(n=r[1].trim()),i?.[1]&&(o=i[1].trim());const a=Math.min(t.includes("[stderr]")?t.indexOf("[stderr]"):t.length,t.includes("[error]")?t.indexOf("[error]"):t.length);return s=t.substring(0,a).trim(),{stdout:s,stderr:n,error:o}}function zt(t){return t==="Sandbox_RunCode"||t==="Sandbox_RunBash"}function Al({stdout:t,stderr:s}){const[n,o]=l.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:()=>o("stdout"),className:`px-3 py-1.5 text-[11px] font-mono transition-colors border-b-2 ${n==="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:()=>o("stderr"),className:`px-3 py-1.5 text-[11px] font-mono transition-colors border-b-2 flex items-center gap-1.5 ${n==="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:[n==="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)"})}),n==="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 ma({toolCall:t,hookNotification:s}){const{resolvedTheme:n}=Xt(),[o,r]=l.useState(!1);if(De(t))return e.jsx("div",{className:"text-paragraph-sm text-text-secondary/70 ml-2",children:la(t)});const i={fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit","--w-rjv-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-key-string":n==="dark"?"#fafafa":"#09090b","--w-rjv-background-color":"transparent","--w-rjv-line-color":n==="dark"?"#27272a":"#e4e4e7","--w-rjv-arrow-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-edit-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-info-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-update-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-success-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-curlybraces-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-colon-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-brackets-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-string-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-type-string-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-type-int-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-float-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-bigint-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-boolean-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-date-color":n==="dark"?"#ec4899":"#db2777","--w-rjv-type-url-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-null-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-nan-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-undefined-color":n==="dark"?"#ef4444":"#dc2626"};return e.jsxs("div",{className:"text-sm border border-border rounded-lg bg-card overflow-hidden w-full",children:[t.locations&&t.locations.length>0&&e.jsxs("div",{className:"p-3 border-b border-border",children:[e.jsx("div",{className:"text-[10px] font-bold text-text-secondary uppercase tracking-wider mb-1.5 font-sans",children:"Files"}),e.jsx("ul",{className:"space-y-1",children:t.locations.map(a=>e.jsxs("li",{className:"font-mono text-[11px] text-foreground bg-muted px-1.5 py-0.5 rounded w-fit",children:[a.path,a.line!==null&&a.line!==void 0&&`:${a.line}`]},`${a.path}:${a.line??""}`))})]}),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(rs,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:i})})]}),t._meta?.compactionAction&&e.jsx(Rl,{compactionAction:t._meta.compactionAction,originalTokens:t._meta.originalTokens,finalTokens:t._meta.finalTokens,originalContentPath:t._meta.originalContentPath}),(t.content&&t.content.length>0||t.error)&&!zt(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((a,c)=>{const u=()=>a.type==="diff"&&"path"in a?`diff-${a.path}-${c}`:a.type==="terminal"&&"terminalId"in a?`terminal-${a.terminalId}`:a.type==="text"&&"text"in a?`text-${a.text.substring(0,20)}-${c}`:a.type==="content"&&"content"in a?`content-${a.content.text?.substring(0,20)}-${c}`:`block-${c}`,d=(p,g)=>{try{const x=JSON.parse(p);if(typeof x=="object"&&x!==null){const h={...x};return"_compactionMeta"in h&&delete h._compactionMeta,e.jsx("div",{className:"text-[11px]",children:e.jsx(rs,{value:h,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:i})},g)}}catch{}return e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-foreground overflow-x-auto",children:p},g)};if(zt(t.title)&&(a.type==="text"||a.type==="content"))return null;if(a.type==="content"&&"content"in a){const p=a.content;if(p.type==="text"&&p.text)return d(p.text,u())}if(a.type==="text"&&"text"in a)return d(a.text,u());if(a.type==="image"){const p=a.alt||"Generated image";let g;if("data"in a)g=`data:${a.mimeType||"image/png"};base64,${a.data}`;else if("url"in a)g=a.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"})},u())}return a.type==="diff"&&"path"in a&&"oldText"in a&&"newText"in a?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:[a.path,"line"in a&&a.line!==null&&a.line!==void 0&&`:${a.line}`]}),e.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"text-red-500 dark:text-red-400",children:["- ",a.oldText]}),e.jsxs("div",{className:"text-green-500 dark:text-green-400",children:["+ ",a.newText]})]})]},u()):null}),t.error&&e.jsxs("div",{className:"text-destructive font-mono text-[11px] mt-2",children:["Error: ",t.error]})]})]}),zt(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 u=Ml(c),d=[u.stderr,u.error].filter(Boolean).join(`
12
+ `);return u.stdout||d?e.jsxs("div",{className:"border-b border-border last:border-0",children:[e.jsxs("button",{type:"button",onClick:()=>r(!o),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(ho,{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"}),u.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(fe,{className:`h-3.5 w-3.5 text-text-secondary transition-transform duration-200 ${o?"rotate-180":""}`})]}),o&&e.jsx(Al,{stdout:u.stdout,stderr:d})]}):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:"," ",ua((t.completedAt-t.startedAt)/1e3)]})]})]})]})]})}const El=Te("w-full min-w-0 rounded-2xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words [overflow-wrap:anywhere] transition-colors",{variants:{role:{user:"bg-secondary text-foreground px-4 py-4 text-paragraph",assistant:"text-foreground text-paragraph",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"}}),Is=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g;function bt(t){Is.lastIndex=0;let s=0;for(;Is.exec(t)!==null;)s++;return s}function Xe(t){return t.replace(/\n+$/g,"")}const pa=l.forwardRef(({role:t,variant:s,isStreaming:n,message:o,thinkingDisplayStyle:r="collapsible",className:i,children:a,...c},u)=>{const d=H(b=>b.streamingStartTime);H(b=>b.currentModel);const m=H(b=>b.sources),p=l.useMemo(()=>{const b=new Map;for(const N of m)b.set(N.id,N);if(o?.sources)for(const N of o.sources)b.set(N.id,N);return Array.from(b.values())},[m,o?.sources]),g=o&&!a,x=g?o.role:t||"assistant",h=g?o.isStreaming:n;let f=a;if(g){const b=o.metadata?.thinking,N=!!b,v=o.isStreaming&&!o.content&&o.role==="assistant";f=e.jsxs(e.Fragment,{children:[o.role==="assistant"&&N&&e.jsx("div",{children:e.jsx(ca,{content:b,isStreaming:o.isStreaming,mode:r,autoCollapse:!0})}),v&&d&&e.jsx("div",{className:"flex flex-col 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..."})})}),o.role==="assistant"?(()=>{const C=(o.toolCalls||[]).slice().sort((j,O)=>(j.contentPosition??1/0)-(O.contentPosition??1/0)),U=j=>{const O=[],Q=new Map;let $=[],X=[],R=null;const E=()=>{$.length>1?O.push({type:"selecting",toolCalls:$}):$.length===1&&O.push($[0]),$=[]},J=()=>{X.length>1?O.push({type:"batch",toolCalls:X}):X.length===1&&O.push(X[0]),X=[],R=null};for(const G of j){if(G.title==="todo_write"){E(),J(),O.push(G);continue}if(G.batchId){E(),J();const ne=Q.get(G.batchId);if(ne)ne.push(G);else{const le=[G];Q.set(G.batchId,le),O.push({type:"batch",toolCalls:le})}}else De(G)?(J(),$.push(G)):(E(),R===G.title?X.push(G):(J(),X=[G],R=G.title))}return E(),J(),O},B=(o.hookNotifications||[]).filter(j=>j.hookType==="tool_response"),D=()=>{const j=C.filter(O=>!De(O));return j.length===0?!1:j.every(O=>gt(O)==="completed")},I=o.isStreaming&&C.length>0&&D()&&o.content.trim().length<50,_=(j,O)=>{if(typeof j=="object"&&"type"in j&&j.type==="batch"){const X=B.filter(R=>j.toolCalls.some(E=>E.id===R.toolCallId));return e.jsx(Pe,{toolCalls:j.toolCalls,isGrouped:!0,hookNotifications:X},`batch-${j.toolCalls[0]?.batchId||O}`)}if(typeof j=="object"&&"type"in j&&j.type==="selecting")return e.jsx(Pe,{toolCalls:j.toolCalls,isGrouped:!0},`selecting-${j.toolCalls[0]?.id||O}`);const Q=j,$=B.filter(X=>X.toolCallId===Q.id);return e.jsx(Pe,{toolCalls:[Q],isGrouped:!1,hookNotifications:$},Q.id)},M=(o.hookNotifications||[]).filter(j=>j.hookType!=="tool_response").slice().sort((j,O)=>(j.contentPosition??1/0)-(O.contentPosition??1/0));if(C.length===0||!C.some(j=>j.contentPosition!==void 0)){const j=U(C);if(!M.some(R=>R.contentPosition!==void 0))return e.jsxs("div",{className:"flex flex-col gap-2",children:[M.length>0&&e.jsx("div",{className:"flex flex-col gap-2",children:M.map(R=>e.jsx(Pt,{notification:R},R.id))}),e.jsx("div",{children:e.jsx(Fe,{content:Xe(o.content),isStreaming:o.isStreaming,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:0})}),j.length>0&&e.jsx("div",{className:"flex flex-col gap-2",children:j.map((R,E)=>_(R,E))}),I&&e.jsx("div",{className:"flex flex-col rounded-md px-1 -mx-1 w-fit",children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Thinking..."})})})]});const Q=[];let $=0,X=0;if(M.forEach(R=>{const E=R.contentPosition??o.content.length;if(E>$){const J=o.content.slice($,E),G=Xe(J);G&&(Q.push(e.jsx("div",{children:e.jsx(Fe,{content:G,isStreaming:!1,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:X})},`text-before-hook-${R.id}`)),X+=bt(G))}Q.push(e.jsx(Pt,{notification:R},R.id)),$=E}),$<o.content.length){const R=o.content.slice($),E=Xe(R);E&&(Q.push(e.jsx("div",{children:e.jsx(Fe,{content:E,isStreaming:o.isStreaming,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:X})},"text-end-hooks")),X+=bt(E))}return j.length>0&&j.forEach((R,E)=>{Q.push(_(R,E))}),e.jsx("div",{className:"flex flex-col gap-2",children:Q})}const A=[],K=[],Y=C.filter(De);C.filter(j=>!De(j)).forEach(j=>{K.push({type:"toolCall",item:j,position:j.contentPosition??o.content.length})}),M.forEach(j=>{K.push({type:"hookNotification",item:j,position:j.contentPosition??0})}),K.sort((j,O)=>j.position-O.position);let W=0,V=0,T=[],k,S;const P=()=>{T.length>1?A.push(e.jsx(Pe,{toolCalls:T,isGrouped:!0},`group-${k||S}-${T[0]?.id}`)):T.length===1&&A.push(e.jsx("div",{children:e.jsx(Pe,{toolCalls:[T[0]],isGrouped:!1})},`tool-${T[0]?.id}`)),T=[],k=void 0,S=void 0};if(K.forEach((j,O)=>{const Q=j.position;if(Q>W){P();const $=o.content.slice(W,Q),X=Xe($);if(X){const R=(j.type==="toolCall",j.item.id);A.push(e.jsx("div",{children:e.jsx(Fe,{content:X,isStreaming:!1,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:V})},`text-before-${R}`)),V+=bt(X)}}if(j.type==="hookNotification")P(),A.push(e.jsx(Pt,{notification:j.item},j.item.id));else{const $=j.item;$.title==="todo_write"?(P(),T=[$],P()):$.batchId?k===$.batchId?T.push($):(P(),k=$.batchId,S=$.title,T=[$]):S===$.title&&!k?T.push($):(P(),S=$.title,T=[$])}W=Q,O===K.length-1&&P()}),W<o.content.length){const j=o.content.slice(W),O=Xe(j);O&&(A.push(e.jsx("div",{children:e.jsx(Fe,{content:O,isStreaming:o.isStreaming,showEmpty:!1,sources:p,messageId:o.id,citationIndexOffset:V})},"text-end")),V+=bt(O))}return Y.length>0&&(Y.length>1?A.push(e.jsx(Pe,{toolCalls:Y,isGrouped:!0},`selecting-group-${Y[0]?.id}`)):A.push(e.jsx("div",{children:e.jsx(Pe,{toolCalls:[Y[0]],isGrouped:!1})},`tool-${Y[0]?.id}`))),I&&A.push(e.jsx("div",{className:"flex flex-col rounded-md px-1 -mx-1 w-fit",children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"text-paragraph-sm text-text-secondary/70",children:"Thinking..."})})},"thinking-indicator")),e.jsx("div",{className:"flex flex-col gap-2",children:A})})():e.jsxs("div",{className:"flex flex-col gap-2",children:[o.images&&o.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:o.images.map((C,U)=>e.jsx("img",{src:`data:${C.mimeType};base64,${C.data}`,alt:`Attachment ${U+1}`,className:"max-w-[200px] max-h-[200px] rounded-lg object-cover"},`image-${C.mimeType}-${C.data.slice(0,20)}`))}),o.content&&e.jsx("div",{className:"whitespace-pre-wrap break-words [overflow-wrap:anywhere]",children:o.content})]})]})}return e.jsx("div",{ref:u,className:y(El({role:x,variant:s}),h&&"animate-pulse-subtle",i),...c,children:f})});pa.displayName="MessageContent";const fa=l.forwardRef(({showIcons:t=!0,visibleTabs:s=["todo","files"],variant:n="default",className:o,...r},i)=>{const c=[{id:"todo",label:"To-do",icon:_t},{id:"files",label:"Files",icon:We},{id:"database",label:"Database",icon:sn},{id:"sources",label:"Sources",icon:nn},{id:"settings",label:"Settings",icon:Ht}].filter(d=>s.includes(d.id)),u=n==="compact"?"gap-[4px]":"gap-3";return e.jsx(He,{ref:i,className:y("w-full justify-start bg-transparent p-0 h-auto",u,o),...r,children:c.map(d=>{const m=d.icon;return e.jsxs(Ue,{value:d.id,className:y("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground hover:text-foreground transition-colors"),children:[t&&m&&e.jsx(m,{className:"size-4"}),d.label]},d.id)})})});fa.displayName="PanelTabsHeader";const Pl=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(qs,{ref:o,className:y("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-paragraph-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[s,e.jsx($a,{asChild:!0,children:e.jsx(xo,{className:"h-4 w-4 opacity-50"})})]}));Pl.displayName=qs.displayName;const ga=l.forwardRef(({className:t,...s},n)=>e.jsx(Ks,{ref:n,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(bo,{className:"h-4 w-4"})}));ga.displayName=Ks.displayName;const ha=l.forwardRef(({className:t,...s},n)=>e.jsx(Ys,{ref:n,className:y("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(fe,{className:"h-4 w-4"})}));ha.displayName=Ys.displayName;const Dl=l.forwardRef(({className:t,children:s,position:n="popper",...o},r)=>e.jsx(La,{children:e.jsxs(Qs,{ref:r,className:y("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...o,children:[e.jsx(ga,{}),e.jsx(Oa,{className:y("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(ha,{})]})}));Dl.displayName=Qs.displayName;const Ul=l.forwardRef(({className:t,...s},n)=>e.jsx(Gs,{ref:n,className:y("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));Ul.displayName=Gs.displayName;const zl=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Xs,{ref:o,className:y("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Fa,{children:e.jsx(lt,{className:"h-4 w-4"})})}),e.jsx(Ba,{children:s})]}));zl.displayName=Xs.displayName;const $l=l.forwardRef(({className:t,...s},n)=>e.jsx(Js,{ref:n,className:y("-mx-1 my-1 h-px bg-muted",t),...s}));$l.displayName=Js.displayName;const Ll=Hs,xa=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{className:y("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s,ref:n}));xa.displayName=Nt.displayName;const Ol=Te("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"}}),Fl=l.forwardRef(({side:t="right",className:s,children:n,...o},r)=>e.jsxs(Ll,{children:[e.jsx(xa,{}),e.jsxs(Ct,{ref:r,className:y(Ol({side:t}),s),...o,children:[n,e.jsxs(Ws,{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(It,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fl.displayName=Ct.displayName;const Bl=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:y("text-lg font-semibold text-foreground",t),...s}));Bl.displayName=St.displayName;const Hl=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:y("text-sm text-muted-foreground",t),...s}));Hl.displayName=kt.displayName;function Wl({className:t}){const{toggleSidebar:s,open:n}=_e();return e.jsx(Re,{className:y(t),"data-testid":"sidebar-toggle-button","data-state":n?"open":"closed",onClick:s,"aria-label":"Toggle sidebar",children:e.jsx(yo,{className:"size-4 text-muted-foreground"})})}const ba=l.forwardRef(({task:t,collapsible:s=!0,defaultExpanded:n=!1,onTaskClick:o,className:r,...i},a)=>{const[c,u]=l.useState(n),d=!!(t.details||t.files&&t.files.length>0),m={pending:Tt,in_progress:Vt,completed:Rt}[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=()=>{d&&s&&u(!c),o?.(t)};return e.jsxs("div",{ref:a,className:y("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",r),...i,children:[e.jsxs("button",{type:"button",onClick:g,className:y("w-full flex items-center gap-3 px-3 py-2.5 text-left",d&&s&&"cursor-pointer"),disabled:!d&&!s,children:[e.jsx(m,{className:y("w-4 h-4 shrink-0",p(),t.status==="in_progress"&&"animate-spin")}),e.jsx("span",{className:y("flex-1 text-paragraph-sm font-[var(--font-family)]",t.status==="completed"&&"line-through opacity-60",t.status==="in_progress"&&"font-medium"),children:t.text}),d&&s&&e.jsx(fe,{className:y("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",c&&"rotate-180"),"aria-hidden":"true"})]}),d&&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(x=>e.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:x},x))})]})]})]})});ba.displayName="Subagent";const Vl=l.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:n,emptyMessage:o="No subagents yet.",className:r,...i},a)=>e.jsx("div",{ref:a,className:y("space-y-2 max-h-96 overflow-y-auto",r),...i,children:t.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:o}):t.map(c=>e.jsx(ba,{task:c,collapsible:s,...n?{onTaskClick:n}:{}},c.id))}));Vl.displayName="SubagentList";const ql=Te("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"}}),Kl=l.forwardRef(({className:t,autoResize:s=!1,maxHeight:n=200,variant:o,...r},i)=>{const a=l.useRef(null),c=l.useCallback(d=>{a.current=d,typeof i=="function"?i(d):i&&(i.current=d)},[i]),u=l.useCallback(()=>{const d=a.current;if(!d||!s)return;d.style.height="auto";const m=Math.min(d.scrollHeight,n);d.style.height=`${m}px`,d.scrollHeight>n?d.style.overflowY="auto":d.style.overflowY="hidden"},[s,n]);return l.useEffect(()=>{u()},[u]),e.jsx("textarea",{className:y(ql({variant:o}),s&&"overflow-y-hidden",t),ref:c,...r})});Kl.displayName="Textarea";function Yl(){return"http://localhost:3100"}const Rs={agentServerUrl:Yl(),debuggerUrl:void 0};function Ql(){const{client:t,error:s,sessionId:n}=tr({serverUrl:Rs.agentServerUrl});return e.jsx(li,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(Vi,{client:t,initialSessionId:n,error:s,...Rs.debuggerUrl})})}const Gl="bibliotecha_auth";function Xl(t){return document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`))?.[2]??null}async function Jl(){new URLSearchParams(window.location.search).get("token"),Xl(Gl);const s=document.getElementById("root");if(!s)throw new Error("Root element not found");va.createRoot(s).render(e.jsx(et.StrictMode,{children:e.jsx(Ql,{})}))}Jl();