@townco/gui-template 0.1.120 → 0.1.122
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 va,c as et,h as wa}from"./react-DiSrVJhY.js";import{bb as $e,bc as ja,bd as rs,be as le,bf as q,bg as w,bh as ee,bi as F,bj as ae,bk as ue,bl as it,bm as vt,bn as te,bo as Ce,bp as Ht,bq as Na,br as Ca,bs as Sa,bt as ka,bu as Te,bv as Ta,bw as pe,am as Ia,bx as Ra,by as is}from"./vendor-Dm9xAZV8.js";import{P as ls,a as _a}from"./acp-sdk-D4VsTV6L.js";import{S as ve,P as Ma,C as Ms,a as Ea,R as Aa,T as Pa,b as Es,c as As,d as Da,e as Ps,I as Ds,f as Us,g as zs,h as $s,L as Ls,i as Os,j as Ua,k as za,l as Fs,m as Bs,n as Hs,o as $a,O as Nt,p as Ws,q as Ct,r as Vs,s as St,D as kt,t as qs,u as Ks,v as La,w as Ys,x as Qs,y as Oa,z as Gs,V as Fa,A as Xs,B as Js,E as Ba,F as Ha,G as Zs}from"./radix-BaZ_UeJz.js";import{c as tt,d as lt,e as Tt,P as Wa,E as Va,S as en,f as tn,g as qa,h as Wt,i as Ka,j as Ya,k as Qa,l as Ga,m as ge,A as Xa,n as It,F as Ja,o as Za,p as eo,q as to,r as We,s as Rt,t as _t,G as sn,u as nn,v as an,B as cs,w as so,x as no,y as ao,z as Vt,H as oo,I as qt,J as wt,T as ro,K as de,N as io,O as on,Q as ds,U as lo,V as us,W as at,Y as Kt,_ as co,$ as uo,a0 as mo,a1 as po,a2 as fo,a3 as go,a4 as ho,a5 as xo,a6 as bo,a7 as yo,a8 as vo}from"./icons-B0Ax5AoZ.js";import{A as ot,m as ke}from"./framer-motion-DEDjTHcO.js";import{g as rn}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 wo={};const ht=typeof process<"u"&&process.versions?.node;let jo,No=0;const $t=new Set;function Co(t){return $t.add(t),()=>$t.delete(t)}function So(t){for(const s of $t)s(t)}const ms={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},ko={trace:$e.TRACE,debug:$e.DEBUG,info:$e.INFO,warn:$e.WARN,error:$e.ERROR,fatal:$e.FATAL};class To{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"&&wo?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){this.logsDir}shouldLog(s){return ms[s]>=ms[this.minLevel]}log(s,n,o){if(!this.shouldLog(s))return;const r={id:`log_${++No}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:n,...o&&{metadata:o}};if(So(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=ja.getLogger(this.service),a=rs.trace.getSpan(rs.context.active());i.emit({severityNumber:ko[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 me(t,s="debug"){return new To(t,s)}const ln=le(["user","assistant","system","tool"]),Io=le(["text","image","file","tool_call","tool_result"]),ct=q({type:Io}),Ro=ct.extend({type:ee("text"),text:w()}),_o=ct.extend({type:ee("image"),url:w().url().optional(),source:q({type:ee("base64"),media_type:le(["image/jpeg","image/png","image/gif","image/webp"]),data:w()}).optional()}),Mo=ct.extend({type:ee("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:F().optional()}),Eo=ct.extend({type:ee("tool_call"),id:w(),name:w(),arguments:ae(w(),ue())}),Ao=ct.extend({type:ee("tool_result"),callId:w(),result:ue(),error:w().optional()}),cn=it("type",[Ro,_o,Mo,Eo,Ao]),dn=q({id:w(),role:ln,content:te(cn),timestamp:vt(),metadata:ae(w(),ue()).optional()}),Po=q({type:ee("content"),id:w(),role:ln,contentDelta:cn,isComplete:Ce(),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()}),Do=q({type:ee("tool_call"),id:w(),toolCall:Ht(),messageId:w().optional()}),Uo=q({type:ee("tool_call_update"),id:w(),toolCallUpdate:Ht(),messageId:w().optional()}),Mt=le(["context_size","tool_response"]),zo=q({type:ee("hook_triggered"),hookType:Mt,threshold:F(),currentPercentage:F(),callback:w(),triggeredAt:F().optional(),toolCallId:w().optional()}),$o=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()}),Lo=q({type:ee("hook_error"),hookType:Mt,callback:w(),error:w(),completedAt:F().optional(),toolCallId:w().optional()}),Oo=it("type",[zo,$o,Lo]),Fo=q({type:ee("hook_notification"),id:w(),notification:Oo,messageId:w().optional()}),un=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),Bo=q({type:ee("sources"),sources:te(un)});it("type",[Po,Do,Uo,Fo,Bo]);const Ho=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),ps=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()}),Yt=le(["pending","in_progress","completed","failed"]),Wo=le(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),mn=q({path:w(),line:F().nullable().optional()}),Qt=q({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}),Gt=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()})]),pn=q({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),status:Yt,content:te(Gt).optional()}),Vo=it("type",[q({type:ee("text"),text:w()}),q({type:ee("tool_call"),toolCall:pn})]),fn=q({id:w(),content:w(),toolCalls:te(pn).optional(),contentBlocks:te(Vo).optional(),isStreaming:Ce().optional(),context_size:ps.optional(),_meta:q({semanticName:w().optional(),agentDefinitionName:w().optional(),currentActivity:w().optional(),statusGenerating:Ce().optional(),context_size:ps.optional()}).passthrough().optional()}),gn=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:Wo,status:Yt,contentPosition:F().optional(),locations:te(mn).optional(),rawInput:ae(w(),ue()).optional(),rawOutput:ae(w(),ue()).optional(),content:te(Gt).optional(),error:w().optional(),startedAt:F().optional(),completedAt:F().optional(),tokenUsage:Qt.optional(),_meta:q({truncationWarning:w().optional(),compactionAction:le(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(fn).optional(),subagentStreaming:Ce().optional(),subagentCompleted:Ce().optional()}),qo=q({id:w(),status:Yt.optional(),title:w().optional(),prettyName:w().optional(),icon:w().optional(),batchId:w().optional(),rawInput:ae(w(),ue()).optional(),locations:te(mn).optional(),rawOutput:ae(w(),ue()).optional(),content:te(Gt).optional(),error:w().optional(),completedAt:F().optional(),tokenUsage:Qt.optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(fn).optional(),subagentCompleted:Ce().optional(),_meta:q({truncationWarning:w().optional(),compactionAction:le(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional()});function fs(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 Ko=q({mimeType:w(),data:w()}),Yo=q({id:w(),hookType:Mt,callback:w(),status:le(["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()}),Qo=q({id:w(),role:le(["user","assistant","system"]),content:w(),timestamp:vt(),isStreaming:Ce().default(!1),streamingStartTime:F().optional(),metadata:ae(w(),ue()).optional(),toolCalls:te(gn).optional(),hookNotifications:te(Yo).optional(),tokenUsage:Qt.optional(),images:te(Ko).optional(),sources:te(Ho).optional()}),Go=q({value:w(),isSubmitting:Ce(),attachedFiles:te(q({name:w(),path:w(),size:F(),mimeType:w(),data:w()})),selectedPromptParameters:ae(w(),w()).optional()});q({sessionId:w().nullable(),isConnected:Ce(),isStreaming:Ce(),messages:te(Qo),input:Go,error:w().nullable()});le(["disconnected","connecting","connected","error"]);let gs=0,hs=0;function je(t){const s=Date.now();s!==hs&&(gs=0,hs=s);const n=gs++,o=Math.random().toString(36).substring(2,7);return`msg_${s}_${n}_${o}_${t}`}const Xo=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=me("http-transport");class Jo{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=Xo.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:ls,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:ls,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=_a.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,y=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,$=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(E=>{if(typeof E!="object"||E===null)return{type:"text",text:""};const _=E;if(_.type==="content"&&typeof _.content=="object"&&_.content!==null){const K=_.content;if(K.type==="text")return{type:"content",content:{type:"text",text:typeof K.text=="string"?K.text:""}}}return _.type==="text"?{type:"text",text:typeof _.text=="string"?_.text:""}:_.type==="diff"?{type:"diff",path:typeof _.path=="string"?_.path:"",oldText:typeof _.oldText=="string"?_.oldText:"",newText:typeof _.newText=="string"?_.newText:"",line:typeof _.line=="number"?_.line:null}:_.type==="terminal"?{type:"terminal",terminalId:typeof _.terminalId=="string"?_.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now(),subagentPort:h,subagentSessionId:f,subagentMessages:y,_meta:N||v||C||$||B?{compactionAction:N,originalTokens:v,finalTokens:C,originalContentPreview:$,originalContentPath:B}:void 0},I={type:"tool_call",sessionId:c,status:"active",toolCall:D,messageId:d},M=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:!!y,subagentMessagesCount:y?.length,isReplay:M,isInReplayMode:this.isInReplayMode}),M||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 E={type:"tool_call",id:c,toolCall:D,messageId:d},_=this.chunkResolvers.shift();_?_(E):this.messageQueue.push(E)}}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 y=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,$=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(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 _=E.content;if(_.type==="text")return{type:"content",content:{type:"text",text:typeof _.text=="string"?_.text:""}}}return E.type==="text"?{type:"text",text:typeof E.text=="string"?E.text:""}:E.type==="diff"?{type:"diff",path:typeof E.path=="string"?E.path:"",oldText:typeof E.oldText=="string"?E.oldText:"",newText:typeof E.newText=="string"?E.newText:"",line:typeof E.line=="number"?E.line:null}:E.type==="terminal"?{type:"terminal",terminalId:typeof E.terminalId=="string"?E.terminalId:""}:{type:"text",text:""}}),error:a.error,completedAt:a.status==="completed"||a.status==="failed"?Date.now():void 0,subagentPort:x,subagentSessionId:h,subagentMessages:f,_meta:y||N||v||C||$?{compactionAction:y,originalTokens:N,finalTokens:v,originalContentPreview:C,originalContentPath:$}: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 M={type:"tool_call_update",id:c,toolCallUpdate:D,messageId:d},E=this.chunkResolvers.shift();E?E(M):this.messageQueue.push(M)}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 y=h;let N=null;if(y.type==="text"&&typeof y.text=="string"&&(N={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:y.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 y.text=="string"&&(d||!this.isReceivingMessages)){const v={type:"generic",sessionId:c,status:"active",message:{id:je("assistant"),role:"assistant",content:[{type:"text",text:y.text}],timestamp:new Date().toISOString()}};d&&this.sessionUpdateCallbacks.size===0?(L.debug("Queueing assistant message for late-subscribing callbacks",{textLength:y.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:je("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 Zo{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 er{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=me("acp-client","debug");class tr{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:je("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 Zo(this.config.options);case"http":return new Jo(this.config.options);case"websocket":return new er(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=me("acp-client-hook");function sr(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 tr({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=me("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 nr=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=Na(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}),y=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:y?"✅":"❌",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:je("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=fs(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:je("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:je("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]=fs(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}))})),re=me("use-chat-session","debug");function Lt(t,s=!1){if(typeof window>"u"){re.debug("safeUpdateUrl: window is undefined, skipping");return}try{const n=new URL(window.location.href);n.searchParams.set("session",t);const o=n.toString();re.info("safeUpdateUrl: updating URL",{sessionId:t,useReplace:s,newUrl:o}),s?window.history.replaceState({},"",o):window.history.pushState({},"",o),re.info("safeUpdateUrl: URL updated successfully")}catch(n){re.warn("Failed to update URL with session ID",{sessionId:t,error:n instanceof Error?n.message:String(n)})}}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(y=>{const N=y._meta,v=N?.context_size||y.context_size;if(v!=null){const C=v;re.info("✅ Received context_size from session update",{context_size:C,totalEstimated:C.totalEstimated,isReplay:N?.isReplay}),m(C)}if(y.message&&(re.debug("Session update with message",{message:y.message}),y.message.role!=="tool")){const C=y.message.content.map(M=>M.type==="text"?M.text:"").join(""),$=[];for(const M of y.message.content)if(M.type==="image"){const E=M;E.source?.data?$.push({mimeType:E.source.media_type||"image/png",data:E.source.data}):E.data&&$.push({mimeType:E.mimeType||"image/png",data:E.data})}const B=H.getState().messages,D=B[B.length-1],I=N?.isReplay===!0;if(y.message.role==="assistant"&&D?.role==="assistant"&&C&&I)re.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(y.message.role==="assistant"&&D?.role==="assistant"&&D.content===""&&C)re.debug("Appending text to existing empty assistant message"),H.getState().updateMessage(D.id,{content:D.content+C});else{const M={id:y.message.id,role:y.message.role,content:C,timestamp:y.message.timestamp,isStreaming:!1,...$.length>0?{images:$}:{}};d(M)}}}):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();f?.id&&i(f.id),r("connected")}catch(f){re.error("Failed to connect",{error:f instanceof Error?f.message:String(f)});const y=f instanceof Error?f.message:String(f);a(y),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 y=await t.loadSession(f);i(y),r("connected"),re.info("Session loaded successfully",{sessionId:y})}catch(y){re.warn("Failed to load session, creating new one instead",{sessionId:f,error:y instanceof Error?y.message:String(y)});try{await p();const N=await t.startSession();i(N),c(),u(),Lt(N,!0),re.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();return i(f),H.getState().messages.length===0&&(c(),u()),Lt(f,!1),f}catch(f){const y=f instanceof Error?f.message:String(f);return a(y),null}},[t,i,a,c,u]),h=l.useCallback(async()=>{if(t)try{await t.disconnect(),r("disconnected"),i(null)}catch(f){const y=f instanceof Error?f.message:String(f);a(y)}},[t,r,i,a]);return l.useEffect(()=>{!t||n!=="disconnected"||(s?(re.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 Z=me("use-chat-messages","debug");function hn(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),y=H(I=>I.addSourcesByToolCallId),N=H(I=>I.truncateMessagesFrom),v=l.useRef(null),C=l.useRef(!1),$=l.useCallback(async(I,M,E)=>{if(Z.debug("[sendMessage] Called with",{contentLength:I.length,attachmentsCount:M?.length||0,hasAttachments:!!M&&M.length>0,hasPromptParameters:!!E,promptParameters:E}),!t){Z.error("No client available"),d("No client available");return}let _=r;if(!_){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}_=Y,Z.info("Session created successfully",{sessionId:Y})}const K=je("assistant");try{const Y=Date.now();i(!0),a(Y);const U={id:je("user"),role:"user",content:I,timestamp:new Date().toISOString(),isStreaming:!1,...M&&M.length>0?{images:M.filter(S=>S.mimeType.startsWith("image/")).map(S=>({mimeType:S.mimeType,data:S.data}))}:{}};c(U),typeof window<"u"&&_&&(new URL(window.location.href).searchParams.has("session")||(Z.info("Updating URL with session ID",{sessionId:_}),Lt(_,!1)));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,_,M,E).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(_,S.toolCall),x(S.toolCall)):S.type==="tool_call_update"?(Z.debug("Received tool_call_update chunk",{chunk:S}),g(_,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}),y(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 wa,c as et,h as ja}from"./react-DiSrVJhY.js";import{bb as $e,bc as Na,bd as rs,be as ce,bf as q,bg as w,bh as ee,bi as F,bj as oe,bk as ue,bl as it,bm as vt,bn as te,bo as Ne,bp as Ht,bq as Ca,br as Sa,bs as ka,bt as Ta,bu as Ie,bv as Ia,bw as pe,am as Ra,bx as _a,by as is}from"./vendor-Dm9xAZV8.js";import{P as ls,a as Ma}from"./acp-sdk-D4VsTV6L.js";import{S as ve,P as Ea,C as Ms,a as Aa,R as Pa,T as Da,b as Es,c as As,d as Ua,e as Ps,I as Ds,f as Us,g as zs,h as $s,L as Ls,i as Os,j as za,k as $a,l as Fs,m as Bs,n as Hs,o as La,O as Nt,p as Ws,q as Ct,r as Vs,s as St,D as kt,t as qs,u as Ks,v as Oa,w as Ys,x as Qs,y as Fa,z as Gs,V as Ba,A as Xs,B as Js,E as Ha,F as Wa,G as Zs}from"./radix-BaZ_UeJz.js";import{c as tt,d as lt,e as Tt,P as Va,E as qa,S as en,f as tn,g as Ka,h as Wt,i as Ya,j as Qa,k as Ga,l as Xa,m as ge,A as Ja,n as It,F as Za,o as eo,p as to,q as so,r as We,s as Rt,t as _t,G as sn,u as nn,v as an,B as cs,w as no,x as ao,y as oo,z as Vt,H as ro,I as qt,J as wt,T as io,K as de,N as lo,O as on,Q as ds,U as co,V as us,W as at,Y as Kt,_ as uo,$ as mo,a0 as po,a1 as fo,a2 as go,a3 as ho,a4 as xo,a5 as bo,a6 as yo,a7 as vo,a8 as wo}from"./icons-B0Ax5AoZ.js";import{A as ot,m as Te}from"./framer-motion-DEDjTHcO.js";import{g as rn}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 jo={};const ht=typeof process<"u"&&process.versions?.node;let No,Co=0;const $t=new Set;function So(t){return $t.add(t),()=>$t.delete(t)}function ko(t){for(const s of $t)s(t)}const ms={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},To={trace:$e.TRACE,debug:$e.DEBUG,info:$e.INFO,warn:$e.WARN,error:$e.ERROR,fatal:$e.FATAL};class Io{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"&&jo?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(s){this.logsDir}shouldLog(s){return ms[s]>=ms[this.minLevel]}log(s,n,o){if(!this.shouldLog(s))return;const r={id:`log_${++Co}`,timestamp:new Date().toISOString(),level:s,service:this.service,message:n,...o&&{metadata:o}};if(ko(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=Na.getLogger(this.service),a=rs.trace.getSpan(rs.context.active());i.emit({severityNumber:To[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 me(t,s="debug"){return new Io(t,s)}const ln=ce(["user","assistant","system","tool"]),Ro=ce(["text","image","file","tool_call","tool_result"]),ct=q({type:Ro}),_o=ct.extend({type:ee("text"),text:w()}),Mo=ct.extend({type:ee("image"),url:w().url().optional(),source:q({type:ee("base64"),media_type:ce(["image/jpeg","image/png","image/gif","image/webp"]),data:w()}).optional()}),Eo=ct.extend({type:ee("file"),name:w(),path:w().optional(),url:w().url().optional(),mimeType:w(),size:F().optional()}),Ao=ct.extend({type:ee("tool_call"),id:w(),name:w(),arguments:oe(w(),ue())}),Po=ct.extend({type:ee("tool_result"),callId:w(),result:ue(),error:w().optional()}),cn=it("type",[_o,Mo,Eo,Ao,Po]),dn=q({id:w(),role:ln,content:te(cn),timestamp:vt(),metadata:oe(w(),ue()).optional()}),Do=q({type:ee("content"),id:w(),role:ln,contentDelta:cn,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()}),Uo=q({type:ee("tool_call"),id:w(),toolCall:Ht(),messageId:w().optional()}),zo=q({type:ee("tool_call_update"),id:w(),toolCallUpdate:Ht(),messageId:w().optional()}),Mt=ce(["context_size","tool_response"]),$o=q({type:ee("hook_triggered"),hookType:Mt,threshold:F(),currentPercentage:F(),callback:w(),triggeredAt:F().optional(),toolCallId:w().optional()}),Lo=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()}),Oo=q({type:ee("hook_error"),hookType:Mt,callback:w(),error:w(),completedAt:F().optional(),toolCallId:w().optional()}),Fo=it("type",[$o,Lo,Oo]),Bo=q({type:ee("hook_notification"),id:w(),notification:Fo,messageId:w().optional()}),un=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),Ho=q({type:ee("sources"),sources:te(un)});it("type",[Do,Uo,zo,Bo,Ho]);const Wo=q({id:w(),url:w().url(),title:w(),snippet:w().optional(),favicon:w().optional(),toolCallId:w(),sourceName:w().optional()}),ps=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()}),Yt=ce(["pending","in_progress","completed","failed"]),Vo=ce(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),mn=q({path:w(),line:F().nullable().optional()}),Qt=q({inputTokens:F().optional(),outputTokens:F().optional(),totalTokens:F().optional()}),Gt=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()})]),pn=q({id:w(),title:w(),prettyName:w().optional(),icon:w().optional(),status:Yt,content:te(Gt).optional()}),qo=it("type",[q({type:ee("text"),text:w()}),q({type:ee("tool_call"),toolCall:pn})]),fn=q({id:w(),content:w(),toolCalls:te(pn).optional(),contentBlocks:te(qo).optional(),isStreaming:Ne().optional(),context_size:ps.optional(),_meta:q({semanticName:w().optional(),agentDefinitionName:w().optional(),currentActivity:w().optional(),statusGenerating:Ne().optional(),context_size:ps.optional()}).passthrough().optional()}),gn=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:Vo,status:Yt,contentPosition:F().optional(),locations:te(mn).optional(),rawInput:oe(w(),ue()).optional(),rawOutput:oe(w(),ue()).optional(),content:te(Gt).optional(),error:w().optional(),startedAt:F().optional(),completedAt:F().optional(),tokenUsage:Qt.optional(),_meta:q({truncationWarning:w().optional(),compactionAction:ce(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(fn).optional(),subagentStreaming:Ne().optional(),subagentCompleted:Ne().optional()}),Ko=q({id:w(),status:Yt.optional(),title:w().optional(),prettyName:w().optional(),icon:w().optional(),batchId:w().optional(),rawInput:oe(w(),ue()).optional(),locations:te(mn).optional(),rawOutput:oe(w(),ue()).optional(),content:te(Gt).optional(),error:w().optional(),completedAt:F().optional(),tokenUsage:Qt.optional(),subagentPort:F().optional(),subagentSessionId:w().optional(),subagentMessages:te(fn).optional(),subagentCompleted:Ne().optional(),_meta:q({truncationWarning:w().optional(),compactionAction:ce(["compacted","truncated"]).optional(),originalTokens:F().optional(),finalTokens:F().optional(),originalContentPreview:w().optional(),originalContentPath:w().optional()}).optional()});function fs(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 Yo=q({mimeType:w(),data:w()}),Qo=q({id:w(),hookType:Mt,callback:w(),status:ce(["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()}),Go=q({id:w(),role:ce(["user","assistant","system"]),content:w(),timestamp:vt(),isStreaming:Ne().default(!1),streamingStartTime:F().optional(),metadata:oe(w(),ue()).optional(),toolCalls:te(gn).optional(),hookNotifications:te(Qo).optional(),tokenUsage:Qt.optional(),images:te(Yo).optional(),sources:te(Wo).optional()}),Xo=q({value:w(),isSubmitting:Ne(),attachedFiles:te(q({name:w(),path:w(),size:F(),mimeType:w(),data:w()})),selectedPromptParameters:oe(w(),w()).optional()});q({sessionId:w().nullable(),isConnected:Ne(),isStreaming:Ne(),messages:te(Go),input:Xo,error:w().nullable()});ce(["disconnected","connecting","connected","error"]);let gs=0,hs=0;function we(t){const s=Date.now();s!==hs&&(gs=0,hs=s);const n=gs++,o=Math.random().toString(36).substring(2,7);return`msg_${s}_${n}_${o}_${t}`}const Jo=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:oe(w(),w()).optional()}),L=me("http-transport");class Zo{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=Jo.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:ls,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:ls,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=Ma.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,y=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,$=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(E=>{if(typeof E!="object"||E===null)return{type:"text",text:""};const _=E;if(_.type==="content"&&typeof _.content=="object"&&_.content!==null){const K=_.content;if(K.type==="text")return{type:"content",content:{type:"text",text:typeof K.text=="string"?K.text:""}}}return _.type==="text"?{type:"text",text:typeof _.text=="string"?_.text:""}:_.type==="diff"?{type:"diff",path:typeof _.path=="string"?_.path:"",oldText:typeof _.oldText=="string"?_.oldText:"",newText:typeof _.newText=="string"?_.newText:"",line:typeof _.line=="number"?_.line:null}:_.type==="terminal"?{type:"terminal",terminalId:typeof _.terminalId=="string"?_.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now(),subagentPort:h,subagentSessionId:f,subagentMessages:y,_meta:N||v||C||$||B?{compactionAction:N,originalTokens:v,finalTokens:C,originalContentPreview:$,originalContentPath:B}:void 0},I={type:"tool_call",sessionId:c,status:"active",toolCall:D,messageId:d},M=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:!!y,subagentMessagesCount:y?.length,isReplay:M,isInReplayMode:this.isInReplayMode}),M||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 E={type:"tool_call",id:c,toolCall:D,messageId:d},_=this.chunkResolvers.shift();_?_(E):this.messageQueue.push(E)}}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 y=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,$=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(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 _=E.content;if(_.type==="text")return{type:"content",content:{type:"text",text:typeof _.text=="string"?_.text:""}}}return E.type==="text"?{type:"text",text:typeof E.text=="string"?E.text:""}:E.type==="diff"?{type:"diff",path:typeof E.path=="string"?E.path:"",oldText:typeof E.oldText=="string"?E.oldText:"",newText:typeof E.newText=="string"?E.newText:"",line:typeof E.line=="number"?E.line:null}:E.type==="terminal"?{type:"terminal",terminalId:typeof E.terminalId=="string"?E.terminalId:""}:{type:"text",text:""}}),error:a.error,completedAt:a.status==="completed"||a.status==="failed"?Date.now():void 0,subagentPort:x,subagentSessionId:h,subagentMessages:f,_meta:y||N||v||C||$?{compactionAction:y,originalTokens:N,finalTokens:v,originalContentPreview:C,originalContentPath:$}: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 M={type:"tool_call_update",id:c,toolCallUpdate:D,messageId:d},E=this.chunkResolvers.shift();E?E(M):this.messageQueue.push(M)}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 y=h;let N=null;if(y.type==="text"&&typeof y.text=="string"&&(N={type:"content",id:s.sessionId,role:"assistant",contentDelta:{type:"text",text:y.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 y.text=="string"&&(d||!this.isReceivingMessages)){const v={type:"generic",sessionId:c,status:"active",message:{id:we("assistant"),role:"assistant",content:[{type:"text",text:y.text}],timestamp:new Date().toISOString()}};d&&this.sessionUpdateCallbacks.size===0?(L.debug("Queueing assistant message for late-subscribing callbacks",{textLength:y.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 er{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 tr{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=me("acp-client","debug");class sr{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 er(this.config.options);case"http":return new Zo(this.config.options);case"websocket":return new tr(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=me("acp-client-hook");function nr(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 sr({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=me("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 ar=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=Ca(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}),y=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:y?"✅":"❌",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=fs(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]=fs(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}))})),ie=me("use-chat-session","debug");function Lt(t,s=!1){if(typeof window>"u"){ie.debug("safeUpdateUrl: window is undefined, skipping");return}try{const n=new URL(window.location.href);n.searchParams.set("session",t);const o=n.toString();ie.info("safeUpdateUrl: updating URL",{sessionId:t,useReplace:s,newUrl:o}),s?window.history.replaceState({},"",o):window.history.pushState({},"",o),ie.info("safeUpdateUrl: URL updated successfully")}catch(n){ie.warn("Failed to update URL with session ID",{sessionId:t,error:n instanceof Error?n.message:String(n)})}}function or(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(y=>{const N=y._meta,v=N?.context_size||y.context_size;if(v!=null){const C=v;ie.info("✅ Received context_size from session update",{context_size:C,totalEstimated:C.totalEstimated,isReplay:N?.isReplay}),m(C)}if(y.message&&(ie.debug("Session update with message",{message:y.message}),y.message.role!=="tool")){const C=y.message.content.map(M=>M.type==="text"?M.text:"").join(""),$=[];for(const M of y.message.content)if(M.type==="image"){const E=M;E.source?.data?$.push({mimeType:E.source.media_type||"image/png",data:E.source.data}):E.data&&$.push({mimeType:E.mimeType||"image/png",data:E.data})}const B=H.getState().messages,D=B[B.length-1],I=N?.isReplay===!0;if(y.message.role==="assistant"&&D?.role==="assistant"&&C&&I)ie.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(y.message.role==="assistant"&&D?.role==="assistant"&&D.content===""&&C)ie.debug("Appending text to existing empty assistant message"),H.getState().updateMessage(D.id,{content:D.content+C});else{const M={id:y.message.id,role:y.message.role,content:C,timestamp:y.message.timestamp,isStreaming:!1,...$.length>0?{images:$}:{}};d(M)}}}):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();f?.id&&i(f.id),r("connected")}catch(f){ie.error("Failed to connect",{error:f instanceof Error?f.message:String(f)});const y=f instanceof Error?f.message:String(f);a(y),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 y=await t.loadSession(f);i(y),r("connected"),ie.info("Session loaded successfully",{sessionId:y})}catch(y){ie.warn("Failed to load session, creating new one instead",{sessionId:f,error:y instanceof Error?y.message:String(y)});try{await p();const N=await t.startSession();i(N),c(),u(),Lt(N,!0),ie.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();return i(f),H.getState().messages.length===0&&(c(),u()),Lt(f,!1),f}catch(f){const y=f instanceof Error?f.message:String(f);return a(y),null}},[t,i,a,c,u]),h=l.useCallback(async()=>{if(t)try{await t.disconnect(),r("disconnected"),i(null)}catch(f){const y=f instanceof Error?f.message:String(f);a(y)}},[t,r,i,a]);return l.useEffect(()=>{!t||n!=="disconnected"||(s?(ie.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 Z=me("use-chat-messages","debug");function hn(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),y=H(I=>I.addSourcesByToolCallId),N=H(I=>I.truncateMessagesFrom),v=l.useRef(null),C=l.useRef(!1),$=l.useCallback(async(I,M,E)=>{if(Z.debug("[sendMessage] Called with",{contentLength:I.length,attachmentsCount:M?.length||0,hasAttachments:!!M&&M.length>0,hasPromptParameters:!!E,promptParameters:E}),!t){Z.error("No client available"),d("No client available");return}let _=r;if(!_){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}_=Y,Z.info("Session created successfully",{sessionId:Y})}const K=we("assistant");try{const Y=Date.now();i(!0),a(Y);const U={id:we("user"),role:"user",content:I,timestamp:new Date().toISOString(),isStreaming:!1,...M&&M.length>0?{images:M.filter(S=>S.mimeType.startsWith("image/")).map(S=>({mimeType:S.mimeType,data:S.data}))}:{}};c(U),typeof window<"u"&&_&&(new URL(window.location.href).searchParams.has("session")||(Z.info("Updating URL with session ID",{sessionId:_}),Lt(_,!1)));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,_,M,E).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(_,S.toolCall),x(S.toolCall)):S.type==="tool_call_update"?(Z.debug("Received tool_call_update chunk",{chunk:S}),g(_,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}),y(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 U=Y instanceof Error?Y.message:String(Y);d(U),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,y]),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,E)=>{if(Z.debug("[editAndResend] Called with",{userMessageIndex:I,contentLength:M.length,attachmentsCount:E?.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 _=0,K=-1;for(let W=0;W<n.length;W++)if(n[W]?.role==="user"){if(_===I){K=W;break}_++}if(K===-1){Z.error("User message not found",{userMessageIndex:I,totalUserMessages:_}),d("User message not found");return}const Y=n[K];Z.debug("[editAndResend] Found target message",{userMessageIndex:I,targetArrayIndex:K,messageRole:Y?.role});const U=
|
|
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 U=Y instanceof Error?Y.message:String(Y);d(U),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,y]),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,E)=>{if(Z.debug("[editAndResend] Called with",{userMessageIndex:I,contentLength:M.length,attachmentsCount:E?.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 _=0,K=-1;for(let W=0;W<n.length;W++)if(n[W]?.role==="user"){if(_===I){K=W;break}_++}if(K===-1){Z.error("User message not found",{userMessageIndex:I,totalUserMessages:_}),d("User message not found");return}const Y=n[K];Z.debug("[editAndResend] Found target message",{userMessageIndex:I,targetArrayIndex:K,messageRole:Y?.role});const U=we("assistant");try{const W=Date.now();i(!0),a(W),N(K);const V={id:we("user"),role:"user",content:M,timestamp:new Date().toISOString(),isStreaming:!1,...E&&E.length>0?{images:E.filter(j=>j.mimeType.startsWith("image/")).map(j=>({mimeType:j.mimeType,data:j.data}))}:{}};c(V);const T={id:U,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:W};c(T),v.current=U,C.current=!1;const k=t.receiveMessages();t.editAndResend(I,M,r,E).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 z=Q;Z.info("✅ Received context_size from backend",{context_size:z,totalEstimated:z.totalEstimated}),m(z)}if(j.isComplete){u(U,{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(U,{content:S,...j.tokenUsage?{tokenUsage:j.tokenUsage}:{}}),document.hidden||await new Promise(z=>setTimeout(z,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}),y(j.sources))}P||(C.current?(Z.info("Stream cancelled by user"),u(U,{content:`${S}
|
|
5
5
|
|
|
6
|
-
[Cancelled]`,isStreaming:!1,streamingStartTime:void 0})):(Z.warn("Stream ended without isComplete flag"),u(U,{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(U,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,n,N,c,u,i,a,d,m,p,g,x,h,f,y]);return{messages:n,isStreaming:o,sendMessage:$,editAndResend:D,cancel:B}}const xs=me("use-chat-input","debug");function or(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}=hn(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;xs.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(y=>({input:{...y.input,attachedFiles:[]}}))}catch(y){xs.error("Failed to send message",{error:y instanceof Error?y.message:String(y)})}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 bs="town-message-history",rr=100;function ir(){const[t,s]=l.useState(-1),[n,o]=l.useState(""),r=l.useCallback(()=>{try{const m=localStorage.getItem(bs);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,rr);localStorage.setItem(bs,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=me("use-tool-calls","debug");function lr(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 cr=q({name:w(),description:w().optional(),parameters:ae(w(),ue()).optional()}),dr=q({name:w(),description:w(),parameters:ae(w(),ue()),required:te(w()).optional()}),ur=q({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:te(cr).optional(),tools:te(dr).optional(),supportedFormats:te(w()).optional()}),mr=le(["initializing","ready","busy","error","terminated"]);q({status:mr,info:ur.optional(),pid:F().optional(),error:w().optional(),uptime:F().optional()});const xn=le(["idle","connecting","connected","active","streaming","error","disconnected"]),pr=q({agentPath:w(),agentArgs:te(w()).optional(),environment:ae(w(),w()).optional(),workingDirectory:w().optional(),timeout:F().optional()}),fr=q({agentName:w().optional(),agentVersion:w().optional(),capabilities:te(w()).optional(),startedAt:vt(),lastActivityAt:vt().optional()});q({id:w(),status:xn,config:pr,metadata:fr.optional(),messages:te(dn),error:w().optional()});const dt=q({sessionId:w(),status:xn.optional(),message:dn.optional(),error:w().optional(),_meta:ae(w(),ue()).optional()}),gr=dt.extend({type:ee("tool_call"),toolCall:gn,messageId:w().optional()}),hr=dt.extend({type:ee("tool_call_update"),toolCallUpdate:qo,messageId:w().optional()}),xr=dt.extend({type:ee("tool_output"),toolOutput:q({id:w(),content:te(Ht()).optional(),rawOutput:ae(w(),ue()).optional()}),messageId:w().optional()}),br=dt.extend({type:ee("sources"),sources:te(un)}),yr=dt.extend({type:ee("generic").optional()});Ca([gr,hr,xr,br,yr]);const vr=[{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 wr{data;constructor(s=vr){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 b(...t){return Sa(ka(t))}const jr=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"}}),ie=l.forwardRef(({className:t,variant:s,size:n,asChild:o=!1,...r},i)=>{const a=o?ve:"button";return e.jsx(a,{className:b(jr({variant:s,size:n,className:t})),ref:i,...r})});ie.displayName="Button";const he=Ea,xe=Aa,be=Pa,ye=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(Ma,{children:e.jsx(Ms,{ref:o,sideOffset:s,className:b("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})}));ye.displayName=Ms.displayName;const Xt=({className:t,children:s,...n})=>e.jsx("div",{className:b("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(ie,{className:b("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(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:c}),e.jsx(ye,{children:e.jsx("p",{children:t})})]})}):c},Re=l.forwardRef(({className:t,...s},n)=>e.jsx(ie,{ref:n,variant:"ghost",size:"icon",className:b("rounded-full",t),...s}));Re.displayName="IconButton";const ut=Ua,mt=za,Nr=l.forwardRef(({className:t,inset:s,children:n,...o},r)=>e.jsxs(Es,{ref:r,className:b("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",s&&"pl-8",t),...o,children:[n,e.jsx(tt,{className:"ml-auto h-4 w-4"})]}));Nr.displayName=Es.displayName;const Cr=l.forwardRef(({className:t,...s},n)=>e.jsx(As,{ref:n,className:b("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...s}));Cr.displayName=As.displayName;const qe=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(Da,{children:e.jsx(Ps,{ref:o,sideOffset:s,className:b("z-50 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-popover p-0.5 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...n})}));qe.displayName=Ps.displayName;const Ne=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx(Ds,{ref:o,className:b("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...n}));Ne.displayName=Ds.displayName;const Sr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Us,{ref:o,className:b("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(zs,{children:e.jsx(lt,{className:"h-4 w-4"})})}),s]}));Sr.displayName=Us.displayName;const kr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs($s,{ref:o,className:b("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(zs,{children:e.jsx(Tt,{className:"h-2 w-2 fill-current"})})}),s]}));kr.displayName=$s.displayName;const Tr=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx(Ls,{ref:o,className:b("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...n}));Tr.displayName=Ls.displayName;const bn=l.forwardRef(({className:t,...s},n)=>e.jsx(Os,{ref:n,className:b("-mx-1 my-1 h-px bg-border",t),...s}));bn.displayName=Os.displayName;const Ir=256,Rr="calc(100vw - 104px)",yn=450,ys=250,vs=800,_r=720,Mr=56,Er=Mr*2;function vn(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 wn(){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]},Ar={duration:.25,ease:pt.smooth},ws={duration:.15,ease:pt.smooth},Pr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},Dr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},js={initial:{opacity:0,x:-20},animate:{opacity:1,x:0}},Ns={duration:.25,ease:pt.smooth,delay:.1},Ur={initial:{opacity:0},animate:{opacity:1},exit:{opacity:0}},zr={initial:{x:"100%"},animate:{x:0},exit:{x:"100%"}},$r={initial:{opacity:0,x:20},animate:{opacity:1,x:0}},Lr={duration:.25,ease:pt.smooth,delay:.1},Or={duration:.15,ease:pt.smooth},Fr=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"}}),jn=l.forwardRef(({className:t,type:s,variant:n,...o},r)=>e.jsx("input",{type:s,className:b(Fr({variant:n,className:t})),ref:r,...o}));jn.displayName="Input";const Br="sidebar_state",Hr=3600*24*7,Wr="s",Nn=l.createContext(null);function _e(){const t=l.useContext(Nn);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const Cn=l.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:n,className:o,style:r,children:i,...a},c)=>{const u=wn(),[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=`${Br}=${C}; path=/; max-age=${Hr}`},[n,x]),f=l.useCallback(()=>u?m(v=>!v):h(v=>!v),[u,h]);l.useEffect(()=>{const v=C=>{C.key.toLowerCase()===Wr&&C.shiftKey&&(C.metaKey||C.ctrlKey)&&(C.preventDefault(),f())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[f]);const y=x?"expanded":"collapsed",N=l.useMemo(()=>({state:y,open:x,setOpen:h,isMobile:u,openMobile:d,setOpenMobile:m,toggleSidebar:f}),[y,x,h,u,d,f]);return e.jsx(Nn.Provider,{value:N,children:e.jsx(he,{delayDuration:0,children:e.jsx("div",{className:b("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",o),ref:c,style:r,...a,children:i})})})});Cn.displayName="SidebarProvider";const Sn=l.forwardRef(({className:t,children:s},n)=>{const{isMobile:o,open:r,openMobile:i,setOpenMobile:a}=_e();return vn(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:Ur,initial:"initial",animate:"animate",exit:"exit",transition:ws,onClick:()=>a(!1),"aria-label":"Close sidebar"}),e.jsx(ke.aside,{ref:n,className:b("fixed inset-y-0 left-0 z-50","bg-sidebar text-sidebar-foreground","flex flex-col","border-r border-sidebar-border","max-h-screen overflow-hidden",t),style:{width:Rr},variants:Dr,initial:"initial",animate:"animate",exit:"exit",transition:ws,"data-sidebar":"sidebar","data-mobile":"true",children:e.jsx(ke.div,{className:"flex flex-col h-full overflow-y-auto",variants:js,initial:"initial",animate:"animate",transition:Ns,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:b("fixed inset-y-0 left-0 z-40","bg-sidebar text-sidebar-foreground","border-r border-sidebar-border","flex flex-col","max-h-screen overflow-hidden",t),style:{width:Ir},variants:Pr,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:js,initial:"initial",animate:"animate",transition:Ns,children:s})})})})});Sn.displayName="Sidebar";const Vr=l.forwardRef(({className:t,onClick:s,...n},o)=>{const{toggleSidebar:r}=_e();return e.jsxs(ie,{className:b("h-7 w-7",t),"data-sidebar":"trigger",onClick:i=>{s?.(i),r()},ref:o,size:"icon",variant:"ghost",...n,children:[e.jsx(Wa,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Vr.displayName="SidebarTrigger";const qr=l.forwardRef(({className:t,...s},n)=>{const{toggleSidebar:o}=_e();return e.jsx("button",{type:"button","aria-label":"Toggle Sidebar",className:b("-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:hover:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),"data-sidebar":"rail",onClick:o,ref:n,tabIndex:-1,title:"Toggle Sidebar",...s})});qr.displayName="SidebarRail";const kn=l.forwardRef(({className:t,children:s,...n},o)=>{const{isMobile:r,open:i}=_e();return e.jsx("main",{className:b("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})});kn.displayName="SidebarInset";const Kr=l.forwardRef(({className:t,...s},n)=>e.jsx(jn,{className:b("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),"data-sidebar":"input",ref:n,...s}));Kr.displayName="SidebarInput";const Tn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("flex flex-col gap-2 p-2",t),"data-sidebar":"header",ref:n,...s}));Tn.displayName="SidebarHeader";const In=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("flex flex-col gap-2 p-2",t),"data-sidebar":"footer",ref:n,...s}));In.displayName="SidebarFooter";const Yr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("mx-2 h-px w-auto bg-sidebar-border",t),"data-sidebar":"separator",ref:n,...s}));Yr.displayName="SidebarSeparator";const Rn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),"data-sidebar":"content",ref:n,...s}));Rn.displayName="SidebarContent";const Je=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("relative flex w-full min-w-0 flex-col p-4",t),"data-sidebar":"group",ref:n,...s}));Je.displayName="SidebarGroup";const _n=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ve:"div";return e.jsx(r,{className:b("flex h-8 shrink-0 items-center rounded-md px-2 font-medium text-sidebar-foreground/70 text-xs outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),"data-sidebar":"group-label",ref:o,...n})});_n.displayName="SidebarGroupLabel";const Qr=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ve:"button";return e.jsx(r,{className:b("absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"group-action",ref:o,type:"button",...n})});Qr.displayName="SidebarGroupAction";const Ze=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("w-full text-sm",t),"data-sidebar":"group-content",ref:n,...s}));Ze.displayName="SidebarGroupContent";const Mn=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:b("flex w-full min-w-0 flex-col gap-1",t),"data-sidebar":"menu",ref:n,...s}));Mn.displayName="SidebarMenu";const En=l.forwardRef(({className:t,...s},n)=>e.jsx("li",{className:b("group/menu-item relative",t),"data-sidebar":"menu-item",ref:n,...s}));En.displayName="SidebarMenuItem";const Gr=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?ve:"button",{isMobile:d,state:m}=_e(),p=e.jsx(u,{className:b(Gr({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(xe,{children:[e.jsx(be,{asChild:!0,children:p}),e.jsx(ye,{align:"center",hidden:m!=="collapsed"||d,side:"right",...r})]})):p});An.displayName="SidebarMenuButton";const Pn=l.forwardRef(({className:t,asChild:s=!1,showOnHover:n=!1,...o},r)=>{const i=s?ve:"button";return e.jsx(i,{className:b("absolute top-3 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-2.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",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})});Pn.displayName="SidebarMenuAction";const Xr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 font-medium text-sidebar-foreground text-xs tabular-nums","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-badge",ref:n,...s}));Xr.displayName="SidebarMenuBadge";const Jr=l.forwardRef(({className:t,showIcon:s=!1,...n},o)=>{const r=l.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{className:b("flex h-8 items-center gap-2 rounded-md px-2",t),"data-sidebar":"menu-skeleton",ref: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}})]})});Jr.displayName="SidebarMenuSkeleton";const Zr=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:b("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-sub",ref:n,...s}));Zr.displayName="SidebarMenuSub";const ei=l.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));ei.displayName="SidebarMenuSubItem";const ti=l.forwardRef(({asChild:t=!1,size:s="md",isActive:n,className:o,...r},i)=>{const a=t?ve:"a";return e.jsx(a,{className:b("-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",s==="sm"&&"text-xs",s==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",o),"data-active":n,"data-sidebar":"menu-sub-button","data-size":s,ref:i,...r})});ti.displayName="SidebarMenuSubButton";const si=({session:t,isActive:s,onSelect:n,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a})=>e.jsxs(En,{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(Pn,{className:"mr-0.5 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",showOnHover:!s,children:[e.jsx(Va,{}),e.jsx("span",{className:"sr-only",children:"More"})]})}),e.jsxs(qe,{align:"end",side:"bottom",children:[e.jsx(Ne,{className:"cursor-pointer",disabled:!o,onSelect:()=>o?.(t.sessionId),children:"Rename"}),e.jsx(Ne,{className:"cursor-pointer",disabled:!r,onSelect:()=>r?.(t.sessionId),children:"Archive"}),e.jsx(bn,{}),e.jsx(Ne,{className:b("cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive"),disabled:!i,onSelect:()=>i?.(t.sessionId),children:"Delete"})]})]})]}),Ye=l.memo(si,(t,s)=>!(t.isActive!==s.isActive||t.session.sessionId!==s.session.sessionId||t.session.firstUserMessage!==s.session.firstUserMessage)),ni=me("session-history"),ai=t=>{const s=new Date;return t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},oi=t=>{const s=new Date;return s.setDate(s.getDate()-1),t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},ri=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 ai(a)?r.today.push(i):oi(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 ii({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(y=>!y.isSubagentSession);u(f)}catch(h){ni.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(_n,{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=ri(c);return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx(Mn,{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 li={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Dn=l.createContext(li);function ci({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(Dn.Provider,{value:c,children:t})}const Jt=()=>{const t=l.useContext(Dn);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function di(){const{setTheme:t}=Jt();return e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsxs(Re,{children:[e.jsx(en,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(tn,{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(Ne,{onClick:()=>t("light"),children:"Light"}),e.jsx(Ne,{onClick:()=>t("dark"),children:"Dark"}),e.jsx(Ne,{onClick:()=>t("system"),children:"System"})]})]})}function ui({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(Sn,{className:b("group-data-[side=left]:border-r-0",c),children:[e.jsx(Tn,{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(qa,{className:"size-4"})})]})}),e.jsx(Rn,{className:"gap-6",children:e.jsx(ii,{client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:r,onArchiveSession:i,onDeleteSession:a})}),e.jsx(In,{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(di,{}),e.jsx(Re,{"aria-label":"Settings",children:e.jsx(Wt,{className:"size-4 text-muted-foreground"})})]})})]})}const mi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));mi.displayName="Card";const pi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("flex flex-col space-y-1.5 p-6",t),...s}));pi.displayName="CardHeader";const fi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("text-2xl font-semibold leading-none tracking-tight",t),...s}));fi.displayName="CardTitle";const gi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("text-sm text-muted-foreground",t),...s}));gi.displayName="CardDescription";const hi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("p-6 pt-0",t),...s}));hi.displayName="CardContent";const xi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("flex items-center p-6 pt-0",t),...s}));xi.displayName="CardFooter";const Un=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 y=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:b("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($=>e.jsx("button",{type:"button",onClick:()=>y($),onMouseEnter:()=>p?.($),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:$})},$))},C.join("-")))})]})]})});Un.displayName="ChatEmptyState";const zn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex items-center justify-between",t),...n,children:s}));zn.displayName="ChatHeader.Root";const bi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("h1",{ref:o,className:b("m-0 text-subheading font-semibold",t),...n,children:s}));bi.displayName="ChatHeader.Title";const yi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex items-center gap-3",t),...n,children:s}));yi.displayName="ChatHeader.Actions";const $n=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,y)=>{const N=f.toLowerCase(),v=y.toLowerCase();if(!y)return 1;if(N.includes(v))return 1-v.length/N.length;let C=0;for(let $=0;$<N.length&&C<v.length;$++)N[$]===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,y)=>y.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:b("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",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,y)=>e.jsxs("button",{type:"button",onClick:()=>{f.onSelect(),c(""),u?.()},className:b("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",y===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))})]})});$n.displayName="ChatInputCommandMenu";const Ln=l.createContext(void 0),ft=()=>{const t=l.useContext(Ln);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},On=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=or(t??null,s??h),y=H(R=>R.isStreaming),{addToHistory:N,navigatePrevious:v,navigateNext:C,resetNavigation:$}=ir(),B=t&&s,D=B?f.value:n||"",I=B?f.onChange:o||(()=>{}),M=B?f.onSubmit:r||(async()=>{}),E=B?f.isSubmitting||y:c||!1,_=l.useCallback(async()=>{const R=D.trim();R&&N(R),await M()},[D,N,M]),[K,Y]=l.useState(!1),[U,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()&&!E&&!a&&(await _(),setTimeout(()=>{x.current?.focus()},0))},z=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(Ln.Provider,{value:{value:D,onChange:I,onSubmit:_,onCancel:i,disabled:a,isSubmitting:E,submitOnEnter:u,showCommandMenu:K,setShowCommandMenu:Y,commandMenuQuery:U,setCommandMenuQuery:W,selectedMenuIndex:V,setSelectedMenuIndex:T,menuItemCount:k,setMenuItemCount:S,triggerMenuSelect:O,triggerCounter:P,navigateHistoryPrevious:v,navigateHistoryNext:C,resetHistoryNavigation:$},children:e.jsx("form",{ref:g,onSubmit:Q,onClick:z,onKeyDown:X,className:b("relative w-full divide-y rounded-xl border bg-background shadow-md",d),...p,children:m})})});On.displayName="ChatInput.Root";const Fn=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:y,menuItemCount:N,triggerMenuSelect:v,navigateHistoryPrevious:C,navigateHistoryNext:$,resetHistoryNavigation:B}=ft(),D=l.useRef(null),[I,M]=l.useState(!1),E=l.useCallback(k=>{D.current=k,typeof a=="function"?a(k):a&&(a.current=k)},[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:E,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(U,{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(U,{isStreaming:!1,streamingStartTime:void 0})}},[t,r,n,N,c,u,i,a,d,m,p,g,x,h,f,y]);return{messages:n,isStreaming:o,sendMessage:$,editAndResend:D,cancel:B}}const xs=me("use-chat-input","debug");function rr(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}=hn(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;xs.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(y=>({input:{...y.input,attachedFiles:[]}}))}catch(y){xs.error("Failed to send message",{error:y instanceof Error?y.message:String(y)})}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 bs="town-message-history",ir=100;function lr(){const[t,s]=l.useState(-1),[n,o]=l.useState(""),r=l.useCallback(()=>{try{const m=localStorage.getItem(bs);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,ir);localStorage.setItem(bs,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=me("use-tool-calls","debug");function cr(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 dr=q({name:w(),description:w().optional(),parameters:oe(w(),ue()).optional()}),ur=q({name:w(),description:w(),parameters:oe(w(),ue()),required:te(w()).optional()}),mr=q({name:w(),version:w().optional(),description:w().optional(),author:w().optional(),capabilities:te(dr).optional(),tools:te(ur).optional(),supportedFormats:te(w()).optional()}),pr=ce(["initializing","ready","busy","error","terminated"]);q({status:pr,info:mr.optional(),pid:F().optional(),error:w().optional(),uptime:F().optional()});const xn=ce(["idle","connecting","connected","active","streaming","error","disconnected"]),fr=q({agentPath:w(),agentArgs:te(w()).optional(),environment:oe(w(),w()).optional(),workingDirectory:w().optional(),timeout:F().optional()}),gr=q({agentName:w().optional(),agentVersion:w().optional(),capabilities:te(w()).optional(),startedAt:vt(),lastActivityAt:vt().optional()});q({id:w(),status:xn,config:fr,metadata:gr.optional(),messages:te(dn),error:w().optional()});const dt=q({sessionId:w(),status:xn.optional(),message:dn.optional(),error:w().optional(),_meta:oe(w(),ue()).optional()}),hr=dt.extend({type:ee("tool_call"),toolCall:gn,messageId:w().optional()}),xr=dt.extend({type:ee("tool_call_update"),toolCallUpdate:Ko,messageId:w().optional()}),br=dt.extend({type:ee("tool_output"),toolOutput:q({id:w(),content:te(Ht()).optional(),rawOutput:oe(w(),ue()).optional()}),messageId:w().optional()}),yr=dt.extend({type:ee("sources"),sources:te(un)}),vr=dt.extend({type:ee("generic").optional()});Sa([hr,xr,br,yr,vr]);const wr=[{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 jr{data;constructor(s=wr){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 b(...t){return ka(Ta(t))}const Nr=Ie("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"}}),le=l.forwardRef(({className:t,variant:s,size:n,asChild:o=!1,...r},i)=>{const a=o?ve:"button";return e.jsx(a,{className:b(Nr({variant:s,size:n,className:t})),ref:i,...r})});le.displayName="Button";const he=Aa,xe=Pa,be=Da,ye=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(Ea,{children:e.jsx(Ms,{ref:o,sideOffset:s,className:b("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})}));ye.displayName=Ms.displayName;const Xt=({className:t,children:s,...n})=>e.jsx("div",{className:b("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(le,{className:b("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(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:c}),e.jsx(ye,{children:e.jsx("p",{children:t})})]})}):c},_e=l.forwardRef(({className:t,...s},n)=>e.jsx(le,{ref:n,variant:"ghost",size:"icon",className:b("rounded-full",t),...s}));_e.displayName="IconButton";const ut=za,mt=$a,Cr=l.forwardRef(({className:t,inset:s,children:n,...o},r)=>e.jsxs(Es,{ref:r,className:b("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",s&&"pl-8",t),...o,children:[n,e.jsx(tt,{className:"ml-auto h-4 w-4"})]}));Cr.displayName=Es.displayName;const Sr=l.forwardRef(({className:t,...s},n)=>e.jsx(As,{ref:n,className:b("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...s}));Sr.displayName=As.displayName;const qe=l.forwardRef(({className:t,sideOffset:s=4,...n},o)=>e.jsx(Ua,{children:e.jsx(Ps,{ref:o,sideOffset:s,className:b("z-50 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-popover p-0.5 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",t),...n})}));qe.displayName=Ps.displayName;const je=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx(Ds,{ref:o,className:b("relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...n}));je.displayName=Ds.displayName;const kr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Us,{ref:o,className:b("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(zs,{children:e.jsx(lt,{className:"h-4 w-4"})})}),s]}));kr.displayName=Us.displayName;const Tr=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs($s,{ref:o,className:b("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(zs,{children:e.jsx(Tt,{className:"h-2 w-2 fill-current"})})}),s]}));Tr.displayName=$s.displayName;const Ir=l.forwardRef(({className:t,inset:s,...n},o)=>e.jsx(Ls,{ref:o,className:b("px-2 py-1.5 text-paragraph-sm font-semibold",s&&"pl-8",t),...n}));Ir.displayName=Ls.displayName;const bn=l.forwardRef(({className:t,...s},n)=>e.jsx(Os,{ref:n,className:b("-mx-1 my-1 h-px bg-border",t),...s}));bn.displayName=Os.displayName;const Rr=256,_r="calc(100vw - 104px)",yn=450,ys=250,vs=800,Mr=720,Er=56,Ar=Er*2;function vn(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 wn(){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]},Pr={duration:.25,ease:pt.smooth},ws={duration:.15,ease:pt.smooth},Dr={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},Ur={initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"}},js={initial:{opacity:0,x:-20},animate:{opacity:1,x:0}},Ns={duration:.25,ease:pt.smooth,delay:.1},zr={initial:{opacity:0},animate:{opacity:1},exit:{opacity:0}},$r={initial:{x:"100%"},animate:{x:0},exit:{x:"100%"}},Lr={initial:{opacity:0,x:20},animate:{opacity:1,x:0}},Or={duration:.25,ease:pt.smooth,delay:.1},Fr={duration:.15,ease:pt.smooth},Br=Ie("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"}}),jn=l.forwardRef(({className:t,type:s,variant:n,...o},r)=>e.jsx("input",{type:s,className:b(Br({variant:n,className:t})),ref:r,...o}));jn.displayName="Input";const Hr="sidebar_state",Wr=3600*24*7,Vr="s",Nn=l.createContext(null);function Me(){const t=l.useContext(Nn);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}const Cn=l.forwardRef(({defaultOpen:t=!0,open:s,onOpenChange:n,className:o,style:r,children:i,...a},c)=>{const u=wn(),[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=`${Hr}=${C}; path=/; max-age=${Wr}`},[n,x]),f=l.useCallback(()=>u?m(v=>!v):h(v=>!v),[u,h]);l.useEffect(()=>{const v=C=>{C.key.toLowerCase()===Vr&&C.shiftKey&&(C.metaKey||C.ctrlKey)&&(C.preventDefault(),f())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[f]);const y=x?"expanded":"collapsed",N=l.useMemo(()=>({state:y,open:x,setOpen:h,isMobile:u,openMobile:d,setOpenMobile:m,toggleSidebar:f}),[y,x,h,u,d,f]);return e.jsx(Nn.Provider,{value:N,children:e.jsx(he,{delayDuration:0,children:e.jsx("div",{className:b("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",o),ref:c,style:r,...a,children:i})})})});Cn.displayName="SidebarProvider";const Sn=l.forwardRef(({className:t,children:s},n)=>{const{isMobile:o,open:r,openMobile:i,setOpenMobile:a}=Me();return vn(o&&i),o?e.jsx(ot,{initial:!1,children:i&&e.jsxs(e.Fragment,{children:[e.jsx(Te.div,{className:"fixed inset-0 z-40 bg-background/80",variants:zr,initial:"initial",animate:"animate",exit:"exit",transition:ws,onClick:()=>a(!1),"aria-label":"Close sidebar"}),e.jsx(Te.aside,{ref:n,className:b("fixed inset-y-0 left-0 z-50","bg-sidebar text-sidebar-foreground","flex flex-col","border-r border-sidebar-border","max-h-screen overflow-hidden",t),style:{width:_r},variants:Ur,initial:"initial",animate:"animate",exit:"exit",transition:ws,"data-sidebar":"sidebar","data-mobile":"true",children:e.jsx(Te.div,{className:"flex flex-col h-full overflow-y-auto",variants:js,initial:"initial",animate:"animate",transition:Ns,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(Te.aside,{className:b("fixed inset-y-0 left-0 z-40","bg-sidebar text-sidebar-foreground","border-r border-sidebar-border","flex flex-col","max-h-screen overflow-hidden",t),style:{width:Rr},variants:Dr,initial:"initial",animate:"animate",exit:"exit",transition:Pr,"data-sidebar":"sidebar",children:e.jsx(Te.div,{className:"flex flex-col h-full overflow-y-auto",variants:js,initial:"initial",animate:"animate",transition:Ns,children:s})})})})});Sn.displayName="Sidebar";const qr=l.forwardRef(({className:t,onClick:s,...n},o)=>{const{toggleSidebar:r}=Me();return e.jsxs(le,{className:b("h-7 w-7",t),"data-sidebar":"trigger",onClick:i=>{s?.(i),r()},ref:o,size:"icon",variant:"ghost",...n,children:[e.jsx(Va,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});qr.displayName="SidebarTrigger";const Kr=l.forwardRef(({className:t,...s},n)=>{const{toggleSidebar:o}=Me();return e.jsx("button",{type:"button","aria-label":"Toggle Sidebar",className:b("-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:hover:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),"data-sidebar":"rail",onClick:o,ref:n,tabIndex:-1,title:"Toggle Sidebar",...s})});Kr.displayName="SidebarRail";const kn=l.forwardRef(({className:t,children:s,...n},o)=>{const{isMobile:r,open:i}=Me();return e.jsx("main",{className:b("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})});kn.displayName="SidebarInset";const Yr=l.forwardRef(({className:t,...s},n)=>e.jsx(jn,{className:b("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),"data-sidebar":"input",ref:n,...s}));Yr.displayName="SidebarInput";const Tn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("flex flex-col gap-2 p-2",t),"data-sidebar":"header",ref:n,...s}));Tn.displayName="SidebarHeader";const In=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("flex flex-col gap-2 p-2",t),"data-sidebar":"footer",ref:n,...s}));In.displayName="SidebarFooter";const Qr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("mx-2 h-px w-auto bg-sidebar-border",t),"data-sidebar":"separator",ref:n,...s}));Qr.displayName="SidebarSeparator";const Rn=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),"data-sidebar":"content",ref:n,...s}));Rn.displayName="SidebarContent";const Je=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("relative flex w-full min-w-0 flex-col p-4",t),"data-sidebar":"group",ref:n,...s}));Je.displayName="SidebarGroup";const _n=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ve:"div";return e.jsx(r,{className:b("flex h-8 shrink-0 items-center rounded-md px-2 font-medium text-sidebar-foreground/70 text-xs outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),"data-sidebar":"group-label",ref:o,...n})});_n.displayName="SidebarGroupLabel";const Gr=l.forwardRef(({className:t,asChild:s=!1,...n},o)=>{const r=s?ve:"button";return e.jsx(r,{className:b("absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"group-action",ref:o,type:"button",...n})});Gr.displayName="SidebarGroupAction";const Ze=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("w-full text-sm",t),"data-sidebar":"group-content",ref:n,...s}));Ze.displayName="SidebarGroupContent";const Mn=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:b("flex w-full min-w-0 flex-col gap-1",t),"data-sidebar":"menu",ref:n,...s}));Mn.displayName="SidebarMenu";const En=l.forwardRef(({className:t,...s},n)=>e.jsx("li",{className:b("group/menu-item relative",t),"data-sidebar":"menu-item",ref:n,...s}));En.displayName="SidebarMenuItem";const Xr=Ie("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?ve:"button",{isMobile:d,state:m}=Me(),p=e.jsx(u,{className:b(Xr({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(xe,{children:[e.jsx(be,{asChild:!0,children:p}),e.jsx(ye,{align:"center",hidden:m!=="collapsed"||d,side:"right",...r})]})):p});An.displayName="SidebarMenuButton";const Pn=l.forwardRef(({className:t,asChild:s=!1,showOnHover:n=!1,...o},r)=>{const i=s?ve:"button";return e.jsx(i,{className:b("absolute top-3 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:-inset-2 after:absolute after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-2.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",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})});Pn.displayName="SidebarMenuAction";const Jr=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{className:b("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 font-medium text-sidebar-foreground text-xs tabular-nums","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-badge",ref:n,...s}));Jr.displayName="SidebarMenuBadge";const Zr=l.forwardRef(({className:t,showIcon:s=!1,...n},o)=>{const r=l.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{className:b("flex h-8 items-center gap-2 rounded-md px-2",t),"data-sidebar":"menu-skeleton",ref: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}})]})});Zr.displayName="SidebarMenuSkeleton";const ei=l.forwardRef(({className:t,...s},n)=>e.jsx("ul",{className:b("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),"data-sidebar":"menu-sub",ref:n,...s}));ei.displayName="SidebarMenuSub";const ti=l.forwardRef(({...t},s)=>e.jsx("li",{ref:s,...t}));ti.displayName="SidebarMenuSubItem";const si=l.forwardRef(({asChild:t=!1,size:s="md",isActive:n,className:o,...r},i)=>{const a=t?ve:"a";return e.jsx(a,{className:b("-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",s==="sm"&&"text-xs",s==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",o),"data-active":n,"data-sidebar":"menu-sub-button","data-size":s,ref:i,...r})});si.displayName="SidebarMenuSubButton";const ni=({session:t,isActive:s,onSelect:n,onRename:o,onArchive:r,onDelete:i,setOpenMobile:a})=>e.jsxs(En,{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(Pn,{className:"mr-0.5 data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",showOnHover:!s,children:[e.jsx(qa,{}),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(bn,{}),e.jsx(je,{className:b("cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive"),disabled:!i,onSelect:()=>i?.(t.sessionId),children:"Delete"})]})]})]}),Ye=l.memo(ni,(t,s)=>!(t.isActive!==s.isActive||t.session.sessionId!==s.session.sessionId||t.session.firstUserMessage!==s.session.firstUserMessage)),ai=me("session-history"),oi=t=>{const s=new Date;return t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},ri=t=>{const s=new Date;return s.setDate(s.getDate()-1),t.getDate()===s.getDate()&&t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear()},ii=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 oi(a)?r.today.push(i):ri(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 li({client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:o,onArchiveSession:r,onDeleteSession:i}){const{setOpenMobile:a}=Me(),[c,u]=l.useState([]),[d,m]=l.useState(!1),p=l.useCallback(async()=>{if(t){m(!0);try{const f=(await t.listSessions()).filter(y=>!y.isSubagentSession);u(f)}catch(h){ai.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(_n,{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=ii(c);return e.jsx(Je,{children:e.jsx(Ze,{children:e.jsx(Mn,{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 ci={theme:"system",setTheme:()=>null,resolvedTheme:"light"},Dn=l.createContext(ci);function di({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(Dn.Provider,{value:c,children:t})}const Jt=()=>{const t=l.useContext(Dn);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function ui(){const{setTheme:t}=Jt();return e.jsxs(ut,{children:[e.jsx(mt,{asChild:!0,children:e.jsxs(_e,{children:[e.jsx(en,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(tn,{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 mi({client:t,currentSessionId:s,onSessionSelect:n,onNewSession:o,onRenameSession:r,onArchiveSession:i,onDeleteSession:a,className:c}){const{setOpenMobile:u}=Me(),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(Sn,{className:b("group-data-[side=left]:border-r-0",c),children:[e.jsx(Tn,{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(_e,{onClick:d,"aria-label":"New Chat",variant:"default",children:e.jsx(Ka,{className:"size-4"})})]})}),e.jsx(Rn,{className:"gap-6",children:e.jsx(li,{client:t,currentSessionId:s,onSessionSelect:n,onRenameSession:r,onArchiveSession:i,onDeleteSession:a})}),e.jsx(In,{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(ui,{}),e.jsx(_e,{"aria-label":"Settings",children:e.jsx(Wt,{className:"size-4 text-muted-foreground"})})]})})]})}const pi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));pi.displayName="Card";const fi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("flex flex-col space-y-1.5 p-6",t),...s}));fi.displayName="CardHeader";const gi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("text-2xl font-semibold leading-none tracking-tight",t),...s}));gi.displayName="CardTitle";const hi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("text-sm text-muted-foreground",t),...s}));hi.displayName="CardDescription";const xi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("p-6 pt-0",t),...s}));xi.displayName="CardContent";const bi=l.forwardRef(({className:t,...s},n)=>e.jsx("div",{ref:n,className:b("flex items-center p-6 pt-0",t),...s}));bi.displayName="CardFooter";const Un=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 y=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:b("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($=>e.jsx("button",{type:"button",onClick:()=>y($),onMouseEnter:()=>p?.($),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:$})},$))},C.join("-")))})]})]})});Un.displayName="ChatEmptyState";const zn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex items-center justify-between",t),...n,children:s}));zn.displayName="ChatHeader.Root";const yi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("h1",{ref:o,className:b("m-0 text-subheading font-semibold",t),...n,children:s}));yi.displayName="ChatHeader.Title";const vi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex items-center gap-3",t),...n,children:s}));vi.displayName="ChatHeader.Actions";const $n=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,y)=>{const N=f.toLowerCase(),v=y.toLowerCase();if(!y)return 1;if(N.includes(v))return 1-v.length/N.length;let C=0;for(let $=0;$<N.length&&C<v.length;$++)N[$]===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,y)=>y.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:b("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",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,y)=>e.jsxs("button",{type:"button",onClick:()=>{f.onSelect(),c(""),u?.()},className:b("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",y===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))})]})});$n.displayName="ChatInputCommandMenu";const Ln=l.createContext(void 0),ft=()=>{const t=l.useContext(Ln);if(!t)throw new Error("ChatInput components must be used within ChatInput.Root");return t},On=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=rr(t??null,s??h),y=H(R=>R.isStreaming),{addToHistory:N,navigatePrevious:v,navigateNext:C,resetNavigation:$}=lr(),B=t&&s,D=B?f.value:n||"",I=B?f.onChange:o||(()=>{}),M=B?f.onSubmit:r||(async()=>{}),E=B?f.isSubmitting||y:c||!1,_=l.useCallback(async()=>{const R=D.trim();R&&N(R),await M()},[D,N,M]),[K,Y]=l.useState(!1),[U,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()&&!E&&!a&&(await _(),setTimeout(()=>{x.current?.focus()},0))},z=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(Ln.Provider,{value:{value:D,onChange:I,onSubmit:_,onCancel:i,disabled:a,isSubmitting:E,submitOnEnter:u,showCommandMenu:K,setShowCommandMenu:Y,commandMenuQuery:U,setCommandMenuQuery:W,selectedMenuIndex:V,setSelectedMenuIndex:T,menuItemCount:k,setMenuItemCount:S,triggerMenuSelect:O,triggerCounter:P,navigateHistoryPrevious:v,navigateHistoryNext:C,resetHistoryNavigation:$},children:e.jsx("form",{ref:g,onSubmit:Q,onClick:z,onKeyDown:X,className:b("relative w-full divide-y rounded-xl border bg-background shadow-md",d),...p,children:m})})});On.displayName="ChatInput.Root";const Fn=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:y,menuItemCount:N,triggerMenuSelect:v,navigateHistoryPrevious:C,navigateHistoryNext:$,resetHistoryNavigation:B}=ft(),D=l.useRef(null),[I,M]=l.useState(!1),E=l.useCallback(k=>{D.current=k,typeof a=="function"?a(k):a&&(a.current=k)},[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:E,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(),y(S=>(S+1)%N);return}else if(k.key==="ArrowUp"){k.preventDefault(),y(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=$();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(),M(!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 _(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(),M(!0)},onDragLeave:k=>{k.preventDefault(),M(!1)},disabled:m,...i};return t&&l.isValidElement(r)?l.cloneElement(r,T):e.jsx("textarea",{...T,rows:1,className:b("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 max-h-[6lh] min-h-[44px]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-paragraph-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",I&&"ring-2 ring-primary ring-offset-2",s)})});Fn.displayName="ChatInput.Field";const Bn=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?ve:ie;return e.jsx(m,{ref:i,type:"submit",disabled:d,variant:t?void 0:"default",size:"icon",className:b(!t&&"gap-1.5 rounded-full",s),...r,children:o})});Bn.displayName="ChatInput.Submit";const Hn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const{onCancel:i,isSubmitting:a}=ft(),c=t?ve:ie;return a?e.jsx(c,{ref:r,type:"button",onClick:()=>i?.(),variant:t?void 0:"default",size:"icon",className:b(!t&&"gap-1.5 rounded-full",s),...o,children:n||e.jsx(Ka,{className:"size-4 fill-current"})}):null});Hn.displayName="ChatInput.Stop";const Wn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex items-center justify-between p-2",t),...n,children:s}));Wn.displayName="ChatInput.Toolbar";const Vn=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?ve:ie;return e.jsx(p,{ref:i,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),onClick:m,...r,children:n||e.jsx(Ya,{className:"size-4"})})});Vn.displayName="ChatInput.Actions";const qn=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?ve:ie;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:b("rounded-full",s),onClick:d,...r,children:n||e.jsx(Qa,{className:"size-4"})})]})});qn.displayName="ChatInput.Attachment";const Kn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const i=t?ve:ie;return e.jsx(i,{ref:r,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),...o,children:n||e.jsx(Ga,{className:"size-4"})})});Kn.displayName="ChatInput.VoiceInput";const Yn=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($n,{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})});Yn.displayName="ChatInput.CommandMenu";function vi({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:b("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:b("inline-flex h-10 items-center gap-1.5 rounded-full px-3","text-sm font-medium transition-colors","focus:outline-none focus-visible:ring-1 focus-visible:ring-ring",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(ge,{className:"h-4 w-4 opacity-50"})]})}),e.jsx(qe,{align:"start",className:"min-w-[160px]",children:c.options.map(m=>e.jsx(Ne,{onClick:()=>i(c.id,m.id),className:b(n?.[c.id]===m.id&&"bg-accent"),children:m.label},m.id))})]},c.id))})}function wi(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 ji(){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),y=l.useRef(null);l.useEffect(()=>{r.current=n},[n]);const N=l.useCallback(()=>{if(!t.current)return!0;const{scrollTop:U,scrollHeight:W,clientHeight:V}=t.current;return U+V>=W-100},[]),v=l.useCallback(()=>{if(!t.current)return[];const U=t.current.querySelectorAll('[aria-label="user message"]');return Array.from(U)},[]),C=l.useCallback(()=>{const U=t.current;if(!U)return[];const W=U.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]),$=l.useCallback((U,W="smooth")=>{const V=v();if(U<0||U>=V.length)return;const T=V[U];if(T){f.current=!0,y.current&&clearTimeout(y.current),T.scrollIntoView({behavior:W,block:"start"}),h.current=U,p(U);const k=V.length-1-U;x(k),d(k>0),y.current=setTimeout(()=>{f.current=!1},500)}},[v]),B=l.useCallback(()=>{const U=t.current;if(!U)return[];const W=U.getBoundingClientRect();return v().filter(T=>T.getBoundingClientRect().bottom<W.top+50)},[v]);l.useCallback(()=>B().length>0,[B]);const D=l.useCallback(()=>{const U=t.current;if(!U)return-1;const W=U.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 U=v(),W=h.current!==-1?h.current:D();return W===-1?!1:W<U.length-1},[v,D]);const I=l.useCallback((U="smooth")=>{t.current&&(t.current.scrollTo({top:t.current.scrollHeight,behavior:U}),h.current=-1)},[]),M=l.useCallback((U="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,y.current&&clearTimeout(y.current),P.scrollIntoView({behavior:U,block:"start"}),h.current=S,p(S);const j=V.length-1-S;x(j),d(j>0),y.current=setTimeout(()=>{f.current=!1},500)}}},[v]),E=l.useCallback((U="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,y.current&&clearTimeout(y.current),k.scrollIntoView({behavior:U,block:"start"}),h.current=T,p(T);const S=V.length-1-T;x(S),d(S>0),y.current=setTimeout(()=>{f.current=!1},500)}}}},[v]);l.useCallback(()=>h.current>0?!0:B().length>0,[B]),l.useCallback(()=>{const U=v();return h.current===-1?!1:h.current<U.length-1},[v]);const _=l.useCallback(()=>{h.current=-1},[]);l.useEffect(()=>{const U=t.current;if(!U)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 U.addEventListener("scroll",V,{passive:!0}),()=>{U.removeEventListener("scroll",V),clearTimeout(W)}},[N,D,v,B]),l.useEffect(()=>{const U=t.current;if(!U)return;const W=()=>{U.scrollHeight<=U.clientHeight+1||r.current&&!i.current&&requestAnimationFrame(()=>{U.scrollTo({top:U.scrollHeight,behavior:"instant"}),o(!0),r.current=!0})},V=new MutationObserver(W);V.observe(U,{childList:!0,subtree:!0,characterData:!0});const T=new ResizeObserver(W);return T.observe(U),Array.from(U.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:M,scrollToNextUserMessage:E,scrollToUserMessageByIndex:$,getUserMessagePreviews:C,resetUserMessageCycle:_}}const Ni=({...t})=>e.jsx(Ta,{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}),Zt=l.createContext(void 0),Me=()=>{const t=l.useContext(Zt);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},Qn=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,y]=l.useState(!1),[N,v]=l.useState(yn),[C,$]=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=M=>{M.key.toLowerCase()==="b"&&(M.metaKey||M.ctrlKey)&&!M.shiftKey&&(M.preventDefault(),B())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[B]),e.jsx(Zt.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:y,asideWidth:N,setAsideWidth:v,mainWidth:C,setMainWidth:$},children:e.jsx("div",{ref:a,"data-panel-state":x?"expanded":"collapsed",className:b("flex h-screen flex-row bg-background text-foreground overflow-hidden",o),...i,children:r})})});Qn.displayName="ChatLayout.Root";const Ci=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("relative z-10 border-b border-border bg-card shrink-0",t),...n,children:s}));Ci.displayName="ChatLayout.Header";const Gn=l.forwardRef(({className:t,children:s},n)=>{const{panelOpen:o,isDraggingAside:r,asideWidth:i,setMainWidth:a}=Me(),c=l.useRef(null),{width:u}=wi(c);return l.useEffect(()=>{a(u)},[u,a]),l.useImperativeHandle(n,()=>c.current),e.jsx("div",{ref:c,className:b("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})});Gn.displayName="ChatLayout.Main";const Xn=l.forwardRef(({showToaster:t=!0,className:s,children:n,...o},r)=>e.jsxs("div",{ref:r,className:b("relative flex flex-1 flex-col overflow-hidden",s),...o,children:[n,t&&e.jsx(Ni,{})]}));Xn.displayName="ChatLayout.Body";const Jn=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}=ji(),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}}}),[]),[y,N]=l.useState(!1),[v,C]=l.useState([]),[$,B]=l.useState(null),[D,I]=l.useState(0),M=l.useRef(null),E=l.useRef(null),_=l.useRef(null),K=l.useRef(0),Y=l.useCallback(()=>{const z=u.current;if(!z)return[];const X=z.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 z=u.current;if(!z)return;const X=()=>{const A=Y();C(A)};X();const R=new MutationObserver(X);return R.observe(z,{childList:!0,subtree:!0}),()=>{R.disconnect()}},[u,Y]),l.useEffect(()=>()=>{M.current&&clearTimeout(M.current),E.current&&clearTimeout(E.current),_.current!==null&&cancelAnimationFrame(_.current)},[]);const U=c>_r+Er,W=v.length>1&&U,V=l.useCallback(z=>{const R=z.currentTarget.getBoundingClientRect(),A=z.clientY-R.top;K.current=A,_.current===null&&(_.current=requestAnimationFrame(()=>{I(K.current),_.current=null}))},[]),T=l.useCallback(()=>{E.current&&(clearTimeout(E.current),E.current=null),M.current=setTimeout(()=>{N(!0)},1500)},[]),k=l.useCallback(()=>{M.current&&(clearTimeout(M.current),M.current=null),E.current=setTimeout(()=>{N(!1),B(null)},500)},[]),S=l.useCallback(z=>{B(z)},[]),P=l.useCallback(()=>{B(null)},[]),j=l.useCallback(z=>{x(z,"smooth")},[x]),O=l.useRef(!1);l.useImperativeHandle(a,()=>u.current),l.useEffect(()=>{n?.(m)},[m,n]),l.useEffect(()=>{if(!r)return;const z=u.current;if(z&&!O.current){const X=setTimeout(()=>{z.scrollHeight>z.clientHeight+1&&(z.scrollTop=z.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:b("h-full overflow-y-auto flex flex-col",t),...i,children:[e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s}),e.jsx("div",{ref: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:z})=>{const X=z===g,R=$===z;return e.jsx("button",{type:"button",onClick:()=>j(z),onMouseEnter:()=>S(z),onMouseLeave:P,className:"py-2 px-1 group","aria-label":`Go to user message ${z+1}`,children:e.jsx("div",{className:b("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")})},z)})}),e.jsx(ot,{children:y&&v.length>0&&$!==null&&(()=>{const R=40*Math.min(3,v.length)+10,A=40,J=40*$,G=A-J,Ie=0,ne=R-40*v.length-10,ce=Math.max(ne,Math.min(Ie,G));return e.jsx(ke.div,{variants:f,initial:"hidden",animate:"visible",exit:"exit",className:b("absolute left-12 pointer-events-none","w-72 overflow-hidden","bg-card border border-border rounded-lg shadow-xl"),style:{top:`${D}px`,y:"-50%",height:`${R}px`,willChange:"transform"},children:e.jsx("div",{className:"p-1",style:{transform:`translateY(${ce}px)`,transition:"transform 0.15s cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:v.map(({index:oe,preview:we})=>{const ze=oe===$;return e.jsx("div",{className:b("w-full text-left px-3 py-2 rounded-md","text-sm text-muted-foreground","transition-colors duration-100","truncate",ze&&"bg-accent text-foreground"),style:{height:"40px"},children:we},oe)})})},"hover-menu")})()})]},"toc")}),Q&&e.jsx("button",{type:"button",onClick:()=>p("smooth"),className:b("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:e.jsx(Xa,{className:"size-4"})})]})});Jn.displayName="ChatLayout.Messages";const Zn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("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})}));Zn.displayName="ChatLayout.Footer";const Si=l.forwardRef(({className:t,children:s,...n},o)=>{const{sidebarOpen:r}=Me();return r?e.jsx("div",{ref:o,className:b("border-r border-border bg-card w-64 overflow-y-auto",t),...n,children:s}):null});Si.displayName="ChatLayout.Sidebar";const ea=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(yn),[p,g]=l.useState(d),[x,h]=l.useState(!1),f=l.useRef(0),y=l.useRef(d),N=i!=="hidden",[v,C]=l.useState(!1);l.useEffect(()=>{if(!N){C(!1);return}const _=requestAnimationFrame(()=>{C(!0)});return()=>cancelAnimationFrame(_)},[N]);const $=wn();vn($&&N),l.useEffect(()=>{g(d)},[d]),l.useEffect(()=>{N&&u(x?p:d)},[N,x,p,d,u]);const B=l.useCallback(_=>{_.preventDefault(),h(!0),c(!0),f.current=_.clientX,y.current=d,_.target.setPointerCapture(_.pointerId)},[d,c]),D=l.useCallback(_=>{if(!x)return;const K=_.clientX-f.current,Y=Math.max(ys,Math.min(vs,y.current-K));g(Y)},[x]),I=l.useCallback(_=>{if(!x)return;const K=_.clientX-f.current,Y=Math.max(ys,Math.min(vs,y.current-K));m(Y),g(Y),h(!1),c(!1),_.target.releasePointerCapture(_.pointerId)},[x,c]),M=N&&$,E=N&&!$;return e.jsxs(ot,{initial:!1,children:[M&&e.jsx(ke.aside,{variants:zr,initial:"initial",animate:"animate",exit:"exit",transition:Or,className:b("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:$r,initial:"initial",animate:"animate",transition:Lr,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"),E&&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:b("fixed inset-y-0 right-0 z-40","hidden h-full border-l border-border bg-card overflow-hidden",t==="sm"&&"sm:block",t==="md"&&"md:block",t==="lg"&&"lg:block",t==="xl"&&"xl:block",t==="2xl"&&"2xl:block",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:b("absolute left-0 inset-y-0 w-2 -ml-1 cursor-col-resize z-10","group flex items-center justify-center","hover:bg-primary/5 transition-colors delay-300",x&&"bg-primary/10")}),e.jsx("div",{className:b("h-full overflow-y-auto",x?"w-full":void 0),style:x?void 0:{width:`${d}px`},children:o})]})},"aside-desktop")]})});ea.displayName="ChatLayout.Aside";class ki{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 ta({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:b("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",g(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",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(Ja,{className:"size-4"}):e.jsx(Za,{className:"size-4"}):e.jsx(eo,{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:b("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:x=>{x.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(to,{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(Ne,{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(ge,{className:b("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(ta,{item:x,level:s+1,...n&&{onSelect:n},...o&&{selectedId:o},...i&&{onDownload:i}},x.id))})]})}const Ti=new wr;function Ii({className:t,provider:s=Ti,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(y=>y+1)},6e4);return()=>clearInterval(f)},[]),l.useEffect(()=>{(async()=>{try{d(!0);const y=await s.getRootItems();i(y),p(void 0)}catch(y){p(y instanceof Error?y.message:"Failed to load items")}finally{d(!1)}})()},[s]);const h=f=>{c(f.id),n?.(f)};return u?e.jsx("div",{className:b("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):m?e.jsx("div",{className:b("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",m]})}):r.length===0?e.jsxs("div",{className:b("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",t),children:[e.jsx(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:b("flex flex-col",t),children:r.map(f=>e.jsx(ta,{item:f,onSelect:h,...a&&{selectedId:a},...o&&{onDownload:o}},f.id))})}const Ot=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:b("group flex w-full text-left gap-2 items-start p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",s&&"bg-accent",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:b("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"]})]})]})]})});Ot.displayName="SourceListItem";const es=$a,He=l.forwardRef(({className:t,...s},n)=>e.jsx(Fs,{ref:n,className:b("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));He.displayName=Fs.displayName;const Ue=l.forwardRef(({className:t,...s},n)=>e.jsx(Bs,{ref:n,className:b("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-paragraph-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...s}));Ue.displayName=Bs.displayName;const fe=l.forwardRef(({className:t,...s},n)=>e.jsx(Hs,{ref:n,className:b("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));fe.displayName=Hs.displayName;const sa=l.forwardRef(({todo:t,className:s,...n},o)=>{const r=t.status==="completed";return e.jsxs("div",{ref:o,className:b("group flex items-start gap-2 p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",!1,s),role:"button",tabIndex:0,...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:b("flex-1 text-foreground",r&&"line-through text-muted-foreground",t.status==="in_progress"&&"font-medium"),children:t.text})]})});sa.displayName="TodoListItem";function Ri(){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 ts=l.forwardRef(({client:t,todos:s,className:n,...o},r)=>{const i=s||[];return i.length===0?e.jsx("div",{ref:r,className:b("h-full",n),...o,children:e.jsx(Ri,{})}):e.jsx("div",{ref:r,className:b("space-y-2 overflow-y-auto",n),...o,children:i.map(a=>e.jsx(sa,{todo:a},a.id))})});ts.displayName="TodoList";const ss=l.forwardRef(({todos:t=[],className:s,...n},o)=>e.jsx("div",{ref:o,className:b("h-full",s),...n,children:e.jsx(ts,{todos:t,className:"h-full"})}));ss.displayName="TodoTabContent";const ns=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,y=>{console.log("Files changed:",y),g()}),[n,r,g]);const x=l.useMemo(()=>{if(s)return s;if(n&&o)return new ki({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 y=`${o}/sandbox/download?sessionId=${encodeURIComponent(n)}&path=${encodeURIComponent(f.path||f.name)}`,N=document.createElement("a");N.href=y,N.download=f.name,document.body.appendChild(N),N.click(),document.body.removeChild(N)}catch(y){console.error("Failed to download file:",y)}},[n,o]);return e.jsx("div",{ref:u,className:b("h-full",a),...c,children:e.jsx(Ii,{...x&&{provider:x},onItemSelect:f=>{f.type==="file"&&i&&i(f.path||f.name)},onDownload:h,className:"h-full"},d)})});ns.displayName="FilesTabContent";const as=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:b("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",n),...o,children:[e.jsx(sn,{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(es,{value:u,onValueChange:m=>d(m),className:b("flex flex-col gap-2",n),children:[e.jsx("div",{className:b("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:b("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:b("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(fe,{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(Ot,{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(fe,{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(Ot,{source:m,isSelected:m.id===s},m.id))}):e.jsx("div",{ref:r,className:"text-xs text-muted-foreground",...o,children:"No reviewed sources."})})]})});as.displayName="SourcesTabContent";const _i=l.forwardRef(({data:t,className:s,...n},o)=>e.jsxs("div",{ref:o,className:b("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]})]})]}));_i.displayName="DatabaseTabContent";const Mi=({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(", ")]})]})},na=l.forwardRef(({tools:t=[],mcps:s=[],subagents:n=[],className:o,...r},i)=>e.jsxs("div",{ref:i,className:b("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(Mi,{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"})]})]}));na.displayName="SettingsTabContent";const Ei=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 y=setTimeout(()=>{const N=p.current;if(d&&N){const v=g.current;if(v){const C=N.getBoundingClientRect(),$=v.getBoundingClientRect(),B=$.left-C.left,D=$.width,I=B/C.width*100,M=100-(B+D)/C.width*100;N.style.clipPath=`inset(0 ${M.toFixed(2)}% 0 ${I.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(y)},[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:nn},{id:"sources",label:"Sources",icon:an}].filter(f=>r.includes(f.id));return e.jsx("div",{ref:c,className:b("select-none",i),...a,children:e.jsxs(es,{value:d,onValueChange:m,className:"w-full",children:[n==="pills"?e.jsx(He,{className:b("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:h.map(f=>{const y=f.icon;return e.jsxs(Ue,{value:f.id,className:b("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&y&&e.jsx(y,{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(fe,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?e.jsx(ss,{todos:u}):e.jsx(ts,{todos:u})}),e.jsx(fe,{value:"files",className:n==="pills"?"mt-0":"",children:e.jsx(ns,{})}),e.jsx(fe,{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(fe,{value:"sources",className:n==="pills"?"mt-0":"",children:e.jsx(as,{})})]})})});Ei.displayName="ChatSecondaryPanel";const Ai=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex h-full flex-col",t),...n,children:s}));Ai.displayName="ChatSidebar.Root";const Pi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("border-b border-border px-4 py-3",t),...n,children:s}));Pi.displayName="ChatSidebar.Header";const Di=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex-1 overflow-y-auto p-4",t),...n,children:s}));Di.displayName="ChatSidebar.Content";const Ui=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("border-t border-border px-4 py-3",t),...n,children:s}));Ui.displayName="ChatSidebar.Footer";const zi=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:b("text-sm text-foreground opacity-60 transition-opacity duration-300",a?"opacity-0":"opacity-60",s),...n,children:r})});zi.displayName="ChatStatus";let Cs=!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=me("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 $i(t){if(rt.push(t),t.level==="error"||t.level==="fatal"){Ss();return}nt||(nt=setTimeout(()=>{nt=null,Ss()},500))}async function Ss(){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 Li(t){Cs||(Cs=!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})},Co(s=>{s.service==="gui-console"&&$i(s)}),window.addEventListener("beforeunload",()=>{nt&&clearTimeout(nt),rt.length>0&&st&&navigator.sendBeacon(`${st}/logs/browser`,JSON.stringify({logs:rt}))}))}const Oi=500;function Fi(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,Oi),()=>{n.current&&(clearInterval(n.current),n.current=null),document.title=t}},[s,t])}const Se=me("gui");function Bi({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 Hi({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(On,{client:t,startSession:s,onCancel:r,children:[e.jsx(Yn,{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(Fn,{placeholder:n,autoFocus:!0,onFilesDropped:d}),e.jsxs(Wn,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Vn,{}),e.jsx(qn,{onFilesSelected:d}),i&&i.length>0&&e.jsx(vi,{parameters:i})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Kn,{}),e.jsx(Hn,{}),e.jsx(Bn,{children:e.jsx(no,{className:"size-4"})})]})]})]})}function Wi({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(es,{value:u,onValueChange:m=>d(m),className:"flex flex-col h-full",children:[e.jsx("div",{className:b("border-b border-border bg-card","px-4 py-2 h-16","flex items-center","sticky top-0 z-10 shrink-0"),children:e.jsx(ga,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(fe,{value:"todo",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ss,{todos:t})}),e.jsx(fe,{value:"files",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ns,{sessionId:i,agentApiUrl:a,client:c})}),e.jsx(fe,{value:"sources",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(as,{sources:s})}),e.jsx(fe,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(na,{tools:n??[],mcps:o??[],subagents:r??[]})})]})}function Vi({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(zn,{className:b("border-b border-border bg-card h-16"),children:e.jsxs("div",{className:"flex items-center w-full py-5 px-4 lg:px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(Vl,{}),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(ra,{}),o&&e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{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(cs,{className:"size-4 text-muted-foreground"})}):e.jsx(cs,{className:"size-4 text-muted-foreground"})})}),e.jsx(ye,{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(so,{className:"size-4 text-muted-foreground"})})]})]})})}function qi({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}=hn(t,c);lr(t);const g=H(R=>R.error),[x,h]=l.useState(void 0),[f,y]=l.useState(void 0),[N,v]=l.useState(void 0),[C,$]=l.useState([]),[B,D]=l.useState([]),[I,M]=l.useState([]),[E,_]=l.useState([]),[K,Y]=l.useState("Type a message or / for commands..."),[U,W]=l.useState(!1),[V,T]=l.useState(null),k=H(nr);H(R=>R.latestContextSize);const{resolvedTheme:S,setTheme:P}=Jt(),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 ce,oe=0;for(;(ce=A.exec(ne))!==null;){const we=ce[1]??ce[2];if(!we)continue;const ze=R.get(we)??[];ze.push({messageId:Ie.id,messageIndex:G,citationIndex:oe}),R.set(we,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]);Fi(x),l.useEffect(()=>{if(t){const R=t.getBaseUrl();R&&Li(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),y(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&&($(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&&(M(A.subagents),Se.info("Agent subagents loaded",{subagents:A.subagents})),A.promptParameters&&A.promptParameters.length>0&&(_(A.promptParameters),Se.info("Agent prompt parameters loaded",{promptParameters:A.promptParameters})),A.uiConfig?.hideTopBar&&W(!0)}},[t,r]);const Q=R=>{Y(R)},z=()=>{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(en,{className:"h-4 w-4"}):e.jsx(tn,{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(Wt,{className:"h-4 w-4"}),category:"action",onSelect:()=>{Se.info("User opened settings")}}];return e.jsxs(Cn,{defaultOpen:!1,children:[e.jsx(ui,{client:t,currentSessionId:a}),e.jsx(kn,{children:e.jsxs(Qn,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsxs(Gn,{children:[!U&&e.jsx(Vi,{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(Xn,{children:[e.jsx(Jn,{children:u.length===0?x!==void 0?e.jsx(Bi,{children:({openFiles:R,openSettings:A})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Un,{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:z,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(la,{message:R,className:b("group",Ie&&"opacity-50",R.role==="user"&&"mb-4"),isLastMessage:A===u.length-1,children:e.jsx("div",{className:b("flex flex-col w-full min-w-0"),children:R.role==="user"?e.jsx(tl,{message:R,messageIndex:G,isStreaming:J,onEditAndResend:m,onEditingChange:ne=>{T(ne?A:null)}}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{message:R,thinkingDisplayStyle:"collapsible"}),e.jsx(ll,{message:R,isStreaming:R.isStreaming,onSendMessage:d,isLastAssistantMessage:A===u.findLastIndex(ne=>ne.role==="assistant"),onRedo:()=>{let ne=null,ce=-1;for(let oe=A-1;oe>=0;oe--)if(u[oe]?.role==="user"){ne=u[oe],ce=u.slice(0,oe+1).filter(we=>we.role==="user").length-1;break}if(ne?.content&&ce>=0){const oe=ne.images?.map((we,ze)=>({name:`image-${ze}`,path:"",size:0,mimeType:we.mimeType,data:we.data}));m(ce,ne.content,oe)}}})]})})},R.id)})})}),e.jsx(Zn,{children:e.jsx(Hi,{client:t,startSession:c,placeholder:K,commandMenuItems:X,onCancel:p,promptParameters:E})})]})]}),e.jsx(ea,{breakpoint:"md",children:e.jsx(Wi,{todos:k,sources:O,tools:C,mcps:B,subagents:I,sessionId:a,agentApiUrl:t?.getBaseUrl(),client:t})})]})})]})}const Ft=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:b("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||Ki(r.url);return e.jsx(he,{delayDuration:200,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsxs("span",{ref:o,role:"button",tabIndex:0,onClick:a,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&a(u)},className:b("inline-flex items-center gap-1 px-1.5 py-0.5","text-xs font-medium rounded-md","bg-accent/50 text-accent-foreground","hover:bg-accent cursor-pointer transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",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(ye,{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(ao,{className:"size-3"}),e.jsx("span",{children:"Click to open"})]})]})})]})})});Ft.displayName="CitationChip";function Ki(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}const Yi=2e5;function os(t){const s=Math.max(t.totalEstimated,t.llmReportedInputTokens??0),n=t.modelContextWindow??Yi,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 aa({contextSize:t}){const{actualTokens:s,formattedPercentage:n,colorClass:o,calculatePercentage:r}=os(t);return e.jsx(ye,{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:b("flex justify-end gap-2 font-semibold",o),children:[e.jsx("span",{children:s.toLocaleString()}),e.jsxs("span",{children:["(",n,")"]})]})})]})})}function oa({contextSize:t,className:s,size:n=12}){if(t==null)return null;const{colorClass:o,clampedPercentage:r}=os(t),i=2,a=(n-i)/2,c=n/2,u=2*Math.PI*a,d=u-r/100*u;return e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{className:b("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(aa,{contextSize:t})]})})}const ra=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}=os(i);return e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(ie,{ref:o,type:"button",variant:"ghost",size:"icon",className:b("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(aa,{contextSize:i})]})})});ra.displayName="ContextUsageButton";const Qi=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 y=l.useCallback(()=>{const v=m.current;if(!v)return;const{scrollTop:C,scrollHeight:$,clientHeight:B}=v,I=$-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=()=>{y()};return v.addEventListener("scroll",C,{passive:!0}),y(),()=>{v.removeEventListener("scroll",C)}},[y]),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:b("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"]})})]})});Qi.displayName="Conversation";const Gi=Ws,ia=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{ref:n,className:b("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s}));ia.displayName=Nt.displayName;const Xi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Gi,{children:[e.jsx(ia,{}),e.jsxs(Ct,{ref:o,className:b("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[s,e.jsxs(Vs,{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"})]})]})]}));Xi.displayName=Ct.displayName;const Ji=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:b("text-subheading font-semibold leading-none tracking-tight",t),...s}));Ji.displayName=St.displayName;const Zi=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:b("text-paragraph-sm text-muted-foreground",t),...s}));Zi.displayName=kt.displayName;function el({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){pe.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),d(!0),pe.success("Copied to clipboard!"),setTimeout(()=>{d(!1)},2e3)}catch{pe.error("Failed to copy to clipboard")}},[t.content]),h=l.useCallback(()=>{n||c(!0)},[n]);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]),y=l.useCallback(()=>{const v=p.current?.textContent||"";if(!v.trim())return;const C=t.images?.map(($,B)=>({name:`image-${B}`,path:"",size:0,mimeType:$.mimeType,data:$.data}));o(s,v.trim(),C),c(!1)},[s,t.images,o]),N=l.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),y()),v.key==="Escape"&&(v.preventDefault(),f())},[y,f]);return e.jsxs("div",{ref:m,className:"w-full group/user-message",children:[e.jsx("div",{className:b("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:b("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:b("whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-foreground leading-relaxed outline-none",a&&"cursor-text",!a&&"cursor-default"),children:t.content})]})}),t.content&&e.jsx("div",{className:"mt-2",children:e.jsx(Xt,{className:b("justify-end transition-opacity",a?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none group-hover/user-message:opacity-100 group-hover/user-message:pointer-events-auto"),children:a?e.jsxs(e.Fragment,{children:[e.jsx(ie,{variant:"ghost",size:"sm",onClick:f,className:"h-7 px-2 text-xs text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsx(ie,{size:"sm",disabled:n,onClick:y,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(Vt,{className:"size-4"})}),e.jsx(Ve,{disabled:n,onClick:h,tooltip:n?"Wait for agent to finish":"Edit",children:e.jsx(oo,{className:"size-4"})})]})})})]})}const tl=l.memo(el,(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 sl(t,s,n,o,r){const i=n==="triggered",a=o==="no_action_needed";return t==="context_size"?i?{icon:de,title:"Compacting Context..."}:{icon:de,title:a?"Context Check":"Context Compacted"}:t==="tool_response"?s==="mid_turn_compaction"||r===!0?i?{icon:de,title:"Compacting Context..."}:{icon:de,title:a?"Context Check":"Context Compacted"}:i?{icon:de,title:"Compacting Response..."}:{icon:de,title:a?"Response Check":"Tool Response Compacted"}:{icon:de,title:i?"Running Hook...":"Hook Executed"}}function Ae(t){return t.toLocaleString()}function nl(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}=sl(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(qt,{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(ge,{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(ro,{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:"," ",nl((t.completedAt-t.triggeredAt)/1e3)]})]})]})})]})]})}const al=l.forwardRef(({className:t,...s},n)=>e.jsx(qs,{ref:n,className:b("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));al.displayName=qs.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:b("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:b("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:b("markdown-content prose prose-sm max-w-none dark:prose-invert",s),children:e.jsx(va,{remarkPlugins:[rn],components:n,children:t})})}const ol=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"}}),la=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 $=v.clientHeight,B=C.offsetHeight,I=Math.max(0,$-B-32);h(I)};f();const y=new ResizeObserver(f);if(g.current){y.observe(g.current);let N=g.current.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;N&&y.observe(N)}return()=>y.disconnect()},[c,m]),l.useEffect(()=>{if((a!==void 0?a:m==="user")&&g.current){const y=setTimeout(()=>{g.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(y)}},[m,a]),e.jsx("article",{ref:g,id:p?`message-${p}`:void 0,"aria-label":`${m} message`,"data-message-id":p,className:b(ol({role:m,layout:n}),o),style:{minHeight:x!==void 0?`${x}px`:void 0},...u,children:r})});la.displayName="Message";const rl=[{id:"pdf",label:"PDF",icon:We},{id:"excel",label:"Excel",icon:ds},{id:"csv",label:"CSV",icon:ds},{id:"text",label:"Text",icon:lo},{id:"markdown",label:"Markdown",icon:We}];function il({message:t,isStreaming:s,onRedo:n,onSendMessage:o,isLastAssistantMessage:r=!1}){const[i,a]=l.useState(!1);if(t.role!=="assistant"||!t.content?.trim())return null;const c=r?"":"opacity-0 group-hover:opacity-100 transition-opacity",u=!!s,d=!!t.content&&!u,m=async()=>{if(!t.content||u){pe.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),a(!0),pe.success("Copied to clipboard!"),setTimeout(()=>{a(!1)},2e3)}catch{pe.error("Failed to copy to clipboard")}},p=()=>{u||(n?n():pe.info("Regenerate not available"))},g=x=>{u||(o?o(`produce an artifact as ${x} for this session`):pe.info("Export not available"))};return e.jsx("div",{className:"mt-1",children:e.jsxs(Xt,{className:b(c,r?"pointer-events-auto":"pointer-events-none group-hover:pointer-events-auto"),children:[e.jsx(Ve,{disabled:!d,onClick:m,tooltip:i?"Copied!":"Copy",children:i?e.jsx(lt,{className:"size-4"}):e.jsx(Vt,{className:"size-4"})}),e.jsx(Ve,{disabled:u,onClick:p,tooltip:"Redo",children:e.jsx(io,{className:"size-4"})}),e.jsxs(ut,{children:[e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(mt,{asChild:!0,children:e.jsxs(ie,{className:b("relative size-7 p-1.5 text-muted-foreground hover:text-foreground"),disabled:u,size:"sm",type:"button",variant:"ghost",children:[e.jsx(on,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Export"})]})})}),e.jsx(ye,{children:e.jsx("p",{children:"Export"})})]})}),e.jsx(qe,{align:"start",children:rl.map(x=>e.jsxs(Ne,{onClick:()=>g(x.label),children:[e.jsx(x.icon,{className:"size-4 mr-2"}),x.label]},x.id))})]})]})})}const ll=l.memo(il,(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)),cl={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 dl(t,s){if(!s||!t.rawInput)return null;const n=t.rawInput[s];return typeof n=="string"?n:null}function ul(t,s){let n=t;for(const[o,r]of Object.entries(s))n=n.replace(`{${o}}`,r);return n}function ml(t,s){return t.length<=s?t:`${t.substring(0,s-1)}…`}function jt(t,s){const n=t.verbiage||cl[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=dl(t,n.paramKey);if(r){const i=ml(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"),ul(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 pl(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 ca(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 fl(t){return t.every(s=>gt(s)==="completed")}function gl(t){return t.some(s=>gt(s)==="failed")}function hl(t){return gl(t)?"failed":fl(t)?"completed":t.every(s=>De(s))?"selecting":"executing"}const ks=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"}}),xl=Te("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),da=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:b(ks({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:b("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(ge,{className:xl({expanded:p}),"aria-hidden":"true"})]}),p&&e.jsx("div",{className:b(ks({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:"..."})]})})]})});da.displayName="Reasoning";function bl(){return t=>{Ia(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=me("Response","debug");function yl(t){const s=/[",\n\r]/.test(t),n=t.replaceAll('"','""');return s?`"${n}"`:n}function Ts(t){return Array.from(t.querySelectorAll("tr")).map(n=>Array.from(n.querySelectorAll("th,td")).map(r=>yl((r.textContent||"").trim())).join(",")).join(`
|
|
9
|
-
`)}function
|
|
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=$();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(),M(!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 _(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(),M(!0)},onDragLeave:k=>{k.preventDefault(),M(!1)},disabled:m,...i};return t&&l.isValidElement(r)?l.cloneElement(r,T):e.jsx("textarea",{...T,rows:1,className:b("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 max-h-[6lh] min-h-[44px]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-paragraph-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",I&&"ring-2 ring-primary ring-offset-2",s)})});Fn.displayName="ChatInput.Field";const Bn=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?ve:le;return e.jsx(m,{ref:i,type:"submit",disabled:d,variant:t?void 0:"default",size:"icon",className:b(!t&&"gap-1.5 rounded-full",s),...r,children:o})});Bn.displayName="ChatInput.Submit";const Hn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const{onCancel:i,isSubmitting:a}=ft(),c=t?ve:le;return a?e.jsx(c,{ref:r,type:"button",onClick:()=>i?.(),variant:t?void 0:"default",size:"icon",className:b(!t&&"gap-1.5 rounded-full",s),...o,children:n||e.jsx(Ya,{className:"size-4 fill-current"})}):null});Hn.displayName="ChatInput.Stop";const Wn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex items-center justify-between p-2",t),...n,children:s}));Wn.displayName="ChatInput.Toolbar";const Vn=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?ve:le;return e.jsx(p,{ref:i,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),onClick:m,...r,children:n||e.jsx(Qa,{className:"size-4"})})});Vn.displayName="ChatInput.Actions";const qn=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?ve:le;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:b("rounded-full",s),onClick:d,...r,children:n||e.jsx(Ga,{className:"size-4"})})]})});qn.displayName="ChatInput.Attachment";const Kn=l.forwardRef(({asChild:t=!1,className:s,children:n,...o},r)=>{const i=t?ve:le;return e.jsx(i,{ref:r,type:"button",variant:"ghost",size:"icon",className:b("rounded-full",s),...o,children:n||e.jsx(Xa,{className:"size-4"})})});Kn.displayName="ChatInput.VoiceInput";const Yn=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($n,{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})});Yn.displayName="ChatInput.CommandMenu";function wi({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:b("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:b("inline-flex h-10 items-center gap-1.5 rounded-full px-3","text-sm font-medium transition-colors","focus:outline-none focus-visible:ring-1 focus-visible:ring-ring",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(ge,{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:b(n?.[c.id]===m.id&&"bg-accent"),children:m.label},m.id))})]},c.id))})}function ji(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 Ni(){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),y=l.useRef(null);l.useEffect(()=>{r.current=n},[n]);const N=l.useCallback(()=>{if(!t.current)return!0;const{scrollTop:U,scrollHeight:W,clientHeight:V}=t.current;return U+V>=W-100},[]),v=l.useCallback(()=>{if(!t.current)return[];const U=t.current.querySelectorAll('[aria-label="user message"]');return Array.from(U)},[]),C=l.useCallback(()=>{const U=t.current;if(!U)return[];const W=U.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]),$=l.useCallback((U,W="smooth")=>{const V=v();if(U<0||U>=V.length)return;const T=V[U];if(T){f.current=!0,y.current&&clearTimeout(y.current),T.scrollIntoView({behavior:W,block:"start"}),h.current=U,p(U);const k=V.length-1-U;x(k),d(k>0),y.current=setTimeout(()=>{f.current=!1},500)}},[v]),B=l.useCallback(()=>{const U=t.current;if(!U)return[];const W=U.getBoundingClientRect();return v().filter(T=>T.getBoundingClientRect().bottom<W.top+50)},[v]);l.useCallback(()=>B().length>0,[B]);const D=l.useCallback(()=>{const U=t.current;if(!U)return-1;const W=U.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 U=v(),W=h.current!==-1?h.current:D();return W===-1?!1:W<U.length-1},[v,D]);const I=l.useCallback((U="smooth")=>{t.current&&(t.current.scrollTo({top:t.current.scrollHeight,behavior:U}),h.current=-1)},[]),M=l.useCallback((U="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,y.current&&clearTimeout(y.current),P.scrollIntoView({behavior:U,block:"start"}),h.current=S,p(S);const j=V.length-1-S;x(j),d(j>0),y.current=setTimeout(()=>{f.current=!1},500)}}},[v]),E=l.useCallback((U="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,y.current&&clearTimeout(y.current),k.scrollIntoView({behavior:U,block:"start"}),h.current=T,p(T);const S=V.length-1-T;x(S),d(S>0),y.current=setTimeout(()=>{f.current=!1},500)}}}},[v]);l.useCallback(()=>h.current>0?!0:B().length>0,[B]),l.useCallback(()=>{const U=v();return h.current===-1?!1:h.current<U.length-1},[v]);const _=l.useCallback(()=>{h.current=-1},[]);l.useEffect(()=>{const U=t.current;if(!U)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 U.addEventListener("scroll",V,{passive:!0}),()=>{U.removeEventListener("scroll",V),clearTimeout(W)}},[N,D,v,B]),l.useEffect(()=>{const U=t.current;if(!U)return;const W=()=>{U.scrollHeight<=U.clientHeight+1||r.current&&!i.current&&requestAnimationFrame(()=>{U.scrollTo({top:U.scrollHeight,behavior:"instant"}),o(!0),r.current=!0})},V=new MutationObserver(W);V.observe(U,{childList:!0,subtree:!0,characterData:!0});const T=new ResizeObserver(W);return T.observe(U),Array.from(U.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:M,scrollToNextUserMessage:E,scrollToUserMessageByIndex:$,getUserMessagePreviews:C,resetUserMessageCycle:_}}const Ci=({...t})=>e.jsx(Ia,{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}),Zt=l.createContext(void 0),Ee=()=>{const t=l.useContext(Zt);if(!t)throw new Error("ChatLayout components must be used within ChatLayout.Root");return t},Qn=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,y]=l.useState(!1),[N,v]=l.useState(yn),[C,$]=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=M=>{M.key.toLowerCase()==="b"&&(M.metaKey||M.ctrlKey)&&!M.shiftKey&&(M.preventDefault(),B())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[B]),e.jsx(Zt.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:y,asideWidth:N,setAsideWidth:v,mainWidth:C,setMainWidth:$},children:e.jsx("div",{ref:a,"data-panel-state":x?"expanded":"collapsed",className:b("flex h-screen flex-row bg-background text-foreground overflow-hidden",o),...i,children:r})})});Qn.displayName="ChatLayout.Root";const Si=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("relative z-10 border-b border-border bg-card shrink-0",t),...n,children:s}));Si.displayName="ChatLayout.Header";const Gn=l.forwardRef(({className:t,children:s},n)=>{const{panelOpen:o,isDraggingAside:r,asideWidth:i,setMainWidth:a}=Ee(),c=l.useRef(null),{width:u}=ji(c);return l.useEffect(()=>{a(u)},[u,a]),l.useImperativeHandle(n,()=>c.current),e.jsx("div",{ref:c,className:b("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})});Gn.displayName="ChatLayout.Main";const Xn=l.forwardRef(({showToaster:t=!0,className:s,children:n,...o},r)=>e.jsxs("div",{ref:r,className:b("relative flex flex-1 flex-col overflow-hidden",s),...o,children:[n,t&&e.jsx(Ci,{})]}));Xn.displayName="ChatLayout.Body";const Jn=l.forwardRef(({className:t,children:s,onScrollChange:n,showScrollToBottom:o=!0,initialScrollToBottom:r=!0,...i},a)=>{const{mainWidth:c}=Ee(),{containerRef:u,endRef:d,isAtBottom:m,scrollToBottom:p,userMessagesAboveCount:g,scrollToUserMessageByIndex:x}=Ni(),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}}}),[]),[y,N]=l.useState(!1),[v,C]=l.useState([]),[$,B]=l.useState(null),[D,I]=l.useState(0),M=l.useRef(null),E=l.useRef(null),_=l.useRef(null),K=l.useRef(0),Y=l.useCallback(()=>{const z=u.current;if(!z)return[];const X=z.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 z=u.current;if(!z)return;const X=()=>{const A=Y();C(A)};X();const R=new MutationObserver(X);return R.observe(z,{childList:!0,subtree:!0}),()=>{R.disconnect()}},[u,Y]),l.useEffect(()=>()=>{M.current&&clearTimeout(M.current),E.current&&clearTimeout(E.current),_.current!==null&&cancelAnimationFrame(_.current)},[]);const U=c>Mr+Ar,W=v.length>1&&U,V=l.useCallback(z=>{const R=z.currentTarget.getBoundingClientRect(),A=z.clientY-R.top;K.current=A,_.current===null&&(_.current=requestAnimationFrame(()=>{I(K.current),_.current=null}))},[]),T=l.useCallback(()=>{E.current&&(clearTimeout(E.current),E.current=null),M.current=setTimeout(()=>{N(!0)},1500)},[]),k=l.useCallback(()=>{M.current&&(clearTimeout(M.current),M.current=null),E.current=setTimeout(()=>{N(!1),B(null)},500)},[]),S=l.useCallback(z=>{B(z)},[]),P=l.useCallback(()=>{B(null)},[]),j=l.useCallback(z=>{x(z,"smooth")},[x]),O=l.useRef(!1);l.useImperativeHandle(a,()=>u.current),l.useEffect(()=>{n?.(m)},[m,n]),l.useEffect(()=>{if(!r)return;const z=u.current;if(z&&!O.current){const X=setTimeout(()=>{z.scrollHeight>z.clientHeight+1&&(z.scrollTop=z.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:b("h-full overflow-y-auto flex flex-col",t),...i,children:[e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:s}),e.jsx("div",{ref:d,className:"shrink-0"})]}),e.jsx(ot,{mode:"wait",children:W&&e.jsxs(Te.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:z})=>{const X=z===g,R=$===z;return e.jsx("button",{type:"button",onClick:()=>j(z),onMouseEnter:()=>S(z),onMouseLeave:P,className:"py-2 px-1 group","aria-label":`Go to user message ${z+1}`,children:e.jsx("div",{className:b("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")})},z)})}),e.jsx(ot,{children:y&&v.length>0&&$!==null&&(()=>{const R=40*Math.min(3,v.length)+10,A=40,J=40*$,G=A-J,Re=0,ne=R-40*v.length-10,ae=Math.max(ne,Math.min(Re,G));return e.jsx(Te.div,{variants:f,initial:"hidden",animate:"visible",exit:"exit",className:b("absolute left-12 pointer-events-none","w-72 overflow-hidden","bg-card border border-border rounded-lg shadow-xl"),style:{top:`${D}px`,y:"-50%",height:`${R}px`,willChange:"transform"},children:e.jsx("div",{className:"p-1",style:{transform:`translateY(${ae}px)`,transition:"transform 0.15s cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform"},children:v.map(({index:Ce,preview:re})=>{const Se=Ce===$;return e.jsx("div",{className:b("w-full text-left px-3 py-2 rounded-md","text-sm text-muted-foreground","transition-colors duration-100","truncate",Se&&"bg-accent text-foreground"),style:{height:"40px"},children:re},Ce)})})},"hover-menu")})()})]},"toc")}),Q&&e.jsx("button",{type:"button",onClick:()=>p("smooth"),className:b("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:e.jsx(Ja,{className:"size-4"})})]})});Jn.displayName="ChatLayout.Messages";const Zn=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("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})}));Zn.displayName="ChatLayout.Footer";const ki=l.forwardRef(({className:t,children:s,...n},o)=>{const{sidebarOpen:r}=Ee();return r?e.jsx("div",{ref:o,className:b("border-r border-border bg-card w-64 overflow-y-auto",t),...n,children:s}):null});ki.displayName="ChatLayout.Sidebar";const ea=l.forwardRef(({breakpoint:t="md",onClose:s,className:n,children:o},r)=>{const{panelSize:i,togglePanel:a,setIsDraggingAside:c,setAsideWidth:u}=Ee(),[d,m]=l.useState(yn),[p,g]=l.useState(d),[x,h]=l.useState(!1),f=l.useRef(0),y=l.useRef(d),N=i!=="hidden",[v,C]=l.useState(!1);l.useEffect(()=>{if(!N){C(!1);return}const _=requestAnimationFrame(()=>{C(!0)});return()=>cancelAnimationFrame(_)},[N]);const $=wn();vn($&&N),l.useEffect(()=>{g(d)},[d]),l.useEffect(()=>{N&&u(x?p:d)},[N,x,p,d,u]);const B=l.useCallback(_=>{_.preventDefault(),h(!0),c(!0),f.current=_.clientX,y.current=d,_.target.setPointerCapture(_.pointerId)},[d,c]),D=l.useCallback(_=>{if(!x)return;const K=_.clientX-f.current,Y=Math.max(ys,Math.min(vs,y.current-K));g(Y)},[x]),I=l.useCallback(_=>{if(!x)return;const K=_.clientX-f.current,Y=Math.max(ys,Math.min(vs,y.current-K));m(Y),g(Y),h(!1),c(!1),_.target.releasePointerCapture(_.pointerId)},[x,c]),M=N&&$,E=N&&!$;return e.jsxs(ot,{initial:!1,children:[M&&e.jsx(Te.aside,{variants:$r,initial:"initial",animate:"animate",exit:"exit",transition:Fr,className:b("fixed inset-0 z-50 bg-card","flex flex-col","block md:hidden",n),"data-aside":"aside","data-mobile":"true",children:e.jsxs(Te.div,{className:"flex flex-col h-full",variants:Lr,initial:"initial",animate:"animate",transition:Or,children:[e.jsx("div",{className:"flex justify-end px-4 pt-3 shrink-0",children:e.jsx(_e,{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"),E&&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:b("fixed inset-y-0 right-0 z-40","hidden h-full border-l border-border bg-card overflow-hidden",t==="sm"&&"sm:block",t==="md"&&"md:block",t==="lg"&&"lg:block",t==="xl"&&"xl:block",t==="2xl"&&"2xl:block",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:b("absolute left-0 inset-y-0 w-2 -ml-1 cursor-col-resize z-10","group flex items-center justify-center","hover:bg-primary/5 transition-colors delay-300",x&&"bg-primary/10")}),e.jsx("div",{className:b("h-full overflow-y-auto",x?"w-full":void 0),style:x?void 0:{width:`${d}px`},children:o})]})},"aside-desktop")]})});ea.displayName="ChatLayout.Aside";class Ti{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 ta({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:b("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",g(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",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(Za,{className:"size-4"}):e.jsx(eo,{className:"size-4"}):e.jsx(to,{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:b("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:x=>{x.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(so,{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(ge,{className:b("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(ta,{item:x,level:s+1,...n&&{onSelect:n},...o&&{selectedId:o},...i&&{onDownload:i}},x.id))})]})}const Ii=new jr;function Ri({className:t,provider:s=Ii,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(y=>y+1)},6e4);return()=>clearInterval(f)},[]),l.useEffect(()=>{(async()=>{try{d(!0);const y=await s.getRootItems();i(y),p(void 0)}catch(y){p(y instanceof Error?y.message:"Failed to load items")}finally{d(!1)}})()},[s]);const h=f=>{c(f.id),n?.(f)};return u?e.jsx("div",{className:b("",t),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):m?e.jsx("div",{className:b("",t),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",m]})}):r.length===0?e.jsxs("div",{className:b("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",t),children:[e.jsx(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:b("flex flex-col",t),children:r.map(f=>e.jsx(ta,{item:f,onSelect:h,...a&&{selectedId:a},...o&&{onDownload:o}},f.id))})}const Ot=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:b("group flex w-full text-left gap-2 items-start p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",s&&"bg-accent",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:b("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"]})]})]})]})});Ot.displayName="SourceListItem";const es=La,He=l.forwardRef(({className:t,...s},n)=>e.jsx(Fs,{ref:n,className:b("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",t),...s}));He.displayName=Fs.displayName;const ze=l.forwardRef(({className:t,...s},n)=>e.jsx(Bs,{ref:n,className:b("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-paragraph-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...s}));ze.displayName=Bs.displayName;const fe=l.forwardRef(({className:t,...s},n)=>e.jsx(Hs,{ref:n,className:b("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));fe.displayName=Hs.displayName;const sa=l.forwardRef(({todo:t,className:s,...n},o)=>{const r=t.status==="completed";return e.jsxs("div",{ref:o,className:b("group flex items-start gap-2 p-2 rounded-md cursor-pointer transition-colors text-paragraph-sm","hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",!1,s),role:"button",tabIndex:0,...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:b("flex-1 text-foreground",r&&"line-through text-muted-foreground",t.status==="in_progress"&&"font-medium"),children:t.text})]})});sa.displayName="TodoListItem";function _i(){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 ts=l.forwardRef(({client:t,todos:s,className:n,...o},r)=>{const i=s||[];return i.length===0?e.jsx("div",{ref:r,className:b("h-full",n),...o,children:e.jsx(_i,{})}):e.jsx("div",{ref:r,className:b("space-y-2 overflow-y-auto",n),...o,children:i.map(a=>e.jsx(sa,{todo:a},a.id))})});ts.displayName="TodoList";const ss=l.forwardRef(({todos:t=[],className:s,...n},o)=>e.jsx("div",{ref:o,className:b("h-full",s),...n,children:e.jsx(ts,{todos:t,className:"h-full"})}));ss.displayName="TodoTabContent";const ns=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,y=>{console.log("Files changed:",y),g()}),[n,r,g]);const x=l.useMemo(()=>{if(s)return s;if(n&&o)return new Ti({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 y=`${o}/sandbox/download?sessionId=${encodeURIComponent(n)}&path=${encodeURIComponent(f.path||f.name)}`,N=document.createElement("a");N.href=y,N.download=f.name,document.body.appendChild(N),N.click(),document.body.removeChild(N)}catch(y){console.error("Failed to download file:",y)}},[n,o]);return e.jsx("div",{ref:u,className:b("h-full",a),...c,children:e.jsx(Ri,{...x&&{provider:x},onItemSelect:f=>{f.type==="file"&&i&&i(f.path||f.name)},onDownload:h,className:"h-full"},d)})});ns.displayName="FilesTabContent";const as=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:b("flex flex-col items-center justify-center h-full text-center py-8 max-w-sm mx-auto",n),...o,children:[e.jsx(sn,{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(es,{value:u,onValueChange:m=>d(m),className:b("flex flex-col gap-2",n),children:[e.jsx("div",{className:b("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(ze,{value:"used",disabled:i.length===0,className:b("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(ze,{value:"consulted",disabled:a.length===0,className:b("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(fe,{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(Ot,{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(fe,{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(Ot,{source:m,isSelected:m.id===s},m.id))}):e.jsx("div",{ref:r,className:"text-xs text-muted-foreground",...o,children:"No reviewed sources."})})]})});as.displayName="SourcesTabContent";const Mi=l.forwardRef(({data:t,className:s,...n},o)=>e.jsxs("div",{ref:o,className:b("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]})]})]}));Mi.displayName="DatabaseTabContent";const Ei=({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(", ")]})]})},na=l.forwardRef(({tools:t=[],mcps:s=[],subagents:n=[],className:o,...r},i)=>e.jsxs("div",{ref:i,className:b("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(Ei,{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"})]})]}));na.displayName="SettingsTabContent";const Ai=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 y=setTimeout(()=>{const N=p.current;if(d&&N){const v=g.current;if(v){const C=N.getBoundingClientRect(),$=v.getBoundingClientRect(),B=$.left-C.left,D=$.width,I=B/C.width*100,M=100-(B+D)/C.width*100;N.style.clipPath=`inset(0 ${M.toFixed(2)}% 0 ${I.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(y)},[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:nn},{id:"sources",label:"Sources",icon:an}].filter(f=>r.includes(f.id));return e.jsx("div",{ref:c,className:b("select-none",i),...a,children:e.jsxs(es,{value:d,onValueChange:m,className:"w-full",children:[n==="pills"?e.jsx(He,{className:b("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:h.map(f=>{const y=f.icon;return e.jsxs(ze,{value:f.id,className:b("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&y&&e.jsx(y,{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(ze,{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(ze,{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(fe,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?e.jsx(ss,{todos:u}):e.jsx(ts,{todos:u})}),e.jsx(fe,{value:"files",className:n==="pills"?"mt-0":"",children:e.jsx(ns,{})}),e.jsx(fe,{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(fe,{value:"sources",className:n==="pills"?"mt-0":"",children:e.jsx(as,{})})]})})});Ai.displayName="ChatSecondaryPanel";const Pi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex h-full flex-col",t),...n,children:s}));Pi.displayName="ChatSidebar.Root";const Di=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("border-b border-border px-4 py-3",t),...n,children:s}));Di.displayName="ChatSidebar.Header";const Ui=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("flex-1 overflow-y-auto p-4",t),...n,children:s}));Ui.displayName="ChatSidebar.Content";const zi=l.forwardRef(({className:t,children:s,...n},o)=>e.jsx("div",{ref:o,className:b("border-t border-border px-4 py-3",t),...n,children:s}));zi.displayName="ChatSidebar.Footer";const $i=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:b("text-sm text-foreground opacity-60 transition-opacity duration-300",a?"opacity-0":"opacity-60",s),...n,children:r})});$i.displayName="ChatStatus";let Cs=!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=me("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 Li(t){if(rt.push(t),t.level==="error"||t.level==="fatal"){Ss();return}nt||(nt=setTimeout(()=>{nt=null,Ss()},500))}async function Ss(){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 Oi(t){Cs||(Cs=!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})},So(s=>{s.service==="gui-console"&&Li(s)}),window.addEventListener("beforeunload",()=>{nt&&clearTimeout(nt),rt.length>0&&st&&navigator.sendBeacon(`${st}/logs/browser`,JSON.stringify({logs:rt}))}))}const Fi=500;function Bi(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,Fi),()=>{n.current&&(clearInterval(n.current),n.current=null),document.title=t}},[s,t])}const ke=me("gui");function Hi({children:t}){const{setPanelSize:s,setActiveTab:n,panelSize:o,activeTab:r}=Ee(),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 Wi({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(On,{client:t,startSession:s,onCancel:r,children:[e.jsx(Yn,{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(Fn,{placeholder:n,autoFocus:!0,onFilesDropped:d}),e.jsxs(Wn,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Vn,{}),e.jsx(qn,{onFilesSelected:d}),i&&i.length>0&&e.jsx(wi,{parameters:i})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Kn,{}),e.jsx(Hn,{}),e.jsx(Bn,{children:e.jsx(ao,{className:"size-4"})})]})]})]})}function Vi({todos:t,sources:s,tools:n,mcps:o,subagents:r,sessionId:i,agentApiUrl:a,client:c}){const{activeTab:u,setActiveTab:d}=Ee();return e.jsxs(es,{value:u,onValueChange:m=>d(m),className:"flex flex-col h-full",children:[e.jsx("div",{className:b("border-b border-border bg-card","px-4 py-2 h-16","flex items-center","sticky top-0 z-10 shrink-0"),children:e.jsx(ga,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(fe,{value:"todo",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ss,{todos:t})}),e.jsx(fe,{value:"files",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(ns,{sessionId:i,agentApiUrl:a,client:c})}),e.jsx(fe,{value:"sources",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(as,{sources:s})}),e.jsx(fe,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx(na,{tools:n??[],mcps:o??[],subagents:r??[]})})]})}function qi({agentName:t,showHeader:s,sessionId:n,debuggerUrl:o}){const{togglePanel:r,panelOpen:i}=Ee(),a=o?n?`${o}/sessions/${n}`:o:null;return e.jsx(zn,{className:b("border-b border-border bg-card h-16"),children:e.jsxs("div",{className:"flex items-center w-full py-5 px-4 lg:px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(ql,{}),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(ra,{}),o&&e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(_e,{"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(cs,{className:"size-4 text-muted-foreground"})}):e.jsx(cs,{className:"size-4 text-muted-foreground"})})}),e.jsx(ye,{children:e.jsx("p",{children:n?"View session in debugger":"Open debugger"})})]})}),e.jsx(_e,{"aria-label":"Toggle panel",onClick:r,"data-state":i?"open":"closed",children:e.jsx(no,{className:"size-4 text-muted-foreground"})})]})]})})}function Ki({client:t,initialSessionId:s,error:n,debuggerUrl:o}){const{connectionStatus:r,connect:i,sessionId:a,startSession:c}=or(t,s),{messages:u,sendMessage:d,editAndResend:m,cancel:p}=hn(t,c);cr(t);const g=H(R=>R.error),[x,h]=l.useState(void 0),[f,y]=l.useState(void 0),[N,v]=l.useState(void 0),[C,$]=l.useState([]),[B,D]=l.useState([]),[I,M]=l.useState([]),[E,_]=l.useState([]),[K,Y]=l.useState("Type a message or / for commands..."),[U,W]=l.useState(!1),[V,T]=l.useState(null),k=H(ar);H(R=>R.latestContextSize);const{resolvedTheme:S,setTheme:P}=Jt(),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 Re=u[G];if(!Re?.content)continue;const ne=J(Re.content);A.lastIndex=0;let ae,Ce=0;for(;(ae=A.exec(ne))!==null;){const re=ae[1]??ae[2];if(!re)continue;const Se=R.get(re)??[];Se.push({messageId:Re.id,messageIndex:G,citationIndex:Ce}),R.set(re,Se),Ce++}}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]);Bi(x),l.useEffect(()=>{if(t){const R=t.getBaseUrl();R&&Oi(R)}},[t]),l.useEffect(()=>{ke.debug("Connection status changed",{status:r}),r==="error"&&g&&ke.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),y(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&&($(A.tools),ke.info("Agent tools loaded",{tools:A.tools})),A.mcps&&A.mcps.length>0&&(D(A.mcps),ke.info("Agent MCPs loaded",{mcps:A.mcps})),A.subagents&&A.subagents.length>0&&(M(A.subagents),ke.info("Agent subagents loaded",{subagents:A.subagents})),A.promptParameters&&A.promptParameters.length>0&&(_(A.promptParameters),ke.info("Agent prompt parameters loaded",{promptParameters:A.promptParameters})),A.uiConfig?.hideTopBar&&W(!0)}},[t,r]);const Q=R=>{Y(R)},z=()=>{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(en,{className:"h-4 w-4"}):e.jsx(tn,{className:"h-4 w-4"}),category:"action",onSelect:()=>{P(S==="dark"?"light":"dark"),ke.info("User toggled theme",{newTheme:S==="dark"?"light":"dark"})}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx(Wt,{className:"h-4 w-4"}),category:"action",onSelect:()=>{ke.info("User opened settings")}}];return e.jsxs(Cn,{defaultOpen:!1,children:[e.jsx(mi,{client:t,currentSessionId:a}),e.jsx(kn,{children:e.jsxs(Qn,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsxs(Gn,{children:[!U&&e.jsx(qi,{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(Xn,{children:[e.jsx(Jn,{children:u.length===0?x!==void 0?e.jsx(Hi,{children:({openFiles:R,openSettings:A})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Un,{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..."),ke.info("Prompt clicked",{prompt:J})},onPromptHover:Q,onPromptLeave:z,onOpenFiles:R,onOpenSettings:A,toolsAndMcpsCount:C.length+B.length+I.length})})}):null:e.jsx("div",{className:"flex flex-col px-4 py-4 gap-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,Re=V!==null&&A>V;return e.jsx(la,{message:R,className:b("group",Re&&"opacity-50"),isLastMessage:A===u.length-1,children:e.jsx("div",{className:b("flex flex-col w-full min-w-0"),children:R.role==="user"?e.jsx(sl,{message:R,messageIndex:G,isStreaming:J,onEditAndResend:m,onEditingChange:ne=>{T(ne?A:null)}}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{message:R,thinkingDisplayStyle:"collapsible"}),(()=>{const ne=A===u.findLastIndex(ae=>ae.role==="assistant");return ne&&R.isStreaming?null:e.jsx(cl,{message:R,isStreaming:R.isStreaming,onSendMessage:d,isLastAssistantMessage:ne,onRedo:()=>{let ae=null,Ce=-1;for(let re=A-1;re>=0;re--)if(u[re]?.role==="user"){ae=u[re],Ce=u.slice(0,re+1).filter(Se=>Se.role==="user").length-1;break}if(ae?.content&&Ce>=0){const re=ae.images?.map((Se,va)=>({name:`image-${va}`,path:"",size:0,mimeType:Se.mimeType,data:Se.data}));m(Ce,ae.content,re)}}})})()]})})},R.id)})})}),e.jsx(Zn,{children:e.jsx(Wi,{client:t,startSession:c,placeholder:K,commandMenuItems:X,onCancel:p,promptParameters:E})})]})]}),e.jsx(ea,{breakpoint:"md",children:e.jsx(Vi,{todos:k,sources:O,tools:C,mcps:B,subagents:I,sessionId:a,agentApiUrl:t?.getBaseUrl(),client:t})})]})})]})}const Ft=l.forwardRef(({sourceId:t,sources:s,className:n},o)=>{const r=s.find(u=>u.id===t);let i=null;try{i=Ee()}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:b("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||Yi(r.url);return e.jsx(he,{delayDuration:200,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsxs("span",{ref:o,role:"button",tabIndex:0,onClick:a,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&a(u)},className:b("inline-flex items-center gap-1 px-1.5 py-0.5","text-xs font-medium rounded-md","bg-accent/50 text-accent-foreground","hover:bg-accent cursor-pointer transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",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(ye,{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(oo,{className:"size-3"}),e.jsx("span",{children:"Click to open"})]})]})})]})})});Ft.displayName="CitationChip";function Yi(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}const Qi=2e5;function os(t){const s=Math.max(t.totalEstimated,t.llmReportedInputTokens??0),n=t.modelContextWindow??Qi,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 aa({contextSize:t}){const{actualTokens:s,formattedPercentage:n,colorClass:o,calculatePercentage:r}=os(t);return e.jsx(ye,{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:b("flex justify-end gap-2 font-semibold",o),children:[e.jsx("span",{children:s.toLocaleString()}),e.jsxs("span",{children:["(",n,")"]})]})})]})})}function oa({contextSize:t,className:s,size:n=12}){if(t==null)return null;const{colorClass:o,clampedPercentage:r}=os(t),i=2,a=(n-i)/2,c=n/2,u=2*Math.PI*a,d=u-r/100*u;return e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{className:b("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(aa,{contextSize:t})]})})}const ra=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}=os(i);return e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(le,{ref:o,type:"button",variant:"ghost",size:"icon",className:b("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(aa,{contextSize:i})]})})});ra.displayName="ContextUsageButton";const Gi=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 y=l.useCallback(()=>{const v=m.current;if(!v)return;const{scrollTop:C,scrollHeight:$,clientHeight:B}=v,I=$-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=()=>{y()};return v.addEventListener("scroll",C,{passive:!0}),y(),()=>{v.removeEventListener("scroll",C)}},[y]),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:b("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"]})})]})});Gi.displayName="Conversation";const Xi=Ws,ia=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{ref:n,className:b("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s}));ia.displayName=Nt.displayName;const Ji=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Xi,{children:[e.jsx(ia,{}),e.jsxs(Ct,{ref:o,className:b("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[s,e.jsxs(Vs,{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"})]})]})]}));Ji.displayName=Ct.displayName;const Zi=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:b("text-subheading font-semibold leading-none tracking-tight",t),...s}));Zi.displayName=St.displayName;const el=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:b("text-paragraph-sm text-muted-foreground",t),...s}));el.displayName=kt.displayName;function tl({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){pe.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),d(!0),pe.success("Copied to clipboard!"),setTimeout(()=>{d(!1)},2e3)}catch{pe.error("Failed to copy to clipboard")}},[t.content]),h=l.useCallback(()=>{n||c(!0)},[n]);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]),y=l.useCallback(()=>{const v=p.current?.textContent||"";if(!v.trim())return;const C=t.images?.map(($,B)=>({name:`image-${B}`,path:"",size:0,mimeType:$.mimeType,data:$.data}));o(s,v.trim(),C),c(!1)},[s,t.images,o]),N=l.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),y()),v.key==="Escape"&&(v.preventDefault(),f())},[y,f]);return e.jsxs("div",{ref:m,className:"w-full group/user-message",children:[e.jsx("div",{className:b("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:b("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:b("whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-foreground leading-relaxed outline-none",a&&"cursor-text",!a&&"cursor-default"),children:t.content})]})}),t.content&&e.jsx("div",{className:"mt-2",children:e.jsx(Xt,{className:b("justify-end transition-opacity",a?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none group-hover/user-message:opacity-100 group-hover/user-message:pointer-events-auto"),children:a?e.jsxs(e.Fragment,{children:[e.jsx(le,{variant:"ghost",size:"sm",onClick:f,className:"h-7 px-2 text-xs text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsx(le,{size:"sm",disabled:n,onClick:y,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(Vt,{className:"size-4"})}),e.jsx(Ve,{disabled:n,onClick:h,tooltip:n?"Wait for agent to finish":"Edit",children:e.jsx(ro,{className:"size-4"})})]})})})]})}const sl=l.memo(tl,(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 nl(t,s,n,o,r){const i=n==="triggered",a=o==="no_action_needed";return t==="context_size"?i?{icon:de,title:"Compacting Context..."}:{icon:de,title:a?"Context Check":"Context Compacted"}:t==="tool_response"?s==="mid_turn_compaction"||r===!0?i?{icon:de,title:"Compacting Context..."}:{icon:de,title:a?"Context Check":"Context Compacted"}:i?{icon:de,title:"Compacting Response..."}:{icon:de,title:a?"Response Check":"Tool Response Compacted"}:{icon:de,title:i?"Running Hook...":"Hook Executed"}}function Pe(t){return t.toLocaleString()}function al(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}=nl(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?`${Pe(f)} messages summarized, `:""}${Pe(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=`${Pe(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(qt,{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(ge,{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:Pe(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:Pe(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:[Pe(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:[Pe(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(io,{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:"," ",al((t.completedAt-t.triggeredAt)/1e3)]})]})]})})]})]})}const ol=l.forwardRef(({className:t,...s},n)=>e.jsx(qs,{ref:n,className:b("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...s}));ol.displayName=qs.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:b("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:b("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:b("markdown-content prose prose-sm max-w-none dark:prose-invert",s),children:e.jsx(wa,{remarkPlugins:[rn],components:n,children:t})})}const rl=Ie("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"}}),la=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 $=v.clientHeight,B=C.offsetHeight,I=Math.max(0,$-B-32);h(I)};f();const y=new ResizeObserver(f);if(g.current){y.observe(g.current);let N=g.current.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;N&&y.observe(N)}return()=>y.disconnect()},[c,m]),l.useEffect(()=>{if((a!==void 0?a:m==="user")&&g.current){const y=setTimeout(()=>{g.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(y)}},[m,a]),e.jsx("article",{ref:g,id:p?`message-${p}`:void 0,"aria-label":`${m} message`,"data-message-id":p,className:b(rl({role:m,layout:n}),o),style:{minHeight:x!==void 0?`${x}px`:void 0},...u,children:r})});la.displayName="Message";const il=[{id:"pdf",label:"PDF",icon:We},{id:"excel",label:"Excel",icon:ds},{id:"csv",label:"CSV",icon:ds},{id:"text",label:"Text",icon:co},{id:"markdown",label:"Markdown",icon:We}];function ll({message:t,isStreaming:s,onRedo:n,onSendMessage:o,isLastAssistantMessage:r=!1}){const[i,a]=l.useState(!1);if(t.role!=="assistant"||!t.content?.trim())return null;const c=r?"":"opacity-0 group-hover:opacity-100 transition-opacity",u=!!s,d=!!t.content&&!u,m=async()=>{if(!t.content||u){pe.error("There's no text to copy!");return}try{await navigator.clipboard.writeText(t.content),a(!0),pe.success("Copied to clipboard!"),setTimeout(()=>{a(!1)},2e3)}catch{pe.error("Failed to copy to clipboard")}},p=()=>{u||(n?n():pe.info("Regenerate not available"))},g=x=>{u||(o?o(`produce an artifact as ${x} for this session`):pe.info("Export not available"))};return e.jsx("div",{className:"mt-2",children:e.jsxs(Xt,{className:b(c,r?"pointer-events-auto":"pointer-events-none group-hover:pointer-events-auto"),children:[e.jsx(Ve,{disabled:!d,onClick:m,tooltip:i?"Copied!":"Copy",children:i?e.jsx(lt,{className:"size-4"}):e.jsx(Vt,{className:"size-4"})}),e.jsx(Ve,{disabled:u,onClick:p,tooltip:"Redo",children:e.jsx(lo,{className:"size-4"})}),e.jsxs(ut,{children:[e.jsx(he,{children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(mt,{asChild:!0,children:e.jsxs(le,{className:b("relative size-7 p-1.5 text-muted-foreground hover:text-foreground"),disabled:u,size:"sm",type:"button",variant:"ghost",children:[e.jsx(on,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Export"})]})})}),e.jsx(ye,{children:e.jsx("p",{children:"Export"})})]})}),e.jsx(qe,{align:"start",children:il.map(x=>e.jsxs(je,{onClick:()=>g(x.label),children:[e.jsx(x.icon,{className:"size-4 mr-2"}),x.label]},x.id))})]})]})})}const cl=l.memo(ll,(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)),dl={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 ul(t,s){if(!s||!t.rawInput)return null;const n=t.rawInput[s];return typeof n=="string"?n:null}function ml(t,s){let n=t;for(const[o,r]of Object.entries(s))n=n.replace(`{${o}}`,r);return n}function pl(t,s){return t.length<=s?t:`${t.substring(0,s-1)}…`}function jt(t,s){const n=t.verbiage||dl[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=ul(t,n.paramKey);if(r){const i=pl(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"),ml(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 fl(t){return t.prettyName||t.title}function Ue(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":Ue(t)?"selecting":(t.status==="pending"||t.status==="in_progress","executing")}function ca(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 gl(t){return t.every(s=>gt(s)==="completed")}function hl(t){return t.some(s=>gt(s)==="failed")}function xl(t){return hl(t)?"failed":gl(t)?"completed":t.every(s=>Ue(s))?"selecting":"executing"}const ks=Ie("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"}}),bl=Ie("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),da=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:b(ks({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:b("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(ge,{className:bl({expanded:p}),"aria-hidden":"true"})]}),p&&e.jsx("div",{className:b(ks({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:"..."})]})})]})});da.displayName="Reasoning";function yl(){return t=>{Ra(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=me("Response","debug");function vl(t){const s=/[",\n\r]/.test(t),n=t.replaceAll('"','""');return s?`"${n}"`:n}function Ts(t){return Array.from(t.querySelectorAll("tr")).map(n=>Array.from(n.querySelectorAll("th,td")).map(r=>vl((r.textContent||"").trim())).join(",")).join(`
|
|
9
|
+
`)}function wl(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 jl(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=Ts(u);await navigator.clipboard.writeText(d),i(!0),pe.success("Copied table as CSV"),setTimeout(()=>i(!1),1500)}catch{pe.error("Failed to copy table")}},[]),c=l.useCallback(()=>{const u=o.current;if(!u)return;const d=Ts(u);wl("table.csv",d,"text/csv;charset=utf-8"),pe.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:b("min-w-full border-collapse border border-border rounded-md",s),...n})}),e.jsxs(Xt,{className:b("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(Vt,{className:"size-4"})}),e.jsx(Ve,{onClick:c,tooltip:"Download CSV",children:e.jsx(on,{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(()=>[rn,yl],[]),x=l.useMemo(()=>{const h={current:0};return{table:f=>e.jsx(jl,{...f}),thead:f=>e.jsx("thead",{className:b("bg-card border-b border-border",f.className),...f}),tr:f=>e.jsx("tr",{className:b("border-b border-border hover:bg-card transition-colors",f.className),...f}),th:f=>e.jsx("th",{className:b("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:b("px-4 py-2 text-foreground border-r border-border last:border-r-0",f.className),...f}),span:f=>{const{className:y,class:N,"data-citation-id":v,children:C,...$}=f,B=y||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(Ft,{sourceId:v,sources:r})}):e.jsx(Ft,{sourceId:v,sources:r})}return e.jsx("span",{className:B,...$,children:C})}}},[r,i,a]);return!t&&s&&n?e.jsx("div",{ref:d,className:b("opacity-70 italic text-paragraph-sm",c),...u,children:o}):t?e.jsx("div",{ref:d,...u,children:e.jsx(_a,{className:b("size-full","[&>*:first-child]:mt-0 [&>*:last-child]:mb-0","[&_code]:whitespace-pre-wrap [&_code]:break-words","[&_pre]:max-w-full [&_pre]:overflow-x-auto",c),remarkPlugins:g,components:x,children:t},`streamdown-${m}`)}):null}),(t,s)=>t.content===s.content&&t.sources===s.sources);Fe.displayName="Response";function Nl(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 Bt(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 Cl(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 Sl(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(Nl).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=Cl(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"} ${Bt(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"} ${Bt(r)}`;const c=fl(n);return`${s==="active"?"Using":"Used"} ${c} ${t.length} times`}function kl(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 Sl(t,s);const o=t.map(i=>i.prettyName||i.title).filter((i,a,c)=>c.indexOf(i)===a);return`${s==="active"?"Running":"Ran"} ${Bt(o)}`}const Tl=50;function ua({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",y=h[h.length-1],N=y&&(y.content||y.toolCalls&&y.toolCalls.length>0||y.contentBlocks&&y.contentBlocks.length>0),v=l.useRef(f);l.useEffect(()=>{v.current&&!f&&m(!1),v.current=f},[f]);const C=l.useCallback(()=>{const M=x.current;if(!M)return;const{scrollTop:E,scrollHeight:_,clientHeight:K}=M,Y=_-E-K;g(Y<Tl)},[]),$=l.useCallback(()=>{const M=x.current;M&&(M.scrollTop=M.scrollHeight)},[]);l.useEffect(()=>{p&&(f||N)&&$()},[p,f,N,$]),l.useEffect(()=>{const M=x.current;if(!M)return;const E=()=>C();return M.addEventListener("scroll",E,{passive:!0}),C(),()=>M.removeEventListener("scroll",E)},[C]),l.useEffect(()=>{d&&(g(!0),requestAnimationFrame(()=>{$()}))},[d,$]);const B=y?.content&&y.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:y?._meta?.currentActivity?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:y._meta.currentActivity}):y?._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(ge,{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..."}),y&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[y.contentBlocks&&y.contentBlocks.length>0?y.contentBlocks.map((M,E)=>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:M.text})},`text-${M.text.slice(0,30)}-${E}`):e.jsx(Tl,{toolCall:M.toolCall},M.toolCall.id)):y.content&&e.jsx("div",{className:"text-[11px] text-foreground prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(Dt,{content:y.content})}),y.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!f&&y?.content&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Output"}),e.jsx("div",{className:"text-[11px] text-foreground max-h-[200px] overflow-y-auto rounded-md bg-muted/30 border border-border/50 px-2 py-2 prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(Dt,{content:y.content})})]})]})]})}function Tl({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(qt,{className:"h-2.5 w-2.5 animate-spin"})]})}function Il({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:b("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 Is={Globe:sn,Image:ho,Link:go,Cloud:fo,CheckSquare:_t,Search:po,FileText:We,Edit:mo,Wrench:uo,BrainCircuit:co,CircleDot:Kt};function Rl(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 ma(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=Rl(t,s);return e.jsx("span",{className:"text-xs text-text-secondary/70 tabular-nums ml-1",children:ma(n)})}function _l({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(de,{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,y=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]),[$,B]=l.useState(!1),D=et.useContext(Zt),I=s?hl(t):m?gt(m):"executing",M=I==="completed",E=I==="failed",_=I==="selecting";l.useEffect(()=>{if(n&&M&&!a&&!u){const T=setTimeout(()=>{c(!0),i(!1)},500);return()=>clearTimeout(T)}},[n,M,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(!$)):(d(!0),i(!r),a&&c(!1))},[p,D,r,a,m,N,$]),U=s?us:m?.icon&&Is[m.icon]?Is[m.icon]:Kt,V=s?Sl(t,M?"past":"active"):m?ca(m):"Tool operation";if(_&&!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(U,{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(_&&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(us,{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(U,{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(oa,{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}),E&&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(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:y?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{children:y?"Some responses were truncated":"Some responses were compacted"})]})}),!s&&x&&e.jsx(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:h?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{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(ge,{className:"h-3 w-3"})})]}),!s&&m&&(p&&m.rawInput?.todos?e.jsx(Il,{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(ua,{parentStatus:m.status,agentName:m.rawInput?.agentName,query:m.rawInput?.query,isExpanded:$,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(Ml,{toolCall:T,...k?{hookNotification:k}:{}},T.id)})}):m&&e.jsx(pa,{toolCall:m,...g?{hookNotification:g}:{}})})]})}function Ml({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(Kt,{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(oa,{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(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{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(ge,{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(ua,{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(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{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(ge,{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(pa,{toolCall:t,...s?{hookNotification:s}:{}})})]})}function El(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 pa({toolCall:t,hookNotification:s}){const{resolvedTheme:n}=Jt(),[o,r]=l.useState(!1);if(De(t))return e.jsx("div",{className:"text-paragraph-sm text-text-secondary/70 ml-2",children:ca(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(is,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:i})})]}),t._meta?.compactionAction&&e.jsx(_l,{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(is,{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=El(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(xo,{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(ge,{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:"," ",ma((t.completedAt-t.startedAt)/1e3)]})]})]})]})]})}const Pl=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"}}),Rs=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g;function bt(t){Rs.lastIndex=0;let s=0;for(;Rs.exec(t)!==null;)s++;return s}function Xe(t){return t.replace(/\n+$/g,"")}const fa=l.forwardRef(({role:t,variant:s,isStreaming:n,message:o,thinkingDisplayStyle:r="collapsible",className:i,children:a,...c},u)=>{const d=H(y=>y.streamingStartTime);H(y=>y.currentModel);const m=H(y=>y.sources),p=l.useMemo(()=>{const y=new Map;for(const N of m)y.set(N.id,N);if(o?.sources)for(const N of o.sources)y.set(N.id,N);return Array.from(y.values())},[m,o?.sources]),g=o&&!a,x=g?o.role:t||"assistant",h=g?o.isStreaming:n;let f=a;if(g){const y=o.metadata?.thinking,N=!!y,v=o.isStreaming&&!o.content&&o.role==="assistant";f=e.jsxs(e.Fragment,{children:[o.role==="assistant"&&N&&e.jsx("div",{children:e.jsx(da,{content:y,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)),$=j=>{const O=[],Q=new Map;let z=[],X=[],R=null;const A=()=>{z.length>1?O.push({type:"selecting",toolCalls:z}):z.length===1&&O.push(z[0]),z=[]},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 ce=[G];Q.set(G.batchId,ce),O.push({type:"batch",toolCalls:ce})}}else De(G)?(J(),z.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,M=(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,z=B.filter(X=>X.toolCallId===Q.id);return e.jsx(Pe,{toolCalls:[Q],isGrouped:!1,hookNotifications:z},Q.id)},E=(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=$(C);if(!E.some(R=>R.contentPosition!==void 0))return e.jsxs("div",{className:"flex flex-col gap-2",children:[E.length>0&&e.jsx("div",{className:"flex flex-col gap-2",children:E.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)=>M(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 z=0,X=0;if(E.forEach(R=>{const A=R.contentPosition??o.content.length;if(A>z){const J=o.content.slice(z,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)),z=A}),z<o.content.length){const R=o.content.slice(z),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(M(R,A))}),e.jsx("div",{className:"flex flex-col gap-2",children:Q})}const _=[],K=[],Y=C.filter(De);C.filter(j=>!De(j)).forEach(j=>{K.push({type:"toolCall",item:j,position:j.contentPosition??o.content.length})}),E.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?_.push(e.jsx(Pe,{toolCalls:T,isGrouped:!0},`group-${k||S}-${T[0]?.id}`)):T.length===1&&_.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 z=o.content.slice(W,Q),X=Xe(z);if(X){const R=(j.type==="toolCall",j.item.id);_.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(),_.push(e.jsx(Pt,{notification:j.item},j.item.id));else{const z=j.item;z.title==="todo_write"?(P(),T=[z],P()):z.batchId?k===z.batchId?T.push(z):(P(),k=z.batchId,S=z.title,T=[z]):S===z.title&&!k?T.push(z):(P(),S=z.title,T=[z])}W=Q,O===K.length-1&&P()}),W<o.content.length){const j=o.content.slice(W),O=Xe(j);O&&(_.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?_.push(e.jsx(Pe,{toolCalls:Y,isGrouped:!0},`selecting-group-${Y[0]?.id}`)):_.push(e.jsx("div",{children:e.jsx(Pe,{toolCalls:[Y[0]],isGrouped:!1})},`tool-${Y[0]?.id}`))),I&&_.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.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,$)=>e.jsx("img",{src:`data:${C.mimeType};base64,${C.data}`,alt:`Attachment ${$+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:b(Pl({role:x,variant:s}),h&&"animate-pulse-subtle",i),...c,children:f})});fa.displayName="MessageContent";const ga=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:nn},{id:"sources",label:"Sources",icon:an},{id:"settings",label:"Settings",icon:Wt}].filter(d=>s.includes(d.id)),u=n==="compact"?"gap-[4px]":"gap-3";return e.jsx(He,{ref:i,className:b("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:b("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground hover:text-foreground transition-colors"),children:[t&&m&&e.jsx(m,{className:"size-4"}),d.label]},d.id)})})});ga.displayName="PanelTabsHeader";const Dl=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Ks,{ref:o,className:b("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-paragraph-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[s,e.jsx(La,{asChild:!0,children:e.jsx(bo,{className:"h-4 w-4 opacity-50"})})]}));Dl.displayName=Ks.displayName;const ha=l.forwardRef(({className:t,...s},n)=>e.jsx(Ys,{ref:n,className:b("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(yo,{className:"h-4 w-4"})}));ha.displayName=Ys.displayName;const xa=l.forwardRef(({className:t,...s},n)=>e.jsx(Qs,{ref:n,className:b("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ge,{className:"h-4 w-4"})}));xa.displayName=Qs.displayName;const Ul=l.forwardRef(({className:t,children:s,position:n="popper",...o},r)=>e.jsx(Oa,{children:e.jsxs(Gs,{ref:r,className:b("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",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(ha,{}),e.jsx(Fa,{className:b("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(xa,{})]})}));Ul.displayName=Gs.displayName;const zl=l.forwardRef(({className:t,...s},n)=>e.jsx(Xs,{ref:n,className:b("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));zl.displayName=Xs.displayName;const $l=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Js,{ref:o,className:b("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ba,{children:e.jsx(lt,{className:"h-4 w-4"})})}),e.jsx(Ha,{children:s})]}));$l.displayName=Js.displayName;const Ll=l.forwardRef(({className:t,...s},n)=>e.jsx(Zs,{ref:n,className:b("-mx-1 my-1 h-px bg-muted",t),...s}));Ll.displayName=Zs.displayName;const Ol=Ws,ba=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{className:b("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s,ref:n}));ba.displayName=Nt.displayName;const Fl=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"}}),Bl=l.forwardRef(({side:t="right",className:s,children:n,...o},r)=>e.jsxs(Ol,{children:[e.jsx(ba,{}),e.jsxs(Ct,{ref:r,className:b(Fl({side:t}),s),...o,children:[n,e.jsxs(Vs,{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"})]})]})]}));Bl.displayName=Ct.displayName;const Hl=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:b("text-lg font-semibold text-foreground",t),...s}));Hl.displayName=St.displayName;const Wl=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:b("text-sm text-muted-foreground",t),...s}));Wl.displayName=kt.displayName;function Vl({className:t}){const{toggleSidebar:s,open:n}=_e();return e.jsx(Re,{className:b(t),"data-testid":"sidebar-toggle-button","data-state":n?"open":"closed",onClick:s,"aria-label":"Toggle sidebar",children:e.jsx(vo,{className:"size-4 text-muted-foreground"})})}const ya=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:qt,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:b("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:b("w-full flex items-center gap-3 px-3 py-2.5 text-left",d&&s&&"cursor-pointer"),disabled:!d&&!s,children:[e.jsx(m,{className:b("w-4 h-4 shrink-0",p(),t.status==="in_progress"&&"animate-spin")}),e.jsx("span",{className:b("flex-1 text-paragraph-sm font-[var(--font-family)]",t.status==="completed"&&"line-through opacity-60",t.status==="in_progress"&&"font-medium"),children:t.text}),d&&s&&e.jsx(ge,{className:b("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))})]})]})]})});ya.displayName="Subagent";const ql=l.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:n,emptyMessage:o="No subagents yet.",className:r,...i},a)=>e.jsx("div",{ref:a,className:b("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(ya,{task:c,collapsible:s,...n?{onTaskClick:n}:{}},c.id))}));ql.displayName="SubagentList";const Kl=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"}}),Yl=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:b(Kl({variant:o}),s&&"overflow-y-hidden",t),ref:c,...r})});Yl.displayName="Textarea";function Ql(){return"http://localhost:3100"}const _s={agentServerUrl:Ql(),debuggerUrl:void 0};function Gl(){const{client:t,error:s,sessionId:n}=sr({serverUrl:_s.agentServerUrl});return e.jsx(ci,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(qi,{client:t,initialSessionId:n,error:s,..._s.debuggerUrl})})}const Xl="bibliotecha_auth";function Jl(t){return document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`))?.[2]??null}async function Zl(){new URLSearchParams(window.location.search).get("token"),Jl(Xl);const s=document.getElementById("root");if(!s)throw new Error("Root element not found");wa.createRoot(s).render(e.jsx(et.StrictMode,{children:e.jsx(Gl,{})}))}Zl();
|
|
11
|
+
`)[0]??"").slice(0,100)+(n.length>100?"...":""):"";return e.jsxs("div",{children:[!u&&e.jsx("div",{className:"w-full max-w-md",children:y?._meta?.currentActivity?e.jsx("p",{className:"text-paragraph-sm text-muted-foreground/70 truncate",children:y._meta.currentActivity}):y?._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(ge,{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..."}),y&&e.jsxs("div",{className:"px-2 py-2 space-y-2",children:[y.contentBlocks&&y.contentBlocks.length>0?y.contentBlocks.map((M,E)=>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:M.text})},`text-${M.text.slice(0,30)}-${E}`):e.jsx(Il,{toolCall:M.toolCall},M.toolCall.id)):y.content&&e.jsx("div",{className:"text-[11px] text-foreground prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(Dt,{content:y.content})}),y.isStreaming&&e.jsx("span",{className:"inline-block w-1.5 h-3 bg-primary/70 ml-0.5 animate-pulse"})]})]})]}),!f&&y?.content&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-1.5 font-sans",children:"Output"}),e.jsx("div",{className:"text-[11px] text-foreground max-h-[200px] overflow-y-auto rounded-md bg-muted/30 border border-border/50 px-2 py-2 prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-pre:my-1 prose-code:text-[10px]",children:e.jsx(Dt,{content:y.content})})]})]})]})}function Il({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(qt,{className:"h-2.5 w-2.5 animate-spin"})]})}function Rl({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:b("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 Is={Globe:sn,Image:xo,Link:ho,Cloud:go,CheckSquare:_t,Search:fo,FileText:We,Edit:po,Wrench:mo,BrainCircuit:uo,CircleDot:Kt};function _l(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 ma(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=_l(t,s);return e.jsx("span",{className:"text-xs text-text-secondary/70 tabular-nums ml-1",children:ma(n)})}function Ml({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(de,{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 De({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,y=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]),[$,B]=l.useState(!1),D=et.useContext(Zt),I=s?xl(t):m?gt(m):"executing",M=I==="completed",E=I==="failed",_=I==="selecting";l.useEffect(()=>{if(n&&M&&!a&&!u){const T=setTimeout(()=>{c(!0),i(!1)},500);return()=>clearTimeout(T)}},[n,M,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(!$)):(d(!0),i(!r),a&&c(!1))},[p,D,r,a,m,N,$]),U=s?us:m?.icon&&Is[m.icon]?Is[m.icon]:Kt,V=s?kl(t,M?"past":"active"):m?ca(m):"Tool operation";if(_&&!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(U,{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(_&&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(us,{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(U,{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(oa,{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}),E&&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(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:y?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{children:y?"Some responses were truncated":"Some responses were compacted"})]})}),!s&&x&&e.jsx(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:h?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{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(ge,{className:"h-3 w-3"})})]}),!s&&m&&(p&&m.rawInput?.todos?e.jsx(Rl,{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(ua,{parentStatus:m.status,agentName:m.rawInput?.agentName,query:m.rawInput?.query,isExpanded:$,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(El,{toolCall:T,...k?{hookNotification:k}:{}},T.id)})}):m&&e.jsx(pa,{toolCall:m,...g?{hookNotification:g}:{}})})]})}function El({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(Kt,{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(oa,{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(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{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(ge,{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(ua,{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(he,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("span",{children:u?e.jsx(at,{className:"h-3 w-3 text-destructive"}):e.jsx(de,{className:"h-3 w-3 text-text-secondary/70"})})}),e.jsx(ye,{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(ge,{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(pa,{toolCall:t,...s?{hookNotification:s}:{}})})]})}function Al(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 Pl({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 pa({toolCall:t,hookNotification:s}){const{resolvedTheme:n}=Jt(),[o,r]=l.useState(!1);if(Ue(t))return e.jsx("div",{className:"text-paragraph-sm text-text-secondary/70 ml-2",children:ca(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(is,{value:t.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,shortenTextAfterLength:80,style:i})})]}),t._meta?.compactionAction&&e.jsx(Ml,{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(is,{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=Al(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(bo,{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(ge,{className:`h-3.5 w-3.5 text-text-secondary transition-transform duration-200 ${o?"rotate-180":""}`})]}),o&&e.jsx(Pl,{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:"," ",ma((t.completedAt-t.startedAt)/1e3)]})]})]})]})]})}const Dl=Ie("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"}}),Rs=/\[\[(\d+)\]\]|\[(\d+)\](?![:(])/g;function bt(t){Rs.lastIndex=0;let s=0;for(;Rs.exec(t)!==null;)s++;return s}function Xe(t){return t.replace(/\n+$/g,"")}const fa=l.forwardRef(({role:t,variant:s,isStreaming:n,message:o,thinkingDisplayStyle:r="collapsible",className:i,children:a,...c},u)=>{const d=H(y=>y.streamingStartTime);H(y=>y.currentModel);const m=H(y=>y.sources),p=l.useMemo(()=>{const y=new Map;for(const N of m)y.set(N.id,N);if(o?.sources)for(const N of o.sources)y.set(N.id,N);return Array.from(y.values())},[m,o?.sources]),g=o&&!a,x=g?o.role:t||"assistant",h=g?o.isStreaming:n;let f=a;if(g){const y=o.metadata?.thinking,N=!!y,v=o.isStreaming&&!o.content&&o.role==="assistant";f=e.jsxs(e.Fragment,{children:[o.role==="assistant"&&N&&e.jsx("div",{children:e.jsx(da,{content:y,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)),$=j=>{const O=[],Q=new Map;let z=[],X=[],R=null;const A=()=>{z.length>1?O.push({type:"selecting",toolCalls:z}):z.length===1&&O.push(z[0]),z=[]},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 ae=[G];Q.set(G.batchId,ae),O.push({type:"batch",toolCalls:ae})}}else Ue(G)?(J(),z.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=>!Ue(O));return j.length===0?!1:j.every(O=>gt(O)==="completed")},I=o.isStreaming&&C.length>0&&D()&&o.content.trim().length<50,M=(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(De,{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(De,{toolCalls:j.toolCalls,isGrouped:!0},`selecting-${j.toolCalls[0]?.id||O}`);const Q=j,z=B.filter(X=>X.toolCallId===Q.id);return e.jsx(De,{toolCalls:[Q],isGrouped:!1,hookNotifications:z},Q.id)},E=(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=$(C);if(!E.some(R=>R.contentPosition!==void 0))return e.jsxs("div",{className:"flex flex-col gap-2",children:[E.length>0&&e.jsx("div",{className:"flex flex-col gap-2",children:E.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)=>M(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 z=0,X=0;if(E.forEach(R=>{const A=R.contentPosition??o.content.length;if(A>z){const J=o.content.slice(z,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)),z=A}),z<o.content.length){const R=o.content.slice(z),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(M(R,A))}),e.jsx("div",{className:"flex flex-col gap-2",children:Q})}const _=[],K=[],Y=C.filter(Ue);C.filter(j=>!Ue(j)).forEach(j=>{K.push({type:"toolCall",item:j,position:j.contentPosition??o.content.length})}),E.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?_.push(e.jsx(De,{toolCalls:T,isGrouped:!0},`group-${k||S}-${T[0]?.id}`)):T.length===1&&_.push(e.jsx("div",{children:e.jsx(De,{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 z=o.content.slice(W,Q),X=Xe(z);if(X){const R=(j.type==="toolCall",j.item.id);_.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(),_.push(e.jsx(Pt,{notification:j.item},j.item.id));else{const z=j.item;z.title==="todo_write"?(P(),T=[z],P()):z.batchId?k===z.batchId?T.push(z):(P(),k=z.batchId,S=z.title,T=[z]):S===z.title&&!k?T.push(z):(P(),S=z.title,T=[z])}W=Q,O===K.length-1&&P()}),W<o.content.length){const j=o.content.slice(W),O=Xe(j);O&&(_.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?_.push(e.jsx(De,{toolCalls:Y,isGrouped:!0},`selecting-group-${Y[0]?.id}`)):_.push(e.jsx("div",{children:e.jsx(De,{toolCalls:[Y[0]],isGrouped:!1})},`tool-${Y[0]?.id}`))),I&&_.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.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,$)=>e.jsx("img",{src:`data:${C.mimeType};base64,${C.data}`,alt:`Attachment ${$+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:b(Dl({role:x,variant:s}),h&&"animate-pulse-subtle",i),...c,children:f})});fa.displayName="MessageContent";const ga=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:nn},{id:"sources",label:"Sources",icon:an},{id:"settings",label:"Settings",icon:Wt}].filter(d=>s.includes(d.id)),u=n==="compact"?"gap-[4px]":"gap-3";return e.jsx(He,{ref:i,className:b("w-full justify-start bg-transparent p-0 h-auto",u,o),...r,children:c.map(d=>{const m=d.icon;return e.jsxs(ze,{value:d.id,className:b("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-accent data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground hover:text-foreground transition-colors"),children:[t&&m&&e.jsx(m,{className:"size-4"}),d.label]},d.id)})})});ga.displayName="PanelTabsHeader";const Ul=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Ks,{ref:o,className:b("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-paragraph-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[s,e.jsx(Oa,{asChild:!0,children:e.jsx(yo,{className:"h-4 w-4 opacity-50"})})]}));Ul.displayName=Ks.displayName;const ha=l.forwardRef(({className:t,...s},n)=>e.jsx(Ys,{ref:n,className:b("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(vo,{className:"h-4 w-4"})}));ha.displayName=Ys.displayName;const xa=l.forwardRef(({className:t,...s},n)=>e.jsx(Qs,{ref:n,className:b("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ge,{className:"h-4 w-4"})}));xa.displayName=Qs.displayName;const zl=l.forwardRef(({className:t,children:s,position:n="popper",...o},r)=>e.jsx(Fa,{children:e.jsxs(Gs,{ref:r,className:b("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",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(ha,{}),e.jsx(Ba,{className:b("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(xa,{})]})}));zl.displayName=Gs.displayName;const $l=l.forwardRef(({className:t,...s},n)=>e.jsx(Xs,{ref:n,className:b("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",t),...s}));$l.displayName=Xs.displayName;const Ll=l.forwardRef(({className:t,children:s,...n},o)=>e.jsxs(Js,{ref:o,className:b("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-paragraph-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ha,{children:e.jsx(lt,{className:"h-4 w-4"})})}),e.jsx(Wa,{children:s})]}));Ll.displayName=Js.displayName;const Ol=l.forwardRef(({className:t,...s},n)=>e.jsx(Zs,{ref:n,className:b("-mx-1 my-1 h-px bg-muted",t),...s}));Ol.displayName=Zs.displayName;const Fl=Ws,ba=l.forwardRef(({className:t,...s},n)=>e.jsx(Nt,{className:b("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s,ref:n}));ba.displayName=Nt.displayName;const Bl=Ie("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"}}),Hl=l.forwardRef(({side:t="right",className:s,children:n,...o},r)=>e.jsxs(Fl,{children:[e.jsx(ba,{}),e.jsxs(Ct,{ref:r,className:b(Bl({side:t}),s),...o,children:[n,e.jsxs(Vs,{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"})]})]})]}));Hl.displayName=Ct.displayName;const Wl=l.forwardRef(({className:t,...s},n)=>e.jsx(St,{ref:n,className:b("text-lg font-semibold text-foreground",t),...s}));Wl.displayName=St.displayName;const Vl=l.forwardRef(({className:t,...s},n)=>e.jsx(kt,{ref:n,className:b("text-sm text-muted-foreground",t),...s}));Vl.displayName=kt.displayName;function ql({className:t}){const{toggleSidebar:s,open:n}=Me();return e.jsx(_e,{className:b(t),"data-testid":"sidebar-toggle-button","data-state":n?"open":"closed",onClick:s,"aria-label":"Toggle sidebar",children:e.jsx(wo,{className:"size-4 text-muted-foreground"})})}const ya=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:qt,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:b("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:b("w-full flex items-center gap-3 px-3 py-2.5 text-left",d&&s&&"cursor-pointer"),disabled:!d&&!s,children:[e.jsx(m,{className:b("w-4 h-4 shrink-0",p(),t.status==="in_progress"&&"animate-spin")}),e.jsx("span",{className:b("flex-1 text-paragraph-sm font-[var(--font-family)]",t.status==="completed"&&"line-through opacity-60",t.status==="in_progress"&&"font-medium"),children:t.text}),d&&s&&e.jsx(ge,{className:b("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))})]})]})]})});ya.displayName="Subagent";const Kl=l.forwardRef(({tasks:t,collapsible:s=!0,onTaskClick:n,emptyMessage:o="No subagents yet.",className:r,...i},a)=>e.jsx("div",{ref:a,className:b("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(ya,{task:c,collapsible:s,...n?{onTaskClick:n}:{}},c.id))}));Kl.displayName="SubagentList";const Yl=Ie("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"}}),Ql=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:b(Yl({variant:o}),s&&"overflow-y-hidden",t),ref:c,...r})});Ql.displayName="Textarea";function Gl(){return"http://localhost:3100"}const _s={agentServerUrl:Gl(),debuggerUrl:void 0};function Xl(){const{client:t,error:s,sessionId:n}=nr({serverUrl:_s.agentServerUrl});return e.jsx(di,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(Ki,{client:t,initialSessionId:n,error:s,..._s.debuggerUrl})})}const Jl="bibliotecha_auth";function Zl(t){return document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`))?.[2]??null}async function ec(){new URLSearchParams(window.location.search).get("token"),Zl(Jl);const s=document.getElementById("root");if(!s)throw new Error("Root element not found");ja.createRoot(s).render(e.jsx(et.StrictMode,{children:e.jsx(Xl,{})}))}ec();
|