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