@townco/gui-template 0.1.44 → 0.1.46
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-CrD5QpoU.js → acp-sdk-Dkgjnioq.js} +1 -1
- package/dist/assets/icons-DnvAZOSE.js +1 -0
- package/dist/assets/index-Bu11KnLt.css +1 -0
- package/dist/assets/index-CFPxv5KS.js +6 -0
- package/dist/assets/{markdown-PIOGdvNw.js → markdown-B17SHLT-.js} +1 -1
- package/dist/assets/{radix-BwF8w229.js → radix-C_VWc-Gz.js} +1 -1
- package/dist/assets/{react-BxIc-aOD.js → react-BNhDTjHq.js} +1 -1
- package/dist/assets/vendor-C8TUcKlD.js +48 -0
- package/dist/index.html +8 -8
- package/package.json +4 -4
- package/src/App.tsx +6 -1
- package/src/config.ts +9 -0
- package/dist/assets/icons-DfHRHe9q.js +0 -1
- package/dist/assets/index-CDHFf0CG.css +0 -1
- package/dist/assets/index-D3XLMip7.js +0 -6
- package/dist/assets/vendor-CDPxlbZ6.js +0 -48
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{r as d,j as e,P as zs,e as Ls,f as Fs,M as Os,b as Me,h as $s}from"./react-BNhDTjHq.js";import{S as le,L as Bs,M as Hs,N as Ws,O as X,P as _,Q as D,R as v,T as nt,U as B,W as H,X as Q,Y as J,Z as Vs,$ as xe,a0 as Ce,a1 as qs,a2 as Gs,a3 as Ks,a4 as Qs,a5 as re,a6 as Js,a7 as Ve}from"./vendor-C8TUcKlD.js";import{P as qe,a as Ys}from"./acp-sdk-Dkgjnioq.js";import{S as ye,a as at,b as ot,P as Xs,C as rt,I as it,c as lt,d as ct,R as dt,L as ut,e as pt,f as Zs,T as en,g as mt,h as ft,i as gt,j as tn,k as ht,l as sn,m as nn,n as an,O as xt,o as on,p as bt,q as rn,r as yt,D as wt,s as vt,t as jt,u as ln,v as Nt,w as St,x as cn,y as Ct,V as dn,z as Tt,A as kt,B as un,E as pn,F as It}from"./radix-C_VWc-Gz.js";import{C as fe,S as mn,P as fn,M as gn,A as hn,a as Rt,b as _e,F as xn,c as bn,d as yn,E as wn,e as ue,f as Et,g as Pe,h as De,D as At,L as Mt,i as _t,B as Ge,j as vn,X as Pt,k as jn,l as Dt,m as Ut,n as zt,W as Nn,o as Sn,p as Cn,q as Tn,r as kn,I as In,G as Rn,s as En,t as An,u as Mn,v as _n,w as Pn}from"./icons-DnvAZOSE.js";import{r as Dn}from"./markdown-B17SHLT-.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function a(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=a(r);fetch(r.href,i)}})();var Un={};const ve=typeof process<"u"&&process.versions?.node;let zn,Ln=0;const Fn=new Set;function On(s){for(const t of Fn)t(s)}const Ke={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},$n={trace:le.TRACE,debug:le.DEBUG,info:le.INFO,warn:le.WARN,error:le.ERROR,fatal:le.FATAL};class Bn{service;minLevel;logFilePath;logsDir;writeQueue=[];isWriting=!1;enableConsoleOutput;constructor(t,a="debug"){this.service=t,this.minLevel=a,typeof process<"u"&&(this.minLevel="info"),this.enableConsoleOutput=typeof process<"u"&&Un?.TOWN_LOG_CONSOLE==="true"||!1}setupFileLogging(){}async writeToFile(t){if(!(!this.logFilePath||!ve)&&(this.writeQueue.push(t),!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(t){return Ke[t]>=Ke[this.minLevel]}log(t,a,n){if(!this.shouldLog(t))return;const r={id:`log_${++Ln}`,timestamp:new Date().toISOString(),level:t,service:this.service,message:a,...n&&{metadata:n}};if(On(r),ve&&this.logFilePath,ve&&this.logFilePath){const m={timestamp:r.timestamp,level:r.level,service:r.service,message:r.message,...r.metadata&&{metadata:r.metadata}};this.writeToFile(JSON.stringify(m)).catch(()=>{})}if(ve&&this.enableConsoleOutput){const m=r.timestamp,p=r.level.toUpperCase().padEnd(5),c=`[${this.service}]`,u=r.metadata?` ${JSON.stringify(r.metadata)}`:"";console.log(`${m} ${p} ${c} ${r.message}${u}`)}const i=Bs.getLogger(this.service),o=Hs.getSpan(Ws.active());i.emit({severityNumber:$n[t],severityText:t.toUpperCase(),body:a,attributes:{service:this.service,...n&&{"log.metadata":JSON.stringify(n)},...o&&{trace_id:o.spanContext().traceId,span_id:o.spanContext().spanId}}})}trace(t,a){this.log("trace",t,a)}debug(t,a){this.log("debug",t,a)}info(t,a){this.log("info",t,a)}warn(t,a){this.log("warn",t,a)}error(t,a){this.log("error",t,a)}fatal(t,a){this.log("fatal",t,a)}}function ne(s,t="debug"){return new Bn(s,t)}const M=ne("http-transport");class Hn{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(t){this.options={...t,baseUrl:t.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const t={protocolVersion:qe,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},a=await this.sendRpcRequest("initialize",t);if(a.agentInfo){const i=a._meta,o=i&&typeof i=="object",m=o&&"agentDescription"in i?String(i.agentDescription):void 0,p=o&&"suggestedPrompts"in i&&Array.isArray(i.suggestedPrompts)?i.suggestedPrompts:void 0,c=o&&"tools"in i&&Array.isArray(i.tools)?i.tools:void 0,u=o&&"mcps"in i&&Array.isArray(i.mcps)?i.mcps:void 0,f=o&&"subagents"in i&&Array.isArray(i.subagents)?i.subagents:void 0;this.agentInfo={name:a.agentInfo.name,...a.agentInfo.title?{displayName:a.agentInfo.title}:{},version:a.agentInfo.version,...m?{description:m}:{},...p?{suggestedPrompts:p}:{},...c?{tools:c}:{},...u?{mcps:u}:{},...f?{subagents:f}:{}}}M.info("ACP connection initialized",{initResponse:a});const n={cwd:"/",mcpServers:[]},r=await this.sendRpcRequest("session/new",n);this.currentSessionId=r.sessionId,M.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(t){this.connected=!1;const a=t instanceof Error?t:new Error(String(t));throw this.notifyError(a),a}}async loadSession(t){this.connected&&(M.warn("Transport already connected, disconnecting first",{sessionId:t}),await this.disconnect());try{this.abortController=new AbortController;const a={protocolVersion:qe,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};M.info("Loading session - initializing connection",{sessionId:t});const n=await this.sendRpcRequest("initialize",a);if(n.agentInfo){const o=n._meta,m=o&&typeof o=="object",p=m&&"agentDescription"in o?String(o.agentDescription):void 0,c=m&&"suggestedPrompts"in o&&Array.isArray(o.suggestedPrompts)?o.suggestedPrompts:void 0,u=m&&"tools"in o&&Array.isArray(o.tools)?o.tools:void 0,f=m&&"mcps"in o&&Array.isArray(o.mcps)?o.mcps:void 0,l=m&&"subagents"in o&&Array.isArray(o.subagents)?o.subagents:void 0;this.agentInfo={name:n.agentInfo.name,...n.agentInfo.title?{displayName:n.agentInfo.title}:{},version:n.agentInfo.version,...p?{description:p}:{},...c?{suggestedPrompts:c}:{},...u?{tools:u}:{},...f?{mcps:f}:{},...l?{subagents:l}:{}}}if(!n.agentCapabilities?.loadSession)throw M.error("Agent does not support loading sessions",{capabilities:n.agentCapabilities}),new Error("Agent does not support loading sessions");M.info("ACP connection initialized, loading session",{sessionId:t,capabilities:n.agentCapabilities}),this.isInReplayMode=!0,this.currentSessionId=t,await this.connectSSE();const r={sessionId:t,cwd:"/",mcpServers:[]};M.info("Sending session/load request",{loadRequest:r});const i=await this.sendRpcRequest("session/load",r);M.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 M.error("Failed to load session",{sessionId:t,error:n.message,stack:n.stack}),this.notifyError(n),n}}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(t){const a=t instanceof Error?t:new Error(String(t));throw this.notifyError(a),a}}async send(t){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");this.isInReplayMode&&(M.info("Exiting replay mode - user sent a message"),this.isInReplayMode=!1);try{this.streamComplete=!1,this.messageQueue=[];const a=t.content.map(o=>o.type==="text"?{type:"text",text:o.text}:o.type==="image"?"source"in o&&o.source?{type:"image",data:o.source.data,mimeType:o.source.media_type}:"data"in o&&"mimeType"in o?{type:"image",data:o.data,mimeType:o.mimeType}:o:o),n={sessionId:this.currentSessionId,prompt:a},r=await this.sendRpcRequest("session/prompt",n);M.debug("Prompt sent",{promptResponse:r}),this.streamComplete=!0;const i=this.chunkResolvers.shift();i?i({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(a){this.streamComplete=!0;const n=a instanceof Error?a:new Error(String(a));throw this.notifyError(n),n}}async*receive(){this.isReceivingMessages=!0;try{for(;!this.streamComplete;)if(this.messageQueue.length>0){const t=this.messageQueue.shift();if(t&&(yield t,t.isComplete))return}else{const t=await new Promise(a=>{this.chunkResolvers.push(a)});if(t.isComplete){yield t;return}else yield t}for(;this.messageQueue.length>0;){const t=this.messageQueue.shift();t&&(yield t)}yield{id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}finally{this.isReceivingMessages=!1}}isConnected(){return this.connected}onSessionUpdate(t){return this.sessionUpdateCallbacks.add(t),()=>{this.sessionUpdateCallbacks.delete(t)}}onError(t){return this.errorCallbacks.add(t),()=>{this.errorCallbacks.delete(t)}}getAgentInfo(){return this.agentInfo||{}}async sendRpcRequest(t,a){const r={jsonrpc:"2.0",id:this.generateRequestId(),method:t,params:a};M.debug("Sending RPC request",{method:t,params:a,request:r});const i={"Content-Type":"application/json",...this.options.headers},o=this.options.timeout??600*1e3,m=new AbortController,p=setTimeout(()=>m.abort(),o);try{const c=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(r),signal:m.signal});if(clearTimeout(p),!c.ok){const f=await c.text();throw new Error(`HTTP ${c.status}: ${f}`)}const u=await c.json();if(u.error)throw new Error(`ACP error: ${u.error.message||JSON.stringify(u.error)}`);return u.result||u}catch(c){throw clearTimeout(p),c instanceof Error&&c.name==="AbortError"?new Error(`Request timeout after ${o}ms`):c}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const t=`${this.options.baseUrl}/events`,a={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const n=await fetch(t,{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");M.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const r=n.body.getReader(),i=new TextDecoder;let o="";(async()=>{try{for(;;){const{done:m,value:p}=await r.read();if(m){M.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}o+=i.decode(p,{stream:!0});const c=o.split(`
|
|
4
|
+
`);o=c.pop()||"";let u={event:"message",data:""};for(const f of c)f.startsWith("event:")?u.event=f.substring(6).trim():f.startsWith("data:")?u.data=f.substring(5).trim():f===""&&(u.event==="message"&&u.data&&this.handleSSEMessage(u.data),u={event:"message",data:""})}}catch(m){if(m instanceof Error&&m.name==="AbortError"){M.debug("SSE stream aborted");return}M.error("Error reading SSE stream",{error:m}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(n){throw M.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 t=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);M.debug("SSE reconnecting",{delay:t,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(a=>setTimeout(a,t));try{await this.connectSSE(),M.info("SSE reconnected successfully"),this.reconnecting=!1}catch(a){M.error("SSE reconnection failed",{error:a}),this.reconnecting=!1}}handleSSEMessage(t){try{const a=JSON.parse(t);M.debug("Received SSE message",{message:a});const n=Ys.safeParse(a);if(!n.success){M.error("Invalid ACP message from SSE",{issues:n.error.issues});return}const r=n.data;M.debug("Parsed ACP message",{method:"method"in r?r.method:"(no method)"}),"method"in r&&r.method==="session/update"&&(M.debug("Received session/update notification"),"params"in r&&r.params&&(M.debug("Calling handleSessionNotification",{params:r.params}),this.handleSessionNotification(r.params)))}catch(a){M.error("Error parsing SSE message",{error:a}),this.notifyError(a instanceof Error?a:new Error(String(a)))}}handleSessionNotification(t){M.debug("handleSessionNotification called",{params:t});const n=t.update,r=this.currentSessionId||t.sessionId;if(M.debug("Update session type",{sessionUpdate:n?.sessionUpdate}),n?.sessionUpdate==="tool_call"){M.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,o=n._meta&&typeof n._meta=="object"&&"prettyName"in n._meta&&typeof n._meta.prettyName=="string"?n._meta.prettyName:void 0,m=n._meta&&typeof n._meta=="object"&&"icon"in n._meta&&typeof n._meta.icon=="string"?n._meta.icon:void 0,p=n._meta&&typeof n._meta=="object"&&"subline"in n._meta&&typeof n._meta.subline=="string"?n._meta.subline:void 0,c=n._meta&&typeof n._meta=="object"&&"batchId"in n._meta&&typeof n._meta.batchId=="string"?n._meta.batchId:void 0,u={id:n.toolCallId??"",batchId:c,title:n.title??"",prettyName:o,icon:m,subline:p,kind:n.kind||"other",status:n.status||"pending",locations:n.locations,rawInput:n.rawInput,tokenUsage:n.tokenUsage,content:n.content?.map(l=>{if(typeof l!="object"||l===null)return{type:"text",text:""};const h=l;if(h.type==="content"&&typeof h.content=="object"&&h.content!==null){const y=h.content;if(y.type==="text")return{type:"content",content:{type:"text",text:typeof y.text=="string"?y.text:""}}}return h.type==="text"?{type:"text",text:typeof h.text=="string"?h.text:""}:h.type==="diff"?{type:"diff",path:typeof h.path=="string"?h.path:"",oldText:typeof h.oldText=="string"?h.oldText:"",newText:typeof h.newText=="string"?h.newText:"",line:typeof h.line=="number"?h.line:null}:h.type==="terminal"?{type:"terminal",terminalId:typeof h.terminalId=="string"?h.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now()},f={type:"tool_call",sessionId:r,status:"active",toolCall:u,messageId:i};this.notifySessionUpdate(f)}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,o=n._meta&&typeof n._meta=="object"&&"prettyName"in n._meta&&typeof n._meta.prettyName=="string"?n._meta.prettyName:void 0,m=n._meta&&typeof n._meta=="object"&&"icon"in n._meta&&typeof n._meta.icon=="string"?n._meta.icon:void 0,p=n._meta&&typeof n._meta=="object"&&"batchId"in n._meta&&typeof n._meta.batchId=="string"?n._meta.batchId:void 0,c={id:n.toolCallId??"",status:n.status,title:n.title,prettyName:o,icon:m,batchId:p,rawInput:n.rawInput,locations:n.locations,rawOutput:n.rawOutput,tokenUsage:n.tokenUsage,content:n.content?.map(f=>{if(typeof f!="object"||f===null)return{type:"text",text:""};const l=f;if(l.type==="content"&&typeof l.content=="object"&&l.content!==null){const h=l.content;if(h.type==="text")return{type:"content",content:{type:"text",text:typeof h.text=="string"?h.text:""}}}return l.type==="text"?{type:"text",text:typeof l.text=="string"?l.text:""}:l.type==="diff"?{type:"diff",path:typeof l.path=="string"?l.path:"",oldText:typeof l.oldText=="string"?l.oldText:"",newText:typeof l.newText=="string"?l.newText:"",line:typeof l.line=="number"?l.line:null}:l.type==="terminal"?{type:"terminal",terminalId:typeof l.terminalId=="string"?l.terminalId:""}:{type:"text",text:""}}),error:n.error,completedAt:n.status==="completed"||n.status==="failed"?Date.now():void 0},u={type:"tool_call_update",sessionId:r,status:"active",toolCallUpdate:c,messageId:i};M.debug("Notifying tool_call_update session update",{sessionUpdate:u}),this.notifySessionUpdate(u)}else if(n&&"sessionUpdate"in n&&n.sessionUpdate==="tool_output"){const i=n,o=i._meta&&typeof i._meta=="object"&&"messageId"in i._meta?String(i._meta.messageId):void 0,m={id:i.toolCallId??"",rawOutput:i.rawOutput,content:i.content?.map(c=>{if(typeof c!="object"||c===null)return{type:"text",text:""};const u=c;if(u.type==="content"&&typeof u.content=="object"&&u.content!==null){const f=u.content;if(f.type==="text")return{type:"content",content:{type:"text",text:typeof f.text=="string"?f.text:""}}}return u.type==="text"?{type:"text",text:typeof u.text=="string"?u.text:""}:u.type==="diff"?{type:"diff",path:typeof u.path=="string"?u.path:"",oldText:typeof u.oldText=="string"?u.oldText:"",newText:typeof u.newText=="string"?u.newText:"",line:typeof u.line=="number"?u.line:null}:u.type==="terminal"?{type:"terminal",terminalId:typeof u.terminalId=="string"?u.terminalId:""}:u.type==="image"?{type:"image",data:typeof u.data=="string"?u.data:"",mimeType:typeof u.mimeType=="string"?u.mimeType:"image/png",alt:typeof u.alt=="string"?u.alt:void 0}:{type:"text",text:""}})},p={type:"tool_call_update",sessionId:r,status:"active",toolCallUpdate:m,messageId:o};M.debug("Notifying tool_output as tool_call_update",{sessionUpdate:p}),this.notifySessionUpdate(p)}else if(n?.sessionUpdate==="agent_message_chunk"){const i=n._meta&&typeof n._meta=="object"&&"isReplay"in n._meta&&n._meta.isReplay===!0;if(this.isInReplayMode&&!i)return;const o=n._meta&&typeof n._meta=="object"&&"tokenUsage"in n._meta?n._meta.tokenUsage:void 0,m=n._meta&&typeof n._meta=="object"&&"contextInputTokens"in n._meta&&typeof n._meta.contextInputTokens=="number"?n._meta.contextInputTokens:void 0,p=n._meta&&typeof n._meta=="object"&&"context_size"in n._meta?n._meta.context_size:void 0,c={type:"generic",sessionId:r,status:"active",_meta:n._meta},u=n.content;if(u&&typeof u=="object"){const l=u;let h=null;if(l.type==="text"&&typeof l.text=="string"&&(h={id:t.sessionId,role:"assistant",contentDelta:{type:"text",text:l.text},tokenUsage:o,contextInputTokens:m,_meta:p?{context_size:p}:void 0,isComplete:!1}),h&&!i){const y=this.chunkResolvers.shift();y?y(h):this.messageQueue.push(h)}if(h&&typeof l.text=="string"&&(i||!this.isReceivingMessages)){const y={type:"generic",sessionId:r,status:"active",message:{id:`msg_${Date.now()}_assistant`,role:"assistant",content:[{type:"text",text:l.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(y)}}const f=c._meta&&"context_size"in c._meta;(!i||f)&&this.notifySessionUpdate(c)}else if(n?.sessionUpdate==="user_message_chunk"){M.debug("Received user_message_chunk",{update:n});const i=n.content;if(i&&typeof i=="object"){const o=i;if(o.type==="text"&&typeof o.text=="string"){const m={type:"generic",sessionId:r,status:"active",message:{id:`msg_${Date.now()}_user`,role:"user",content:[{type:"text",text:o.text}],timestamp:new Date().toISOString()}};M.debug("Notifying session update for user message"),this.notifySessionUpdate(m)}}}else{const i={type:"generic",sessionId:r,status:"active"};this.notifySessionUpdate(i)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(t){for(const a of this.sessionUpdateCallbacks)try{a(t)}catch(n){M.error("Error in session update callback",{error:n})}}notifyError(t){for(const a of this.errorCallbacks)try{a(t)}catch(n){M.error("Error in error callback",{error:n})}}}class Wn{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 Vn{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(t){}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(t){throw!this.connected||!this.ws?new Error("Transport not connected"):new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async*receive(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}isConnected(){return this.connected}onSessionUpdate(t){return this.sessionUpdateCallbacks.add(t),()=>{this.sessionUpdateCallbacks.delete(t)}}onError(t){return this.errorCallbacks.add(t),()=>{this.errorCallbacks.delete(t)}}}const Ae=ne("acp-client","debug");class qn{config;transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;constructor(t){this.config=t,this.transport=this.createTransport(),this.setupTransportListeners(),t.autoConnect&&this.connect().catch(a=>{Ae.error("Failed to auto-connect",{error:a instanceof Error?a.message:String(a)})})}async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(t){const a="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(a){const m=new Date().toISOString(),p=this.transport.getAgentInfo?.()?.name,c={id:a,status:"connected",config:t?{...t,agentPath:t.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:m,agentName:p}};return this.sessions.set(a,c),this.currentSessionId=a,a}const n=this.generateSessionId(),r=new Date().toISOString(),i=this.transport.getAgentInfo?.()?.name,o={id:n,status:"connecting",config:t?{...t,agentPath:t.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:r,agentName:i}};return this.sessions.set(n,o),this.currentSessionId=n,this.updateSessionStatus(n,"connected"),n}async loadSession(t,a){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const n=new Date().toISOString(),r={id:t,status:"connecting",config:a?{...a,agentPath:a.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:n}};if(this.sessions.set(t,r),this.currentSessionId=t,await this.transport.loadSession(t),this.transport.getAgentInfo){const i=this.transport.getAgentInfo();i.name&&r.metadata&&(r.metadata.agentName=i.name)}return this.updateSessionStatus(t,"connected"),t}async sendMessage(t,a,n){const r=a||this.currentSessionId;if(!r)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const i=this.sessions.get(r);if(!i)throw new Error(`Session ${r} not found`);const o=[];if(n&&n.length>0)for(const p of n)p.mimeType.startsWith("image/")&&o.push({type:"image",source:{type:"base64",media_type:p.mimeType,data:p.data}});o.push({type:"text",text:t});const m={id:this.generateMessageId(),role:"user",content:o,timestamp:new Date().toISOString()};i.messages.push(m),this.updateSessionStatus(r,"active"),await this.transport.send(m)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(t){return this.sessions.get(t)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(t){return this.sessionUpdateHandlers.add(t),()=>{this.sessionUpdateHandlers.delete(t)}}onError(t){return this.errorHandlers.add(t),()=>{this.errorHandlers.delete(t)}}getAgentInfo(){return this.transport.getAgentInfo?.()||{}}createTransport(){switch(this.config.type){case"stdio":return new Wn(this.config.options);case"http":return new Hn(this.config.options);case"websocket":return new Vn(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(t=>{this.handleSessionUpdate(t)}),this.transport.onError(t=>{this.handleError(t)})}handleSessionUpdate(t){if(t.sessionId){const a=this.sessions.get(t.sessionId);a&&(t.status&&(a.status=t.status),t.message&&a.messages.push(t.message),t.error&&(a.error=t.error))}for(const a of this.sessionUpdateHandlers)try{a(t)}catch(n){Ae.error("Error in session update handler",{error:n instanceof Error?n.message:String(n)})}}handleError(t){for(const a of this.errorHandlers)try{a(t)}catch(n){Ae.error("Error in error handler",{error:n instanceof Error?n.message:String(n)})}}updateSessionStatus(t,a){const n=this.sessions.get(t);n&&(n.status=a,this.handleSessionUpdate({sessionId:t,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 ce=ne("acp-client-hook");function Gn(s){const[t,a]=d.useState(null),[n,r]=d.useState(null),[i,o]=d.useState(null);return d.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("session");p&&(ce.info("Session ID found in URL",{sessionId:p}),o(p));try{ce.info("Initializing ACP client",{serverUrl:s.serverUrl});const c=new qn({type:"http",options:{baseUrl:s.serverUrl}});return a(c),ce.info("ACP client initialized successfully"),()=>{ce.debug("Disconnecting ACP client"),c.disconnect().catch(u=>{ce.error("Failed to disconnect ACP client",{error:u instanceof Error?u.message:String(u)})})}}catch(c){const u=c instanceof Error?c.message:"Failed to initialize ACP client";r(u),ce.error("Failed to initialize ACP client",{error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0});return}},[s.serverUrl]),{client:t,error:n,sessionId:i}}const Lt=X(["pending","in_progress","completed","failed"]),Kn=X(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),Ft=_({path:v(),line:D().nullable().optional()}),Ue=_({inputTokens:D().optional(),outputTokens:D().optional(),totalTokens:D().optional()}),Ot=nt("type",[_({type:B("content"),content:_({type:B("text"),text:v()})}),_({type:B("text"),text:v()}),_({type:B("image"),data:v(),mimeType:v().optional(),alt:v().optional()}),_({type:B("image"),url:v(),alt:v().optional()}),_({type:B("diff"),path:v(),oldText:v(),newText:v(),line:D().nullable().optional()}),_({type:B("terminal"),terminalId:v()})]),$t=_({id:v(),batchId:v().optional(),title:v(),prettyName:v().optional(),icon:v().optional(),subline:v().optional(),kind:Kn,status:Lt,contentPosition:D().optional(),locations:H(Ft).optional(),rawInput:Q(v(),J()).optional(),rawOutput:Q(v(),J()).optional(),content:H(Ot).optional(),error:v().optional(),startedAt:D().optional(),completedAt:D().optional(),tokenUsage:Ue.optional(),_meta:_({truncationWarning:v().optional(),compactionAction:X(["compacted","truncated"]).optional(),originalTokens:D().optional(),finalTokens:D().optional()}).optional()}),Qn=_({id:v(),status:Lt.optional(),title:v().optional(),prettyName:v().optional(),icon:v().optional(),batchId:v().optional(),rawInput:Q(v(),J()).optional(),locations:H(Ft).optional(),rawOutput:Q(v(),J()).optional(),content:H(Ot).optional(),error:v().optional(),completedAt:D().optional(),tokenUsage:Ue.optional()});function Qe(s,t){return{...s,status:t.status??s.status,title:t.title??s.title,prettyName:t.prettyName??s.prettyName,icon:t.icon??s.icon,batchId:t.batchId??s.batchId,rawInput:t.rawInput??s.rawInput,locations:t.locations??s.locations,rawOutput:t.rawOutput??s.rawOutput,content:t.content?[...s.content??[],...t.content]:s.content,error:t.error??s.error,completedAt:t.completedAt??s.completedAt,tokenUsage:t.tokenUsage??s.tokenUsage}}const de=ne("chat-store","debug"),Ne=[];let je={sessionId:null,toolCallId:null,todos:Ne};const Jn=s=>{const t=s.sessionId;if(!t)return Ne;const n=(s.toolCalls[t]||[]).filter(o=>o.title==="todo_write").sort((o,m)=>(m.startedAt||0)-(o.startedAt||0));if(n.length===0)return Ne;const r=n[0];if(!r?.rawInput?.todos||!Array.isArray(r.rawInput.todos))return Ne;if(je.sessionId===t&&je.toolCallId===r.id)return je.todos;const i=r.rawInput.todos.map((o,m)=>({id:`${r.id}-${m}`,text:o.status==="in_progress"?o.activeForm:o.content,status:o.status}));return je={sessionId:t,toolCallId:r.id,todos:i},i},R=Vs(s=>({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:t=>s({connectionStatus:t}),setSessionId:t=>s({sessionId:t}),setError:t=>s({error:t}),addMessage:t=>s(a=>({messages:[...a.messages,t]})),updateMessage:(t,a)=>s(n=>{const r=n.messages.find(c=>c.id===t);let i=n.totalBilled,o=n.currentContext,m=a;if(a.tokenUsage){const c=r?.tokenUsage;de.debug("updateMessage: incoming tokenUsage",{incoming:a.tokenUsage,existing:c});const u={inputTokens:Math.max(a.tokenUsage.inputTokens??0,c?.inputTokens??0),outputTokens:Math.max(a.tokenUsage.outputTokens??0,c?.outputTokens??0),totalTokens:Math.max(a.tokenUsage.inputTokens??0,c?.inputTokens??0)+Math.max(a.tokenUsage.outputTokens??0,c?.outputTokens??0)};de.debug("updateMessage: merged tokenUsage",{merged:u}),m={...a,tokenUsage:u};const f=u.inputTokens-(c?.inputTokens??0),l=u.outputTokens-(c?.outputTokens??0),h=u.totalTokens-(c?.totalTokens??0);i={inputTokens:n.totalBilled.inputTokens+f,outputTokens:n.totalBilled.outputTokens+l,totalTokens:n.totalBilled.totalTokens+h},o={inputTokens:u.inputTokens,outputTokens:n.currentContext.outputTokens+l,totalTokens:u.totalTokens}}const p=n.messages.map(c=>c.id===t?{...c,...m}:c);if(a.tokenUsage&&m.tokenUsage){const c=r?.tokenUsage,u=m.tokenUsage,f=(u.inputTokens??0)-(c?.inputTokens??0),l=(u.outputTokens??0)-(c?.outputTokens??0),h=(u.totalTokens??0)-(c?.totalTokens??0),y=p.filter(w=>w.tokenUsage).map(w=>({id:w.id,role:w.role,tokens:w.tokenUsage})),g=p.reduce((w,j)=>({inputTokens:w.inputTokens+(j.tokenUsage?.inputTokens??0),outputTokens:w.outputTokens+(j.tokenUsage?.outputTokens??0),totalTokens:w.totalTokens+(j.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),b=g.inputTokens===i.inputTokens&&g.outputTokens===i.outputTokens&&g.totalTokens===i.totalTokens;de.debug("updateMessage: tokenUsage update",{messageId:t,updates:a.tokenUsage,existing:c,messageMax:u,delta:{inputDelta:f,outputDelta:l,totalDelta:h},totalBilled:i,currentContext:o,actualSum:g,billedCorrect:b?"✅":"❌",messageCount:p.length,messagesWithTokens:y.length,breakdown:y})}return{messages:p,totalBilled:i,currentContext:o}}),clearMessages:()=>s({messages:[]}),setIsStreaming:t=>s({isStreaming:t}),setStreamingStartTime:t=>s({streamingStartTime:t}),addToolCall:(t,a)=>s(n=>({toolCalls:{...n.toolCalls,[t]:[...n.toolCalls[t]||[],a]}})),addToolCallToCurrentMessage:t=>s(a=>{const n=a.messages.findLastIndex(p=>p.role==="assistant");if(n===-1){de.debug("No assistant message found, creating one for tool call at position 0");const p={id:`msg_${Date.now()}_assistant`,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!1,toolCalls:[{...t,contentPosition:0}]};return{messages:[...a.messages,p]}}const r=[...a.messages],i=r[n];if(!i)return a;const o=i.content.length,m={...t,contentPosition:o};return r[n]={...i,toolCalls:[...i.toolCalls||[],m]},{messages:r}}),updateToolCallInCurrentMessage:t=>s(a=>{const n=a.messages.findLastIndex(u=>u.role==="assistant");if(n===-1)return de.warn("No assistant message found to update tool call in"),a;const r=[...a.messages],i=r[n];if(!i)return a;const o=i.toolCalls||[],m=o.findIndex(u=>u.id===t.id);if(m===-1)return de.warn(`Tool call ${t.id} not found in message`),a;const p=o[m];if(!p)return a;const c=[...o];return c[m]=Qe(p,t),r[n]={...i,toolCalls:c},{messages:r}}),updateToolCall:(t,a)=>s(n=>{const r=n.toolCalls[t]||[],i=r.findIndex(p=>p.id===a.id);if(i===-1)return n;const o=r[i];if(!o)return n;const m=[...r];return m[i]=Qe(o,a),{toolCalls:{...n.toolCalls,[t]:m}}}),setInputValue:t=>s(a=>({input:{...a.input,value:t}})),setInputSubmitting:t=>s(a=>({input:{...a.input,isSubmitting:t}})),addFileAttachment:t=>s(a=>({input:{...a.input,attachedFiles:[...a.input.attachedFiles,t]}})),removeFileAttachment:t=>s(a=>({input:{...a.input,attachedFiles:a.input.attachedFiles.filter((n,r)=>r!==t)}})),clearInput:()=>s(t=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}})),addTokenUsage:t=>s(a=>({totalBilled:{inputTokens:a.totalBilled.inputTokens+(t.inputTokens??0),outputTokens:a.totalBilled.outputTokens+(t.outputTokens??0),totalTokens:a.totalBilled.totalTokens+(t.totalTokens??0)},currentContext:{inputTokens:t.inputTokens??a.currentContext.inputTokens,outputTokens:a.currentContext.outputTokens+(t.outputTokens??0),totalTokens:(t.inputTokens??a.currentContext.inputTokens)+(a.currentContext.outputTokens+(t.outputTokens??0))}})),setLatestContextSize:t=>s({latestContextSize:t}),setCurrentModel:t=>s({currentModel:t}),resetTokens:()=>s({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0},latestContextSize:null}),cycleTokenDisplayMode:()=>s(t=>{const a=["context","input","output"],r=(a.indexOf(t.tokenDisplayMode)+1)%a.length,i=a[r];return i?{tokenDisplayMode:i}:t}),addLog:t=>s(a=>({logs:[...a.logs,t]})),clearLogs:()=>s({logs:[]}),setActiveTab:t=>s({activeTab:t})})),te=ne("use-chat-messages","debug");function Bt(s,t){const a=R(l=>l.messages),n=R(l=>l.isStreaming),r=R(l=>l.sessionId),i=R(l=>l.setIsStreaming),o=R(l=>l.setStreamingStartTime),m=R(l=>l.addMessage),p=R(l=>l.updateMessage),c=R(l=>l.setError),u=R(l=>l.setLatestContextSize),f=d.useCallback(async(l,h)=>{if(te.debug("[sendMessage] Called with",{contentLength:l.length,attachmentsCount:h?.length||0,hasAttachments:!!h&&h.length>0}),!s){te.error("No client available"),c("No client available");return}let y=r;if(!y){te.info("Creating new session before sending first message");const b=await t();if(!b){te.error("Failed to create session"),c("Failed to create session");return}y=b,te.info("Session created successfully",{sessionId:b})}const g=`msg_${Date.now()}_assistant`;try{const b=Date.now();i(!0),o(b);const w={id:`msg_${Date.now()}_user`,role:"user",content:l,timestamp:new Date().toISOString(),isStreaming:!1,...h&&h.length>0?{images:h.filter(N=>N.mimeType.startsWith("image/")).map(N=>({mimeType:N.mimeType,data:N.data}))}:{}};m(w);const j={id:g,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:b};m(j);const C=s.receiveMessages();s.sendMessage(l,y,h).catch(N=>{const A=N instanceof Error?N.message:String(N);c(A),i(!1),o(null)});let P="",E=!1;for await(const N of C){const A=N._meta,U=A?.context_size||N.context_size;if(U!=null){const F=U;te.info("✅ Received context_size from backend",{context_size:F,totalEstimated:F.totalEstimated,source:A?.context_size?"_meta":"direct"}),u(F)}else te.debug("Chunk does not have context_size",{hasContextSize:"context_size"in N,hasMeta:"_meta"in N,metaKeys:A?Object.keys(A):null});if(N.tokenUsage&&te.debug("Received tokenUsage from backend",{tokenUsage:N.tokenUsage}),N.isComplete){p(g,{content:P,isStreaming:!1,streamingStartTime:void 0,...N.tokenUsage?{tokenUsage:N.tokenUsage}:{}}),i(!1),o(null),E=!0;break}else N.contentDelta.type==="text"&&(P+=N.contentDelta.text,p(g,{content:P,...N.tokenUsage?{tokenUsage:N.tokenUsage}:{}}),await new Promise(F=>setTimeout(F,16)))}E||(te.warn("Stream ended without isComplete flag"),p(g,{isStreaming:!1,streamingStartTime:void 0}),i(!1),o(null))}catch(b){const w=b instanceof Error?b.message:String(b);c(w),i(!1),o(null),p(g,{isStreaming:!1,streamingStartTime:void 0})}},[s,r,t,m,p,i,o,c,u]);return{messages:a,isStreaming:n,sendMessage:f}}const Je=ne("use-chat-input","debug");function Yn(s,t){const a=R(l=>l.input),n=R(l=>l.setInputValue),r=R(l=>l.setInputSubmitting),i=R(l=>l.addFileAttachment),o=R(l=>l.removeFileAttachment),{sendMessage:m}=Bt(s,t),p=d.useCallback(l=>{n(l)},[n]),c=d.useCallback(async()=>{if(!a.value.trim()||a.isSubmitting)return;const l=a.value,h=a.attachedFiles;Je.debug("Submitting message with attachments",{messageLength:l.length,attachmentCount:h.length,hasAttachments:h.length>0}),n(""),r(!0);try{await m(l,h.length>0?h:void 0),R.setState(y=>({input:{...y.input,attachedFiles:[]}}))}catch(y){Je.error("Failed to send message",{error:y instanceof Error?y.message:String(y)})}finally{r(!1)}},[a,n,r,m]),u=d.useCallback(l=>{i(l)},[i]),f=d.useCallback(l=>{o(l)},[o]);return{value:a.value,isSubmitting:a.isSubmitting,attachedFiles:a.attachedFiles,onChange:p,onSubmit:c,onAttachFile:u,onRemoveFile:f}}const se=ne("use-chat-session","debug");function Xn(s,t){const a=R(g=>g.connectionStatus),n=R(g=>g.sessionId),r=R(g=>g.setConnectionStatus),i=R(g=>g.setSessionId),o=R(g=>g.setError),m=R(g=>g.clearMessages),p=R(g=>g.resetTokens),c=R(g=>g.addMessage),u=R(g=>g.setLatestContextSize);d.useEffect(()=>s?s.onSessionUpdate(b=>{const w=b._meta,j=w?.context_size||b.context_size;if(j!=null){const C=j;se.info("✅ Received context_size from session update",{context_size:C,totalEstimated:C.totalEstimated,isReplay:w?.isReplay}),u(C)}if(b.message&&(se.debug("Session update with message",{message:b.message}),b.message.role!=="tool")){const C=b.message.content.map(A=>A.type==="text"?A.text:"").join(""),P=[];for(const A of b.message.content)if(A.type==="image"){const U=A;U.source?.data?P.push({mimeType:U.source.media_type||"image/png",data:U.source.data}):U.data&&P.push({mimeType:U.mimeType||"image/png",data:U.data})}const E=R.getState().messages,N=E[E.length-1];if(b.message.role==="assistant"&&N?.role==="assistant"&&N.content===""&&C)se.debug("Appending text to existing assistant message"),R.getState().updateMessage(N.id,{content:N.content+C});else{const A={id:b.message.id,role:b.message.role,content:C,timestamp:b.message.timestamp,isStreaming:!1,...P.length>0?{images:P}:{}};c(A)}}}):void 0,[s,c,u]);const f=d.useCallback(async()=>{if(!s){o("No client available");return}try{r("connecting"),o(null),await s.connect(),r("connected")}catch(g){se.error("Failed to connect",{error:g instanceof Error?g.message:String(g)});const b=g instanceof Error?g.message:String(g);o(b),r("error")}},[s,r,o]),l=d.useCallback(async g=>{if(!s){o("No client available");return}try{r("connecting"),o(null),m(),p();const b=await s.loadSession(g);i(b),r("connected"),se.info("Session loaded successfully",{sessionId:b})}catch(b){se.warn("Failed to load session, creating new one instead",{sessionId:g,error:b instanceof Error?b.message:String(b)});try{await f();const w=await s.startSession();if(i(w),m(),p(),typeof window<"u"){const j=new URL(window.location.href);j.searchParams.set("session",w),window.history.replaceState({},"",j.toString())}se.info("Created new session after failed load",{sessionId:w})}catch(w){const j=w instanceof Error?w.message:String(w);o(`Failed to load or create session: ${j}`),r("error")}}},[s,r,i,o,m,p,f]),h=d.useCallback(async()=>{if(!s)return o("No client available"),null;try{const g=await s.startSession();if(i(g),m(),p(),typeof window<"u"){const b=new URL(window.location.href);b.searchParams.set("session",g),window.history.pushState({},"",b.toString())}return g}catch(g){const b=g instanceof Error?g.message:String(g);return o(b),null}},[s,i,o,m,p]),y=d.useCallback(async()=>{if(s)try{await s.disconnect(),r("disconnected"),i(null)}catch(g){const b=g instanceof Error?g.message:String(g);o(b)}},[s,r,i,o]);return d.useEffect(()=>{!s||a!=="disconnected"||(t?(se.info("Loading initial session from URL",{sessionId:t}),l(t)):f())},[s,a,t,f,l]),{connectionStatus:a,sessionId:n,connect:f,loadSession:l,startSession:h,disconnect:y}}const Ye="town-message-history",Zn=100;function ea(){const[s,t]=d.useState(-1),[a,n]=d.useState(""),r=d.useCallback(()=>{try{const u=localStorage.getItem(Ye);return u?JSON.parse(u):[]}catch{return[]}},[]),i=d.useCallback(u=>{const f=u.trim();if(f){try{const l=r();if(l[0]===f)return;const h=[f,...l].slice(0,Zn);localStorage.setItem(Ye,JSON.stringify(h))}catch{}t(-1),n("")}},[r]),o=d.useCallback(u=>{const f=r();if(f.length===0)return null;s===-1&&n(u);const l=Math.min(s+1,f.length-1);if(l===s)return null;const h=f[l];return h===void 0?null:(t(l),h)},[s,r]),m=d.useCallback(()=>{if(s===-1)return null;const u=r();if(s===0){t(-1);const h=a;return n(""),h}const f=s-1,l=u[f];return l===void 0?null:(t(f),l)},[s,a,r]),p=d.useCallback(()=>{s!==-1&&(t(-1),n(""))},[s]);return{addToHistory:i,navigatePrevious:o,navigateNext:m,resetNavigation:p,isBrowsingHistory:s!==-1,historyIndex:s}}function ta(s){const t=R(o=>o.toolCalls),a=R(o=>o.addToolCall),n=R(o=>o.updateToolCall),r=R(o=>o.addToolCallToCurrentMessage),i=R(o=>o.updateToolCallInCurrentMessage);return d.useEffect(()=>{if(!s)return;const o=s.onSessionUpdate(m=>{m.type==="tool_call"?(a(m.sessionId,m.toolCall),r(m.toolCall)):m.type==="tool_call_update"&&(n(m.sessionId,m.toolCallUpdate),i(m.toolCallUpdate))});return()=>{o()}},[s,a,n,r,i]),{toolCalls:t,getToolCallsForSession:o=>{const m=t[o];return m&&m.length>0?m:Object.values(t).flat()}}}const sa=_({mimeType:v(),data:v()}),na=_({id:v(),role:X(["user","assistant","system"]),content:v(),timestamp:Ce(),isStreaming:xe().default(!1),streamingStartTime:D().optional(),metadata:Q(v(),J()).optional(),toolCalls:H($t).optional(),tokenUsage:Ue.optional(),images:H(sa).optional()}),aa=_({value:v(),isSubmitting:xe(),attachedFiles:H(_({name:v(),path:v(),size:D(),mimeType:v(),data:v()}))});_({sessionId:v().nullable(),isConnected:xe(),isStreaming:xe(),messages:H(na),input:aa,error:v().nullable()});X(["disconnected","connecting","connected","error"]);const oa=_({name:v(),description:v().optional(),parameters:Q(v(),J()).optional()}),ra=_({name:v(),description:v(),parameters:Q(v(),J()),required:H(v()).optional()}),ia=_({name:v(),version:v().optional(),description:v().optional(),author:v().optional(),capabilities:H(oa).optional(),tools:H(ra).optional(),supportedFormats:H(v()).optional()}),la=X(["initializing","ready","busy","error","terminated"]);_({status:la,info:ia.optional(),pid:D().optional(),error:v().optional(),uptime:D().optional()});const Ht=X(["user","assistant","system","tool"]),ca=X(["text","image","file","tool_call","tool_result"]),we=_({type:ca}),da=we.extend({type:B("text"),text:v()}),ua=we.extend({type:B("image"),url:v().url().optional(),source:_({type:B("base64"),media_type:X(["image/jpeg","image/png","image/gif","image/webp"]),data:v()}).optional()}),pa=we.extend({type:B("file"),name:v(),path:v().optional(),url:v().url().optional(),mimeType:v(),size:D().optional()}),ma=we.extend({type:B("tool_call"),id:v(),name:v(),arguments:Q(v(),J())}),fa=we.extend({type:B("tool_result"),callId:v(),result:J(),error:v().optional()}),Wt=nt("type",[da,ua,pa,ma,fa]),Vt=_({id:v(),role:Ht,content:H(Wt),timestamp:Ce(),metadata:Q(v(),J()).optional()});_({id:v(),role:Ht,contentDelta:Wt,isComplete:xe(),tokenUsage:_({inputTokens:D().optional(),outputTokens:D().optional(),totalTokens:D().optional()}).optional(),contextInputTokens:D().optional(),_meta:_({context_size:_({systemPromptTokens:D(),userMessagesTokens:D(),assistantMessagesTokens:D(),toolInputTokens:D(),toolResultsTokens:D(),totalEstimated:D(),llmReportedInputTokens:D().optional()}).optional()}).optional()});const qt=X(["idle","connecting","connected","active","streaming","error","disconnected"]),ga=_({agentPath:v(),agentArgs:H(v()).optional(),environment:Q(v(),v()).optional(),workingDirectory:v().optional(),timeout:D().optional()}),ha=_({agentName:v().optional(),agentVersion:v().optional(),capabilities:H(v()).optional(),startedAt:Ce(),lastActivityAt:Ce().optional()});_({id:v(),status:qt,config:ga,metadata:ha.optional(),messages:H(Vt),error:v().optional()});const Te=_({sessionId:v(),status:qt.optional(),message:Vt.optional(),error:v().optional(),_meta:Q(v(),J()).optional()}),xa=Te.extend({type:B("tool_call"),toolCall:$t,messageId:v().optional()}),ba=Te.extend({type:B("tool_call_update"),toolCallUpdate:Qn,messageId:v().optional()}),ya=Te.extend({type:B("tool_output"),toolOutput:_({id:v(),content:H(qs()).optional(),rawOutput:Q(v(),J()).optional()}),messageId:v().optional()}),wa=Te.extend({type:B("generic").optional()});Gs([xa,ba,ya,wa]);const va=[{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 ja{data;constructor(t=va){this.data=t}async getRootItems(){return Promise.resolve(this.data)}async getItemChildren(t){const a=r=>{for(const i of r){if(i.id===t)return i;if(i.children){const o=a(i.children);if(o)return o}}},n=a(this.data);return Promise.resolve(n?.children||[])}async getItemDetails(t){const a=r=>{for(const i of r){if(i.id===t)return i;if(i.children){const o=a(i.children);if(o)return o}}},n=a(this.data);if(!n)throw new Error(`Item with id ${t} not found`);return Promise.resolve(n)}}const Na=[{id:"1",title:"Boeing Scores Early Wins at Dubai Airshow",url:"https://www.reuters.com/business/aerospace-defense/boeing-scores-early-wins-dubai-airshow-2024-11-17",snippet:"DUBAI, Nov 17 (Reuters) - Boeing (BA.N), opens new tab took centre stage at day one of the Dubai Airshow on Monday, booking a $38 billion order from host carrier Emirates and clinching more deals with African carriers, while China displayed its C919 in the Middle East for the first time.",sourceName:"Reuters",favicon:"https://www.reuters.com/favicon.ico"},{id:"2",title:"Boeing's Sustainable Aviation Goals Take Flight",url:"https://www.forbes.com/boeing-sustainability",snippet:"SEATTLE, Nov 18 (Reuters) - Boeing is making headway towards its sustainability targets, unveiling plans for a new eco-friendly aircraft design aimed at reducing emissions by 50% by 2030.",sourceName:"Forbes"},{id:"3",title:"Boeing Faces Increased Competition in Global Aviation Market",url:"https://www.reuters.com/business/aerospace-defense/boeing-competition-2024-11-19",snippet:"CHICAGO, Nov 19 (Reuters) - As the global aviation industry rebounds post-pandemic, Boeing is grappling with intensified competition from rival manufacturers, particularly in the Asian market.",sourceName:"Reuters",favicon:"https://www.reuters.com/favicon.ico"},{id:"4",title:"Boeing's Starliner Successfully Completes Orbital Test Flight",url:"https://www.theverge.com/boeing-starliner",snippet:"NASA, Nov 20 (Reuters) - Boeing's CST-100 Starliner spacecraft achieves a significant milestone, successfully completing its orbital test flight, paving the way for future crewed missions to the International Space Station.",sourceName:"The Verge"}];function x(...s){return Ks(Qs(s))}const Sa=re("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-paragraph-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 cursor-pointer",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary-hover",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive-hover",outline:"border border-input bg-background hover:bg-accent-hover hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover",ghost:"hover:bg-accent-hover hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ie=d.forwardRef(({className:s,variant:t,size:a,asChild:n=!1,...r},i)=>{const o=n?ye:"button";return e.jsx(o,{className:x(Sa({variant:t,size:a,className:s})),ref:i,...r})});ie.displayName="Button";const Ca=d.forwardRef(({className:s,...t},a)=>e.jsx("div",{ref:a,className:x("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));Ca.displayName="Card";const Ta=d.forwardRef(({className:s,...t},a)=>e.jsx("div",{ref:a,className:x("flex flex-col space-y-1.5 p-6",s),...t}));Ta.displayName="CardHeader";const ka=d.forwardRef(({className:s,...t},a)=>e.jsx("div",{ref:a,className:x("text-2xl font-semibold leading-none tracking-tight",s),...t}));ka.displayName="CardTitle";const Ia=d.forwardRef(({className:s,...t},a)=>e.jsx("div",{ref:a,className:x("text-sm text-muted-foreground",s),...t}));Ia.displayName="CardDescription";const Ra=d.forwardRef(({className:s,...t},a)=>e.jsx("div",{ref:a,className:x("p-6 pt-0",s),...t}));Ra.displayName="CardContent";const Ea=d.forwardRef(({className:s,...t},a)=>e.jsx("div",{ref:a,className:x("flex items-center p-6 pt-0",s),...t}));Ea.displayName="CardFooter";const Gt=d.forwardRef(({title:s,description:t,guideUrl:a,guideText:n="Guide",suggestedPrompts:r=[],onPromptClick:i,onGuideClick:o,onOpenFiles:m,onOpenSettings:p,toolsAndMcpsCount:c,onPromptHover:u,onPromptLeave:f,className:l,...h},y)=>{const g=j=>{i?.(j)},b=()=>{a&&window.open(a,"_blank","noopener,noreferrer"),o?.()},w=[];for(let j=0;j<r.length;j+=2)w.push(r.slice(j,j+2));return e.jsxs("div",{ref:y,className:x("flex flex-col items-start",l),...h,children:[e.jsx("h3",{className:"text-heading-4 text-text-primary mb-6",children:s}),e.jsx("p",{className:"text-subheading text-text-secondary max-w-prose mb-6",children:t}),(m||p)&&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"})]}),p&&e.jsxs("button",{type:"button",onClick:p,className:"inline-flex items-center gap-1 py-1.5 pr-3 pl-3 rounded-lg hover:bg-accent transition-colors",children:[e.jsxs("span",{className:"text-paragraph-sm-medium text-foreground tracking-wide leading-none",children:["View Tools & MCPs",c!==void 0&&c>0&&e.jsxs("span",{className:"ml-1",children:["(",c,")"]})]}),e.jsx(fe,{className:"size-4 text-foreground shrink-0"})]})]}),(a||o)&&e.jsxs("button",{type:"button",onClick:b,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:n}),e.jsx(fe,{className:"size-4 text-foreground shrink-0"})]}),r.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[e.jsx("p",{className:"text-label text-text-tertiary",children:"Suggested Prompts"}),e.jsx("div",{className:"flex flex-col gap-2.5",children:w.map(j=>e.jsx("div",{className:"flex gap-2.5 items-center",children:j.map(C=>e.jsx("button",{type:"button",onClick:()=>g(C),onMouseEnter:()=>u?.(C),onMouseLeave:()=>f?.(),className:"flex-1 flex items-start gap-2 p-3 bg-secondary hover:bg-secondary/80 rounded-2xl transition-colors min-w-0",children:e.jsx("span",{className:"text-paragraph font-normal leading-normal text-text-tertiary truncate",children:C})},C))},j.join("-")))})]})]})});Gt.displayName="ChatEmptyState";const Kt=d.createContext(void 0),ze=()=>{const s=d.useContext(Kt);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},Qt=d.forwardRef(({defaultExpanded:s=!1,expanded:t,onExpandedChange:a,className:n,children:r,...i},o)=>{const[m,p]=d.useState(s),c=t??m,u=d.useCallback(y=>{p(y),a?.(y)},[a]),f=d.Children.toArray(r),l=f.find(y=>d.isValidElement(y)&&typeof y.type=="function"&&y.type.displayName==="ChatHeader.ExpandablePanel"),h=f.filter(y=>y!==l);return e.jsxs(Kt.Provider,{value:{isExpanded:c,setIsExpanded:u},children:[e.jsx("div",{ref:o,className:x("flex items-center justify-between px-6 py-4",n),...i,children:h}),l]})});Qt.displayName="ChatHeader.Root";const Aa=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("h1",{ref:n,className:x("m-0 text-subheading font-semibold",s),...a,children:t}));Aa.displayName="ChatHeader.Title";const Ma=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("flex items-center gap-3",s),...a,children:t}));Ma.displayName="ChatHeader.Actions";const _a=s=>{switch(s){case"connected":return"bg-green-500";case"connecting":return"bg-yellow-500";case"error":return"bg-red-500";default:return"bg-gray-500"}},Pa=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},Da=d.forwardRef(({status:s,statusText:t,className:a,...n},r)=>{const i=t??Pa(s),o=_a(s);return e.jsxs("div",{ref:r,className:x("flex items-center gap-2",a),...n,children:[e.jsx("div",{className:x("h-2 w-2 rounded-full",o)}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:i})]})});Da.displayName="ChatHeader.StatusIndicator";const Ua=d.forwardRef(({icon:s,className:t,children:a,onClick:n,...r},i)=>{const{isExpanded:o,setIsExpanded:m}=ze(),p=c=>{m(!o),n?.(c)};return e.jsxs("button",{ref:i,type:"button",onClick:p,className:x("rounded p-1 transition-colors hover:bg-background lg:hidden",t),"aria-label":o?"Collapse header":"Expand header",...r,children:[s&&e.jsx("div",{className:x("transition-transform duration-200",o&&"rotate-180"),children:s}),a]})});Ua.displayName="ChatHeader.Toggle";const Jt=d.forwardRef(({className:s,children:t,...a},n)=>{const{isExpanded:r}=ze();return r?e.jsx("div",{ref:n,className:x("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",s),...a,children:t}):null});Jt.displayName="ChatHeader.ExpandablePanel";const Yt=d.forwardRef(({commands:s=[],showCommandMenu:t,commandMenuQuery:a,selectedMenuIndex:n,setSelectedMenuIndex:r,setMenuItemCount:i,triggerCounter:o,onChange:m,className:p,...c},u)=>{const f=d.useCallback((h,y)=>{const g=h.toLowerCase(),b=y.toLowerCase();if(!y)return 1;if(g.includes(b))return 1-b.length/g.length;let w=0;for(let j=0;j<g.length&&w<b.length;j++)g[j]===b[w]&&w++;return w===b.length?.5-w/g.length:0},[]),l=d.useMemo(()=>s.map(h=>({...h,score:Math.max(f(h.label,a),h.description?f(h.description,a):0)})).filter(h=>h.score>0).sort((h,y)=>y.score-h.score),[s,a,f]);return d.useEffect(()=>{i(l.length)},[l.length,i]),d.useEffect(()=>{r(0)},[r]),d.useEffect(()=>{o>0&&l[n]&&(l[n].onSelect(),m(""))},[o,l,n,m]),!t||l.length===0?null:e.jsxs("div",{ref:u,className:x("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",p),...c,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:l.map((h,y)=>e.jsxs("button",{type:"button",onClick:()=>h.onSelect(),className:x("w-full rounded-sm px-2 py-2 text-left text-paragraph-sm transition-colors","flex items-start gap-2","hover:bg-muted",y===n&&"bg-muted"),children:[h.icon&&e.jsx("span",{className:"shrink-0 mt-0.5",children:h.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:h.label}),h.description&&e.jsx("div",{className:"text-caption text-muted-foreground truncate",children:h.description})]})]},h.id))})]})});Yt.displayName="ChatInputCommandMenu";const Xt=d.createContext(void 0),ke=()=>{const s=d.useContext(Xt);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},Zt=d.forwardRef(({client:s,startSession:t,value:a,onChange:n,onSubmit:r,disabled:i=!1,isSubmitting:o,submitOnEnter:m=!0,className:p,children:c,...u},f)=>{const l=d.useRef(null),h=d.useCallback(async()=>Promise.resolve(null),[]),y=Yn(s??null,t??h),g=R(O=>O.isStreaming),{addToHistory:b,navigatePrevious:w,navigateNext:j,resetNavigation:C}=ea(),P=s&&t,E=P?y.value:a||"",N=P?y.onChange:n||(()=>{}),A=P?y.onSubmit:r||(async()=>{}),U=P?y.isSubmitting||g:o||!1,F=d.useCallback(async()=>{const O=E.trim();O&&b(O),await A()},[E,b,A]),[K,Z]=d.useState(!1),[I,L]=d.useState(""),[V,q]=d.useState(0),[Y,k]=d.useState(0),[T,S]=d.useState(0),z=d.useCallback(()=>{S(O=>O+1)},[]),$=async O=>{O.preventDefault(),E.trim()&&!U&&!i&&(await F(),setTimeout(()=>{l.current?.focus()},0))},W=O=>{const ee=O.target;!(ee.tagName==="BUTTON"||ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.closest("button"))&&l.current&&l.current.focus()},Ds=O=>{const ee=O.target;!(ee.tagName==="BUTTON"||ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.closest("button"))&&O.key===" "&&(O.preventDefault(),l.current&&l.current.focus())};return d.useEffect(()=>{const O=document.querySelector('textarea[name="chat-input"]');O&&l.current!==O&&(l.current=O)},[]),d.useEffect(()=>{!E&&l.current&&(l.current.style.height="auto",l.current.style.overflowY="hidden")},[E]),e.jsx(Xt.Provider,{value:{value:E,onChange:N,onSubmit:F,disabled:i,isSubmitting:U,submitOnEnter:m,showCommandMenu:K,setShowCommandMenu:Z,commandMenuQuery:I,setCommandMenuQuery:L,selectedMenuIndex:V,setSelectedMenuIndex:q,menuItemCount:Y,setMenuItemCount:k,triggerMenuSelect:z,triggerCounter:T,navigateHistoryPrevious:w,navigateHistoryNext:j,resetHistoryNavigation:C},children:e.jsx("form",{ref:f,onSubmit:$,onClick:W,onKeyDown:Ds,className:x("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...u,children:c})})});Zt.displayName="ChatInput.Root";const es=d.forwardRef(({asChild:s=!1,className:t,onKeyDown:a,onFilesDropped:n,children:r,...i},o)=>{const{value:m,onChange:p,onSubmit:c,disabled:u,isSubmitting:f,submitOnEnter:l,showCommandMenu:h,setShowCommandMenu:y,setCommandMenuQuery:g,setSelectedMenuIndex:b,menuItemCount:w,triggerMenuSelect:j,navigateHistoryPrevious:C,navigateHistoryNext:P,resetHistoryNavigation:E}=ke(),N=d.useRef(null),[A,U]=d.useState(!1),F=d.useCallback(k=>{N.current=k,typeof o=="function"?o(k):o&&(o.current=k)},[o]),K=k=>new Promise((T,S)=>{const z=new FileReader;z.readAsDataURL(k),z.onload=()=>{const $=z.result.split(",")[1];T($||"")},z.onerror=$=>S($)}),Y={ref:F,name:"chat-input",value:m,onChange:k=>{const T=k.target.value;if(p(T),E(),T.startsWith("/")&&!T.includes(`
|
|
5
|
+
`)){y(!0);const $=T.slice(1);g($)}else y(!1),g("");const S=N.current;if(!S)return;S.style.height="auto";const z=Math.min(S.scrollHeight,164);S.style.height=`${z}px`,S.scrollHeight>164?S.style.overflowY="auto":S.style.overflowY="hidden"},onKeyDown:k=>{if(h&&w>0){if(k.key==="ArrowDown"){k.preventDefault(),b(T=>(T+1)%w);return}else if(k.key==="ArrowUp"){k.preventDefault(),b(T=>(T-1+w)%w);return}else if(k.key==="Enter"&&!k.shiftKey){k.preventDefault(),j();return}else if(k.key==="Escape"){k.preventDefault(),y(!1),g("");return}}if(!h){const T=N.current,S=T?.selectionStart===0&&T?.selectionEnd===0,z=T?.selectionStart===m.length&&T?.selectionEnd===m.length,$=m.includes(`
|
|
6
|
+
`);if(k.key==="ArrowUp"&&(S||!m||!$)){const W=C(m);if(W!==null){k.preventDefault(),p(W),setTimeout(()=>{N.current&&(N.current.selectionStart=W.length,N.current.selectionEnd=W.length)},0);return}}else if(k.key==="ArrowDown"&&(z||!m||!$)){const W=P();if(W!==null){k.preventDefault(),p(W),setTimeout(()=>{N.current&&(N.current.selectionStart=W.length,N.current.selectionEnd=W.length)},0);return}}}l&&k.key==="Enter"&&!k.shiftKey&&(m.trim()&&!f&&!u?(k.preventDefault(),c()):(f||u)&&k.preventDefault()),a?.(k)},onDrop:async k=>{k.preventDefault(),U(!1);const T=k.dataTransfer.files;if(!T||T.length===0||!n)return;const S=[];for(const z of Array.from(T))if(z.type.startsWith("image/"))try{const $=await K(z);S.push({name:z.name,path:z.name,size:z.size,mimeType:z.type,data:$})}catch($){console.error("Failed to process dropped file:",z.name,$)}S.length>0&&n(S)},onDragOver:k=>{k.preventDefault(),U(!0)},onDragLeave:k=>{k.preventDefault(),U(!1)},disabled:u,...i};return s&&d.isValidElement(r)?d.cloneElement(r,Y):e.jsx("textarea",{...Y,rows:1,className:x("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",A&&"ring-2 ring-primary ring-offset-2",t)})});es.displayName="ChatInput.Field";const ts=d.forwardRef(({asChild:s=!1,className:t,disabled:a,children:n,...r},i)=>{const{value:o,disabled:m,isSubmitting:p}=ke(),c=a||m||p||!o.trim(),u=s?ye:ie;return e.jsx(u,{ref:i,type:"submit",disabled:c,variant:s?void 0:"default",size:"icon",className:x(!s&&"gap-1.5 rounded-full",t),...r,children:n})});ts.displayName="ChatInput.Submit";const ss=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("flex items-center justify-between p-2",s),...a,children:t}));ss.displayName="ChatInput.Toolbar";const ns=d.forwardRef(({asChild:s=!1,className:t,children:a,onClick:n,...r},i)=>{const{value:o,onChange:m,setShowCommandMenu:p,setCommandMenuQuery:c}=ke(),u=l=>{o.startsWith("/")||(m("/"),p(!0),c("")),n?.(l)},f=s?ye:ie;return e.jsx(f,{ref:i,type:"button",variant:"ghost",size:"icon",className:x("rounded-full",t),onClick:u,...r,children:a||e.jsx(mn,{className:"size-4"})})});ns.displayName="ChatInput.Actions";const as=d.forwardRef(({asChild:s=!1,className:t,children:a,onFilesSelected:n,...r},i)=>{const o=d.useRef(null),m=f=>new Promise((l,h)=>{const y=new FileReader;y.readAsDataURL(f),y.onload=()=>{const g=y.result.split(",")[1];l(g||"")},y.onerror=g=>h(g)}),p=async f=>{const l=f.target.files;if(!l||l.length===0)return;const h=[];for(const y of Array.from(l))if(y.type.startsWith("image/"))try{const g=await m(y);h.push({name:y.name,path:y.name,size:y.size,mimeType:y.type,data:g})}catch(g){console.error("Failed to process file:",y.name,g)}h.length>0&&n&&n(h),o.current&&(o.current.value="")},c=f=>{f.preventDefault(),o.current?.click()},u=s?ye:ie;return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:p}),e.jsx(u,{ref:i,type:"button",variant:"ghost",size:"icon",className:x("rounded-full",t),onClick:c,...r,children:a||e.jsx(fn,{className:"size-4"})})]})});as.displayName="ChatInput.Attachment";const os=d.forwardRef(({asChild:s=!1,className:t,children:a,...n},r)=>{const i=s?ye:ie;return e.jsx(i,{ref:r,type:"button",variant:"ghost",size:"icon",className:x("rounded-full",t),...n,children:a||e.jsx(gn,{className:"size-4"})})});os.displayName="ChatInput.VoiceInput";const rs=d.forwardRef(({commands:s=[],className:t,onChange:a,...n},r)=>{const{showCommandMenu:i,commandMenuQuery:o,selectedMenuIndex:m,setSelectedMenuIndex:p,setMenuItemCount:c,triggerCounter:u,onChange:f}=ke();return e.jsx(Yt,{ref:r,commands:s,showCommandMenu:i,commandMenuQuery:o,selectedMenuIndex:m,setSelectedMenuIndex:p,setMenuItemCount:c,triggerCounter:u,onChange:f,className:t,...n})});rs.displayName="ChatInput.CommandMenu";const za=({className:s,...t})=>e.jsx(zs,{className:x("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...t}),is=({className:s,...t})=>e.jsx(Ls,{className:x(s),...t}),La=({withHandle:s,className:t,...a})=>e.jsx(Fs,{className:x("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...a,children:s&&e.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"h-2.5 w-2.5",children:[e.jsx("title",{children:"Resize Handle"}),e.jsx("circle",{cx:"9",cy:"12",r:"1"}),e.jsx("circle",{cx:"9",cy:"5",r:"1"}),e.jsx("circle",{cx:"9",cy:"19",r:"1"}),e.jsx("circle",{cx:"15",cy:"12",r:"1"}),e.jsx("circle",{cx:"15",cy:"5",r:"1"}),e.jsx("circle",{cx:"15",cy:"19",r:"1"})]})})}),Fa=({...s})=>e.jsx(Js,{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"}},...s}),Le=d.createContext(void 0),pe=()=>{const s=d.useContext(Le);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},ls=d.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:t="hidden",defaultActiveTab:a="todo",className:n,children:r,...i},o)=>{const[m,p]=d.useState(s),[c,u]=d.useState(t),[f,l]=d.useState(a);return e.jsx(Le.Provider,{value:{sidebarOpen:m,setSidebarOpen:p,panelSize:c,setPanelSize:u,activeTab:f,setActiveTab:l},children:e.jsx("div",{ref:o,className:x("flex h-screen flex-row bg-background text-foreground",n),...i,children:e.jsx(za,{direction:"horizontal",className:"flex-1",children:r})})})});ls.displayName="ChatLayout.Root";const Oa=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("relative z-10 border-b border-border bg-card shrink-0",s),...a,children:t}));Oa.displayName="ChatLayout.Header";const cs=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx(is,{defaultSize:70,minSize:50,children:e.jsx("div",{ref:n,className:x("flex flex-1 flex-col overflow-hidden h-full",s),...a,children:t})}));cs.displayName="ChatLayout.Main";const ds=d.forwardRef(({showToaster:s=!0,className:t,children:a,...n},r)=>e.jsxs("div",{ref:r,className:x("relative flex flex-1 flex-col overflow-hidden",t),...n,children:[a,s&&e.jsx(Fa,{})]}));ds.displayName="ChatLayout.Body";const us=d.forwardRef(({className:s,children:t,onScrollChange:a,showScrollToBottom:n=!0,...r},i)=>{const[o,m]=d.useState(!1),p=d.useRef(null),c=d.useRef(!0),u=d.useRef(!1);d.useImperativeHandle(i,()=>p.current);const f=d.useCallback(()=>{const b=p.current;if(!b)return!1;const{scrollTop:w,scrollHeight:j,clientHeight:C}=b,E=j-w-C<100;return m(!E&&n),a?.(E),E},[a,n]),l=d.useCallback(()=>{if(u.current)return;const b=f();c.current=b},[f]),h=d.useCallback((b=!0)=>{const w=p.current;w&&(u.current=!0,c.current=!0,w.scrollTo({top:w.scrollHeight,behavior:b?"smooth":"auto"}),setTimeout(()=>{u.current=!1},b?300:0))},[]);d.useEffect(()=>{p.current&&(c.current&&!u.current&&requestAnimationFrame(()=>{h(!1)}),u.current||f())},[t,h,f]),d.useEffect(()=>{if(!u.current){const b=f();c.current=b}},[f]);const y=d.useCallback(()=>{u.current=!1;const b=p.current;if(!b)return;const{scrollTop:w,scrollHeight:j,clientHeight:C}=b;j-w-C>=100&&(c.current=!1)},[]),g=d.useCallback(b=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"].includes(b.key)&&(u.current=!1,requestAnimationFrame(()=>{const j=p.current;if(!j)return;const{scrollTop:C,scrollHeight:P,clientHeight:E}=j,N=P-C-E;c.current=N<100}))},[]);return e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsx("div",{ref:p,className:x("h-full overflow-y-auto flex flex-col",s),onScroll:l,onWheel:y,onTouchStart:y,onKeyDown:g,tabIndex:0,...r,children:e.jsx("div",{className:"mx-auto max-w-chat flex-1 w-full flex flex-col",children:t})}),o&&e.jsx("button",{type:"button",onClick:()=>h(!0),className:x("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(hn,{className:"size-4"})})]})});us.displayName="ChatLayout.Messages";const ps=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("bg-linear-to-t from-background to-transparent px-4 pb-4",s),...a,children:e.jsx("div",{className:"mx-auto max-w-chat",children:t})}));ps.displayName="ChatLayout.Footer";const $a=d.forwardRef(({className:s,children:t,...a},n)=>{const{sidebarOpen:r}=pe();return r?e.jsx("div",{ref:n,className:x("border-r border-border bg-card w-64 overflow-y-auto",s),...a,children:t}):null});$a.displayName="ChatLayout.Sidebar";const ms=d.forwardRef(({breakpoint:s="lg",className:t,children:a,...n},r)=>{const{panelSize:i}=pe(),[o,m]=d.useState(28);return d.useEffect(()=>{const p=()=>{const u=450/window.innerWidth*100;m(Math.max(u,28))};return p(),window.addEventListener("resize",p),()=>{window.removeEventListener("resize",p)}},[]),i==="hidden"?null:e.jsxs(e.Fragment,{children:[e.jsx(La,{withHandle:!0,className:"group-hover:opacity-100 opacity-0 transition-opacity"}),e.jsx(is,{defaultSize:30,minSize:o,maxSize:40,className:"group",children:e.jsx("div",{ref:r,className:x("hidden h-full border-l border-border bg-card overflow-y-auto transition-all duration-300",s==="md"&&"md:block",s==="lg"&&"lg:block",s==="xl"&&"xl:block",s==="2xl"&&"2xl:block",t),...n,children:a})})]})});ms.displayName="ChatLayout.Aside";const fs=Zs,gs=en,Ba=d.forwardRef(({className:s,inset:t,children:a,...n},r)=>e.jsxs(at,{ref:r,className:x("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",t&&"pl-8",s),...n,children:[a,e.jsx(fe,{className:"ml-auto h-4 w-4"})]}));Ba.displayName=at.displayName;const Ha=d.forwardRef(({className:s,...t},a)=>e.jsx(ot,{ref:a,className:x("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",s),...t}));Ha.displayName=ot.displayName;const Fe=d.forwardRef(({className:s,sideOffset:t=4,...a},n)=>e.jsx(Xs,{children:e.jsx(rt,{ref:n,sideOffset:t,className:x("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",s),...a})}));Fe.displayName=rt.displayName;const oe=d.forwardRef(({className:s,inset:t,...a},n)=>e.jsx(it,{ref:n,className:x("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",t&&"pl-8",s),...a}));oe.displayName=it.displayName;const Wa=d.forwardRef(({className:s,children:t,...a},n)=>e.jsxs(lt,{ref:n,className:x("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",s),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(ct,{children:e.jsx(Rt,{className:"h-4 w-4"})})}),t]}));Wa.displayName=lt.displayName;const Va=d.forwardRef(({className:s,children:t,...a},n)=>e.jsxs(dt,{ref:n,className:x("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",s),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(ct,{children:e.jsx(_e,{className:"h-2 w-2 fill-current"})})}),t]}));Va.displayName=dt.displayName;const qa=d.forwardRef(({className:s,inset:t,...a},n)=>e.jsx(ut,{ref:n,className:x("px-2 py-1.5 text-paragraph-sm font-semibold",t&&"pl-8",s),...a}));qa.displayName=ut.displayName;const hs=d.forwardRef(({className:s,...t},a)=>e.jsx(pt,{ref:a,className:x("-mx-1 my-1 h-px bg-border",s),...t}));hs.displayName=pt.displayName;function xs({item:s,level:t=0,onSelect:a,selectedId:n,isDropTarget:r=!1,onDownload:i,onRename:o,onDelete:m}){const[p,c]=d.useState(!0),u=n===s.id,f=()=>{s.type==="folder"&&c(!p)},l=()=>{a?.(s),s.type==="folder"&&f()},h=g=>{g.key==="Enter"||g.key===" "?(g.preventDefault(),l()):g.key==="ArrowRight"&&s.type==="folder"&&!p?(g.preventDefault(),c(!0)):g.key==="ArrowLeft"&&s.type==="folder"&&p&&(g.preventDefault(),c(!1))},y=()=>t===0?"p-2":t===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":s.type==="folder"?p:void 0,className:x("group/item flex items-center gap-2 rounded-md cursor-pointer transition-colors text-paragraph-sm",y(),"hover:bg-accent-hover","focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-border-dark",u&&"bg-accent",r&&["bg-accent","border border-dashed border-border-dark"]),onClick:l,onKeyDown:h,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:s.type==="folder"?p?e.jsx(xn,{className:"size-4"}):e.jsx(bn,{className:"size-4"}):e.jsx(yn,{className:"size-4"})}),e.jsx("p",{className:"flex-1 text-foreground whitespace-nowrap overflow-hidden text-ellipsis",children:s.name}),e.jsxs(fs,{children:[e.jsx(gs,{asChild:!0,children:e.jsx("button",{className:x("shrink-0 size-4 transition-opacity text-muted-foreground hover:text-foreground","opacity-0 group-hover/item:opacity-100","data-[state=open]:opacity-100"),onClick:g=>{g.stopPropagation()},"aria-label":"More options",type:"button",tabIndex:-1,children:e.jsx(wn,{className:"size-4"})})}),e.jsxs(Fe,{align:"end",side:"bottom",sideOffset:5,alignOffset:0,collisionPadding:8,className:"w-40 z-[100]",onClick:g=>g.stopPropagation(),children:[i&&e.jsx(oe,{onClick:g=>{g.stopPropagation(),i(s)},children:"Download"}),o&&e.jsx(oe,{onClick:g=>{g.stopPropagation(),o(s)},children:"Rename"}),(i||o)&&m&&e.jsx(hs,{}),m&&e.jsx(oe,{className:"text-destructive focus:text-destructive focus:bg-muted",onClick:g=>{g.stopPropagation(),m(s)},children:e.jsx("span",{className:"text-paragraph-sm",children:"Delete"})})]})]}),s.type==="folder"&&e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-muted-foreground",children:e.jsx(ue,{className:x("size-4 transition-transform",!p&&"-rotate-90")})})]}),s.type==="folder"&&p&&s.children&&e.jsx("div",{className:"flex flex-col",children:s.children.map(g=>e.jsx(xs,{item:g,level:t+1,...a&&{onSelect:a},...n&&{selectedId:n},...i&&{onDownload:i},...o&&{onRename:o},...m&&{onDelete:m}},g.id))})]})}const Ga=new ja;function Ka({className:s,provider:t=Ga,onItemSelect:a,onDownload:n,onRename:r,onDelete:i}){const[o,m]=d.useState([]),[p,c]=d.useState(),[u,f]=d.useState(!0),[l,h]=d.useState();d.useEffect(()=>{(async()=>{try{f(!0);const b=await t.getRootItems();m(b),h(void 0)}catch(b){h(b instanceof Error?b.message:"Failed to load items")}finally{f(!1)}})()},[t]);const y=g=>{c(g.id),a?.(g)};return u?e.jsx("div",{className:x("",s),children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):l?e.jsx("div",{className:x("",s),children:e.jsxs("p",{className:"text-sm text-destructive",children:["Error: ",l]})}):e.jsx("div",{className:x("flex flex-col",s),children:o.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items found"}):o.map(g=>e.jsx(xs,{item:g,onSelect:y,...p&&{selectedId:p},...n&&{onDownload:n},...r&&{onRename:r},...i&&{onDelete:i}},g.id))})}const bs=d.forwardRef(({source:s,isSelected:t,className:a,...n},r)=>e.jsxs("button",{ref:r,type:"button",className:x("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",t&&"bg-accent",a),onClick:()=>window.open(s.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:s.favicon?e.jsx("img",{alt:s.sourceName,className:"size-full object-cover",src:s.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:s.sourceName}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",s.title]})]}),e.jsx("p",{className:"text-paragraph-sm text-muted-foreground line-clamp-3",children:s.snippet})]})]}));bs.displayName="SourceListItem";const ys=d.forwardRef(({todo:s,className:t,...a},n)=>{const r=s.status==="completed";return e.jsxs("div",{ref:n,className:x("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,t),role:"button",tabIndex:0,...a,children:[e.jsx("div",{className:"shrink-0 size-4 flex items-center justify-center text-foreground",children:s.status==="completed"?e.jsx(Et,{className:"size-4 text-muted-foreground"}):s.status==="in_progress"?e.jsx("div",{className:"size-2.5 rounded-full bg-foreground animate-pulse-scale"}):e.jsx(_e,{className:"size-4 text-foreground"})}),e.jsx("p",{className:x("flex-1 text-foreground",r&&"line-through text-muted-foreground",s.status==="in_progress"&&"font-medium"),children:s.text})]})});ys.displayName="TodoListItem";const Oe=d.forwardRef(({client:s,todos:t,className:a,...n},r)=>{const i=t||[];return e.jsx("div",{ref:r,className:x("space-y-2 max-h-64 overflow-y-auto",a),...n,children:i.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic",children:"No tasks yet."}):i.map(o=>e.jsx(ys,{todo:o},o.id))})});Oe.displayName="TodoList";const Ie=d.forwardRef(({todos:s=[],className:t,...a},n)=>e.jsx("div",{ref:n,className:x("space-y-2",t),...a,children:e.jsx(Oe,{todos:s})}));Ie.displayName="TodoTabContent";const Re=d.forwardRef(({files:s=[],provider:t,onFileSelect:a,className:n,...r},i)=>{const o=d.useCallback(c=>{console.log("Download:",c.name)},[]),m=d.useCallback(c=>{console.log("Rename:",c.name)},[]),p=d.useCallback(c=>{console.log("Delete:",c.name)},[]);return e.jsx("div",{ref:i,className:x("h-full",n),...r,children:e.jsx(Ka,{...t&&{provider:t},onItemSelect:c=>{c.type==="file"&&a&&a(c.path||c.name)},onDownload:o,onRename:m,onDelete:p,className:"h-full"})})});Re.displayName="FilesTabContent";const Ee=d.forwardRef(({sources:s,className:t,...a},n)=>{const r=s&&s.length>0?s:Na;return e.jsx("div",{ref:n,className:x("space-y-2",t),...a,children:r.map(i=>e.jsx(bs,{source:i},i.id))})});Ee.displayName="SourcesTabContent";const Qa=d.forwardRef(({data:s,className:t,...a},n)=>e.jsxs("div",{ref:n,className:x("space-y-4",t),...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"}),s&&typeof s=="object"?e.jsx("pre",{className:"mt-2 text-caption overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));Qa.displayName="DatabaseTabContent";const $e=d.forwardRef(({tools:s=[],mcps:t=[],subagents:a=[],className:n,...r},i)=>e.jsxs("div",{ref:i,className:x("space-y-6",n),...r,children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Tools"}),s.length>0?e.jsx("div",{className:"space-y-2",children:s.map(o=>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:o.prettyName||o.name}),o.description&&e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-1",children:o.description})]},o.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No tools available"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"MCP Servers"}),t.length>0?e.jsx("div",{className:"space-y-2",children:t.map(o=>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:o.name}),e.jsxs("div",{className:"text-caption text-muted-foreground mt-1",children:["Transport: ",o.transport]})]},o.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No MCP servers connected"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-subheading",children:"Subagents"}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(o=>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:o.name}),e.jsx("div",{className:"text-caption text-muted-foreground mt-1 line-clamp-2",children:o.description})]},o.name))}):e.jsx("p",{className:"text-paragraph-sm text-muted-foreground",children:"No subagents available"})]})]}));$e.displayName="SettingsTabContent";const Be=tn,ge=d.forwardRef(({className:s,...t},a)=>e.jsx(mt,{ref:a,className:x("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...t}));ge.displayName=mt.displayName;const he=d.forwardRef(({className:s,...t},a)=>e.jsx(ft,{ref:a,className:x("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",s),...t}));he.displayName=ft.displayName;const G=d.forwardRef(({className:s,...t},a)=>e.jsx(gt,{ref:a,className:x("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));G.displayName=gt.displayName;const Ja=d.forwardRef(({client:s,todos:t,variant:a="animated",showIcons:n=!1,visibleTabs:r=["todo","files","database"],className:i,...o},m)=>{const p=t||[],[c,u]=d.useState(r[0]||"todo"),f=d.useRef(null),l=d.useRef(null);d.useEffect(()=>{const b=setTimeout(()=>{const w=f.current;if(c&&w){const j=l.current;if(j){const C=w.getBoundingClientRect(),P=j.getBoundingClientRect(),E=P.left-C.left,N=P.width,A=E/C.width*100,U=100-(E+N)/C.width*100;w.style.clipPath=`inset(0 ${U.toFixed(2)}% 0 ${A.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(b)},[c]);const y=[{id:"todo",label:a==="pills"?"To-do":"To-Do List",icon:Pe},{id:"files",label:"Files",icon:De},{id:"database",label:"Database",icon:At},{id:"sources",label:"Sources",icon:Mt}].filter(g=>r.includes(g.id));return e.jsx("div",{ref:m,className:x("select-none",i),...o,children:e.jsxs(Be,{value:c,onValueChange:u,className:"w-full",children:[a==="pills"?e.jsx(ge,{className:x("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:y.map(g=>{const b=g.icon;return e.jsxs(he,{value:g.id,className:x("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[n&&b&&e.jsx(b,{className:"size-4"}),g.label]},g.id)})}):e.jsxs("div",{className:"relative mb-4 border-border",children:[e.jsx(ge,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:y.map(g=>e.jsx(he,{value:g.id,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:g.label},g.id))}),e.jsx("div",{ref:f,className:"absolute top-0 left-0 w-full overflow-hidden z-10 pointer-events-none",style:{clipPath:"inset(0 100% 0 0% round 999px)",transition:"clip-path 0.25s ease-out"},children:e.jsx(ge,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:y.map(g=>e.jsx(he,{value:g.id,ref:c===g.id?l:null,className:"px-3 py-1 text-paragraph-sm font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:g.label},g.id))})})]}),e.jsx(G,{value:"todo",className:a==="pills"?"mt-0":"",children:a==="pills"?e.jsx(Ie,{todos:p}):e.jsx(Oe,{todos:p})}),e.jsx(G,{value:"files",className:a==="pills"?"mt-0":"",children:e.jsx(Re,{})}),e.jsx(G,{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(G,{value:"sources",className:a==="pills"?"mt-0":"",children:e.jsx(Ee,{})})]})})});Ja.displayName="ChatSecondaryPanel";const Ya=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("flex h-full flex-col",s),...a,children:t}));Ya.displayName="ChatSidebar.Root";const Xa=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("border-b border-border px-4 py-3",s),...a,children:t}));Xa.displayName="ChatSidebar.Header";const Za=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("flex-1 overflow-y-auto p-4",s),...a,children:t}));Za.displayName="ChatSidebar.Content";const eo=d.forwardRef(({className:s,children:t,...a},n)=>e.jsx("div",{ref:n,className:x("border-t border-border px-4 py-3",s),...a,children:t}));eo.displayName="ChatSidebar.Footer";const to=d.forwardRef(({children:s,className:t,...a},n)=>{const[r,i]=d.useState(s),[o,m]=d.useState(!1),p=d.useRef(s),c=d.useRef(!0);return d.useEffect(()=>{if(c.current){c.current=!1,p.current=s;return}if(p.current===s)return;m(!0);const u=setTimeout(()=>{i(s),p.current=s,requestAnimationFrame(()=>{m(!1)})},150);return()=>{clearTimeout(u)}},[s]),e.jsx("span",{ref:n,className:x("text-sm text-foreground opacity-60 transition-opacity duration-300",o?"opacity-0":"opacity-60",t),...a,children:r})});to.displayName="ChatStatus";const ae=ne("gui");function so({children:s}){const{setPanelSize:t,setActiveTab:a,panelSize:n,activeTab:r}=pe(),i=()=>{n!=="hidden"&&r==="files"?t("hidden"):(t("small"),a("files"))},o=()=>{n!=="hidden"&&r==="settings"?t("hidden"):(t("small"),a("settings"))};return e.jsx(e.Fragment,{children:s({openFiles:i,openSettings:o})})}function no(){const{panelSize:s,setPanelSize:t}=pe();return d.useEffect(()=>{const a=n=>{(n.metaKey||n.ctrlKey)&&n.key==="b"&&(n.preventDefault(),t(s==="hidden"?"small":"hidden"))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[s,t]),null}function ao({client:s,startSession:t,placeholder:a,latestContextSize:n,currentModel:r,commandMenuItems:i}){const o=R(u=>u.input.attachedFiles),m=R(u=>u.addFileAttachment),p=R(u=>u.removeFileAttachment),c=u=>{for(const f of u)m(f)};return e.jsxs(Zt,{client:s,startSession:t,children:[e.jsx(rs,{commands:i}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border-b border-border",children:o.map((u,f)=>e.jsxs("div",{className:"relative group rounded-md overflow-hidden border border-border",children:[e.jsx("img",{src:`data:${u.mimeType};base64,${u.data}`,alt:u.name,className:"h-20 w-20 object-cover"}),e.jsx("button",{type:"button",onClick:()=>p(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"})})]},f))}),e.jsx(es,{placeholder:a,autoFocus:!0,onFilesDropped:c}),e.jsxs(ss,{children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx(ns,{}),e.jsx(as,{onFilesSelected:c}),n!=null&&e.jsx(Ns,{contextSize:n,modelContextWindow:r?.includes("claude")?2e5:128e3})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(os,{}),e.jsx(ts,{children:e.jsx(jn,{className:"size-4"})})]})]})]})}function oo({todos:s,tools:t,mcps:a,subagents:n}){const{activeTab:r,setActiveTab:i}=pe();return e.jsxs(Be,{value:r,onValueChange:o=>i(o),className:"flex flex-col h-full",children:[e.jsx("div",{className:x("border-b border-border bg-card","px-6 py-2 h-16","flex items-center","[border-bottom-width:0.5px]"),children:e.jsx(We,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"compact"})}),e.jsx(G,{value:"todo",className:"flex-1 p-4 mt-0",children:e.jsx(Ie,{todos:s})}),e.jsx(G,{value:"files",className:"flex-1 p-4 mt-0",children:e.jsx(Re,{})}),e.jsx(G,{value:"sources",className:"flex-1 p-4 mt-0",children:e.jsx(Ee,{})}),e.jsx(G,{value:"settings",className:"flex-1 p-4 mt-0 overflow-y-auto",children:e.jsx($e,{tools:t??[],mcps:a??[],subagents:n??[]})})]})}function ro({agentName:s,showHeader:t}){const{isExpanded:a,setIsExpanded:n}=ze();return e.jsxs("div",{className:"flex lg:hidden items-center flex-1",children:[t&&e.jsx("div",{className:"flex items-center gap-2 flex-1",children:e.jsx("h1",{className:"text-heading-4 text-foreground",children:s})}),!t&&e.jsx("div",{className:"flex-1"}),e.jsx(_s,{}),e.jsx(be,{"aria-label":"Toggle menu",onClick:()=>n(!a),children:e.jsx(Dt,{className:x("size-4 text-muted-foreground transition-transform duration-200",a?"":"rotate-180")})})]})}function io({agentName:s,todos:t,sources:a,showHeader:n,sessionId:r,debuggerUrl:i,tools:o,mcps:m,subagents:p}){const{panelSize:c,setPanelSize:u}=pe(),f=r&&i?`${i}/sessions/${r}`:null;return e.jsxs(Qt,{className:x("border-b border-border bg-card relative lg:p-0","[border-bottom-width:0.5px]"),children:[e.jsxs("div",{className:"hidden lg:flex items-center w-full h-16 py-5 pl-6 pr-4",children:[n&&e.jsx("div",{className:"flex items-center gap-2 flex-1",children:e.jsx("h1",{className:"text-heading-4 text-foreground",children:s})}),!n&&e.jsx("div",{className:"flex-1"}),i&&e.jsx(ws,{children:e.jsxs(vs,{children:[e.jsx(js,{asChild:!0,children:e.jsx(be,{"aria-label":"View session in debugger",disabled:!f,asChild:!!f,children:f?e.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ge,{className:"size-4 text-muted-foreground"})}):e.jsx(Ge,{className:"size-4 text-muted-foreground"})})}),e.jsx(He,{children:e.jsx("p",{children:"View session in debugger"})})]})}),e.jsx(_s,{}),e.jsx(be,{"aria-label":"Toggle sidebar",onClick:()=>{u(c==="hidden"?"small":"hidden")},children:e.jsx(vn,{className:"size-4 text-muted-foreground"})})]}),e.jsx(ro,{agentName:s,showHeader:n}),e.jsx(Jt,{className:x("pt-6 pb-8 px-6","border-b border-border bg-card","shadow-[0_4px_16px_0_rgba(0,0,0,0.04)]","[border-bottom-width:0.5px]"),children:e.jsxs(Be,{defaultValue:"todo",className:"w-full",children:[e.jsx(We,{showIcons:!0,visibleTabs:["todo","files","sources","settings"],variant:"default"}),e.jsx(G,{value:"todo",className:"mt-4",children:e.jsx(Ie,{todos:t})}),e.jsx(G,{value:"files",className:"mt-4",children:e.jsx(Re,{})}),e.jsx(G,{value:"sources",className:"mt-4",children:e.jsx(Ee,{sources:a})}),e.jsx(G,{value:"settings",className:"mt-4",children:e.jsx($e,{tools:o??[],mcps:m??[],subagents:p??[]})})]})})]})}function lo({client:s,initialSessionId:t,error:a,debuggerUrl:n}){const{connectionStatus:r,connect:i,sessionId:o,startSession:m}=Xn(s,t),{messages:p,sendMessage:c}=Bt(s,m);ta(s);const u=R(T=>T.error),f=R(T=>T.currentModel),[l,h]=d.useState("Agent"),[y,g]=d.useState("This research agent can help you find and summarize information, analyze sources, track tasks, and answer questions about your research. Start by typing a message below to begin your investigation."),[b,w]=d.useState(["Search the web for the latest news on top tech company earnings, produce a summary for each company, and then a macro trend analysis of the tech industry. Use your todo list","What can you help me with?"]),[j,C]=d.useState([]),[P,E]=d.useState([]),[N,A]=d.useState([]),[U,F]=d.useState(typeof window<"u"?window.innerWidth>=1024:!0),[K,Z]=d.useState("Type a message or / for commands...");d.useEffect(()=>{ae.debug("Connection status changed",{status:r}),r==="error"&&u&&ae.error("Connection error occurred",{error:u})},[r,u]),d.useEffect(()=>{if(s){const T=s.getCurrentSession();T?.metadata?.agentName&&h(T.metadata.agentName);const S=s.getAgentInfo();S.displayName?h(S.displayName):S.name&&h(S.name),S.description&&g(S.description),S.suggestedPrompts&&S.suggestedPrompts.length>0&&w(S.suggestedPrompts),S.tools&&S.tools.length>0&&(C(S.tools),ae.info("Agent tools loaded",{tools:S.tools})),S.mcps&&S.mcps.length>0&&(E(S.mcps),ae.info("Agent MCPs loaded",{mcps:S.mcps})),S.subagents&&S.subagents.length>0&&(A(S.subagents),ae.info("Agent subagents loaded",{subagents:S.subagents}))}},[s,o,r]),d.useEffect(()=>{const T=window.matchMedia("(min-width: 1024px)"),S=z=>{F(z.matches)};return F(T.matches),T.addEventListener("change",S),()=>{T.removeEventListener("change",S)}},[]);const I=T=>{Z(T)},L=()=>{Z("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=R(Jn),q=[{id:"1",title:"Boeing Scores Early Wins at Dubai Airshow",sourceName:"Reuters",url:"https://www.reuters.com/markets/companies/BA.N",snippet:"DUBAI, Nov 17 (Reuters) - Boeing (BA.N), opens new tab took centre stage at day one of the Dubai Airshow on Monday, booking a $38 billion order from host carrier Emirates and clinching more deals with African carriers, while China displayed its C919 in the Middle East for the first time.",favicon:"https://www.google.com/s2/favicons?domain=reuters.com&sz=32"},{id:"2",title:"Boeing's Sustainable Aviation Goals Take Flight",sourceName:"Forbes",url:"https://www.forbes.com",snippet:"SEATTLE, Nov 18 (Reuters) - Boeing is making headway towards its sustainability targets, unveiling plans for a new eco-friendly aircraft design aimed at reducing emissions by 50% by 2030.",favicon:"https://www.google.com/s2/favicons?domain=forbes.com&sz=32"},{id:"3",title:"Boeing Faces Increased Competition in Global Aviation Market",sourceName:"Reuters",url:"https://www.reuters.com",snippet:"CHICAGO, Nov 19 (Reuters) - As the global aviation industry rebounds post-pandemic, Boeing is grappling with intensified competition from rival manufacturers, particularly in the Asian market.",favicon:"https://www.google.com/s2/favicons?domain=reuters.com&sz=32"},{id:"4",title:"Boeing's Starliner Successfully Completes Orbital Test Flight",sourceName:"The Verge",url:"https://www.theverge.com",snippet:"NASA, Nov 20 (Reuters) - Boeing's CST-100 Starliner spacecraft achieves a significant milestone, successfully completing its orbital test flight, paving the way for future crewed missions to the International Space Station.",favicon:"https://www.google.com/s2/favicons?domain=theverge.com&sz=32"}],Y=R(T=>T.latestContextSize),k=[{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:e.jsx(_t,{className:"h-4 w-4"}),category:"action",onSelect:()=>{ae.info("User opened settings")}}];return e.jsxs(ls,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[e.jsx(no,{}),e.jsxs(cs,{children:[e.jsx(io,{agentName:l,todos:V,sources:q,showHeader:p.length>0,sessionId:o,tools:j,mcps:P,subagents:N,...n&&{debuggerUrl:n}}),r==="error"&&u&&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:u})]}),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(ds,{children:[e.jsx(us,{children:p.length===0?e.jsx(so,{children:({openFiles:T,openSettings:S})=>e.jsx("div",{className:"flex flex-1 items-center px-4",children:e.jsx(Gt,{title:l,description:y,suggestedPrompts:b,onPromptClick:z=>{c(z),Z("Type a message or / for commands..."),ae.info("Prompt clicked",{prompt:z})},onPromptHover:I,onPromptLeave:L,onOpenFiles:T,onOpenSettings:S,toolsAndMcpsCount:j.length+P.length+N.length})})}):e.jsx("div",{className:"flex flex-col px-4",children:p.map((T,S)=>{const z=S===0,$=z?null:p[S-1];let W="mt-2";return z?W="mt-2":T.role==="user"?W=($?.role==="user","mt-4"):T.role==="assistant"&&(W=$?.role==="assistant"?"mt-2":"mt-6"),e.jsx(Cs,{message:T,className:W,isLastMessage:S===p.length-1,children:e.jsx(Rs,{message:T,thinkingDisplayStyle:"collapsible"})},T.id)})})}),e.jsx(ps,{children:e.jsx(ao,{client:s,startSession:m,placeholder:K,latestContextSize:Y,currentModel:f,commandMenuItems:k})})]})]}),U&&e.jsx(ms,{breakpoint:"lg",children:e.jsx(oo,{todos:V,tools:j,mcps:P,subagents:N})})]})}const ws=sn,vs=nn,js=an,He=d.forwardRef(({className:s,sideOffset:t=4,...a},n)=>e.jsx(ht,{ref:n,sideOffset:t,className:x("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",s),...a}));He.displayName=ht.displayName;const Ns=d.forwardRef(({contextSize:s,modelContextWindow:t,className:a,...n},r)=>{const i=Math.max(s.totalEstimated,s.llmReportedInputTokens??0),o=i/t*100,m=`${o.toFixed(1)}%`,p=Math.min(100,Math.max(0,o)),u=(j=>j<50?"text-foreground":j<75?"text-yellow-500":"text-red-500")(o),f=j=>i===0?"0.0%":`${(j/i*100).toFixed(1)}%`,l=16,h=2,y=(l-h)/2,g=l/2,b=2*Math.PI*y,w=b-p/100*b;return e.jsx(ws,{children:e.jsxs(vs,{children:[e.jsx(js,{asChild:!0,children:e.jsx(ie,{ref:r,type:"button",variant:"ghost",size:"icon",className:x("rounded-full cursor-default",u,a),...n,children:e.jsxs("svg",{width:l,height:l,viewBox:`0 0 ${l} ${l}`,className:"transform -rotate-90",children:[e.jsx("circle",{cx:g,cy:g,r:y,stroke:"currentColor",strokeWidth:h,fill:"transparent",className:"opacity-20"}),e.jsx("circle",{cx:g,cy:g,r:y,stroke:"currentColor",strokeWidth:h,fill:"transparent",strokeDasharray:b,strokeDashoffset:w,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]})})}),e.jsx(He,{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:s.systemPromptTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.systemPromptTokens),")"]})]})]}),s.toolOverheadTokens!==void 0&&s.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:s.toolOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.toolOverheadTokens),")"]})]})]}),s.mcpOverheadTokens!==void 0&&s.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:s.mcpOverheadTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.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:s.userMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.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:s.assistantMessagesTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.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:s.toolInputTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.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:s.toolResultsTokens.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",f(s.toolResultsTokens),")"]})]})]})]}),e.jsx("div",{className:"border-t border-border pt-2",children:e.jsxs("div",{className:x("flex justify-end gap-2 font-semibold",u),children:[e.jsx("span",{children:i.toLocaleString()}),e.jsxs("span",{children:["(",m,")"]})]})})]})})]})})});Ns.displayName="ContextUsageButton";const co=d.forwardRef(({autoScroll:s=!0,isStreaming:t=!1,scrollBehavior:a="smooth",scrollThreshold:n=100,showScrollButton:r=!0,scrollButton:i,className:o,children:m,...p},c)=>{const u=d.useRef(null),[f,l]=d.useState(!0),[h,y]=d.useState(!1),g=d.useRef(0);d.useImperativeHandle(c,()=>{if(!u.current)throw new Error("Container ref not initialized");return u.current});const b=d.useCallback(()=>{const j=u.current;if(!j)return;const{scrollTop:C,scrollHeight:P,clientHeight:E}=j,A=P-C-E<n;l(A),y(!A&&r),g.current=C},[n,r]),w=d.useCallback((j=a)=>{const C=u.current;C&&C.scrollTo({top:C.scrollHeight,behavior:j})},[a]);return d.useEffect(()=>{!s||!u.current||(t&&f?w("auto"):!t&&f&&w())},[s,t,f,w]),d.useEffect(()=>{const j=u.current;if(!j)return;const C=()=>{b()};return j.addEventListener("scroll",C,{passive:!0}),b(),()=>{j.removeEventListener("scroll",C)}},[b]),d.useEffect(()=>{const j=u.current;if(!j)return;const C=new ResizeObserver(()=>{f&&s&&w("auto")});return C.observe(j),()=>{C.disconnect()}},[f,s,w]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx("div",{ref:u,className:x("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",o),...p,children:e.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:m})}),h&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||e.jsxs("button",{type:"button",onClick:()=>w(),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"]})})]})});co.displayName="Conversation";const uo=on,Ss=d.forwardRef(({className:s,...t},a)=>e.jsx(xt,{ref:a,className:x("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",s),...t}));Ss.displayName=xt.displayName;const po=d.forwardRef(({className:s,children:t,...a},n)=>e.jsxs(uo,{children:[e.jsx(Ss,{}),e.jsxs(bt,{ref:n,className:x("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",s),...a,children:[t,e.jsxs(rn,{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"})]})]})]}));po.displayName=bt.displayName;const mo=d.forwardRef(({className:s,...t},a)=>e.jsx(yt,{ref:a,className:x("text-subheading font-semibold leading-none tracking-tight",s),...t}));mo.displayName=yt.displayName;const fo=d.forwardRef(({className:s,...t},a)=>e.jsx(wt,{ref:a,className:x("text-paragraph-sm text-muted-foreground",s),...t}));fo.displayName=wt.displayName;const be=d.forwardRef(({className:s,...t},a)=>e.jsx(ie,{ref:a,variant:"ghost",size:"icon",className:x("rounded-full",s),...t}));be.displayName="IconButton";const go=re("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"}}),ho=d.forwardRef(({className:s,type:t,variant:a,...n},r)=>e.jsx("input",{type:t,className:x(go({variant:a,className:s})),ref:r,...n}));ho.displayName="Input";const xo=d.forwardRef(({className:s,...t},a)=>e.jsx(vt,{ref:a,className:x("text-label font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...t}));xo.displayName=vt.displayName;const bo=re("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"}}),Cs=d.forwardRef(({message:s,role:t,layout:a,className:n,children:r,messageId:i,autoScroll:o,isLastMessage:m=!1,...p},c)=>{const u=s?s.role:t||"assistant",f=s?s.id:i,l=d.useRef(null),[h,y]=d.useState(void 0);return d.useImperativeHandle(c,()=>l.current),d.useEffect(()=>{if(!m||u!=="assistant"){y(void 0);return}const g=()=>{const w=l.current;if(!w)return;let j=w.parentElement;for(;j&&!j.classList.contains("overflow-y-auto");)j=j.parentElement;if(!j)return;const C=w.previousElementSibling;if(!C||C.getAttribute("aria-label")!=="user message"){y(void 0);return}const P=j.clientHeight,E=C.offsetHeight,A=Math.max(0,P-E-32);y(A)};g();const b=new ResizeObserver(g);if(l.current){b.observe(l.current);let w=l.current.parentElement;for(;w&&!w.classList.contains("overflow-y-auto");)w=w.parentElement;w&&b.observe(w)}return()=>b.disconnect()},[m,u]),d.useEffect(()=>{if((o!==void 0?o:u==="user")&&l.current){const b=setTimeout(()=>{l.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(b)}},[u,o]),e.jsx("article",{ref:l,"aria-label":`${u} message`,"data-message-id":f,className:x(bo({role:u,layout:a}),n),style:{minHeight:h!==void 0?`${h}px`:void 0},...p,children:r})});Cs.displayName="Message";function Xe({toolCalls:s}){const t=s.map(r=>r.prettyName||r.title),a=[...new Set(t)],n=a.length<=2?a.join(", "):`${a.slice(0,2).join(", ")} +${a.length-2} more`;return e.jsxs("div",{className:"flex flex-col my-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-paragraph-sm text-muted-foreground/50",children:[e.jsx(Ut,{className:"h-3 w-3"}),e.jsx("span",{children:"Invoking parallel operation"}),e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-muted-foreground/50",children:s.length})]}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground/50 pl-4.5",children:n})]})}const Ze=re("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"}}),yo=re("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Ts=d.forwardRef(({content:s,isStreaming:t=!1,mode:a="collapsible",defaultExpanded:n=!1,autoExpand:r=!1,autoCollapse:i=!0,autoCollapseDelay:o=2e3,label:m="Thinking",variant:p,className:c},u)=>{const[f,l]=d.useState(a==="inline"?!0:n),[h,y]=d.useState(!1);return d.useEffect(()=>{if(i&&!t&&s&&a==="collapsible"){const g=setTimeout(()=>{y(!0),l(!1)},o);return()=>clearTimeout(g)}},[t,s,i,o,a]),d.useEffect(()=>{r&&t&&a==="collapsible"&&!h&&l(!0)},[r,t,a,h]),!s&&!t?null:a==="inline"?e.jsxs("div",{ref:u,className:x(Ze({variant:p}),"p-3",c),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:m}),t&&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:[s,t&&s&&e.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):e.jsxs("div",{ref:u,className:x("mb-3",c),children:[e.jsxs("button",{type:"button",onClick:()=>{l(!f),y(!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:m}),t&&e.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!f&&s&&e.jsxs("span",{className:"text-caption text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),e.jsx(ue,{className:yo({expanded:f}),"aria-hidden":"true"})]}),f&&e.jsx("div",{className:x(Ze({variant:p}),"mt-2 p-3 animate-fadeIn"),children:e.jsxs("div",{className:"text-paragraph-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,t&&s&&e.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});Ts.displayName="Reasoning";const Se=d.forwardRef(({content:s,isStreaming:t=!1,showEmpty:a=!0,emptyMessage:n="",className:r,...i},o)=>{if(!s&&t&&a)return e.jsx("div",{ref:o,className:x("opacity-70 italic text-paragraph-sm",r),...i,children:n});if(!s)return null;const m={table:({node:p,...c})=>e.jsx("div",{className:"overflow-x-auto my-4",children:e.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...c})}),thead:({node:p,...c})=>e.jsx("thead",{className:"bg-card border-b border-border",...c}),tbody:({node:p,...c})=>e.jsx("tbody",{...c}),tr:({node:p,...c})=>e.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...c}),th:({node:p,...c})=>e.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...c}),td:({node:p,...c})=>e.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...c}),input:({node:p,checked:c,...u})=>u.type==="checkbox"?e.jsx("input",{type:"checkbox",checked:c||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...u}):e.jsx("input",{...u}),code:({node:p,...c})=>c.className?.includes("language-")?e.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-code text-foreground shadow-sm",...c}):e.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-code text-foreground",...c}),pre:({node:p,...c})=>e.jsx("pre",{className:"my-4 rounded-lg",...c}),h1:({node:p,...c})=>e.jsx("h1",{className:"text-heading-3 mt-6 mb-4 text-foreground border-b border-border pb-2",...c}),h2:({node:p,...c})=>e.jsx("h2",{className:"text-subheading mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...c}),h3:({node:p,...c})=>e.jsx("h3",{className:"text-subheading mt-4 mb-2 text-foreground",...c}),h4:({node:p,...c})=>e.jsx("h4",{className:"text-paragraph-sm font-semibold mt-3 mb-2 text-foreground",...c}),ul:({node:p,...c})=>{const u=p?.children?.some(f=>typeof f=="object"&&f!==null&&"type"in f&&f.type==="element"&&"tagName"in f&&f.tagName==="li"&&"children"in f&&Array.isArray(f.children)&&f.children.some(l=>typeof l=="object"&&l!==null&&"type"in l&&l.type==="element"&&"tagName"in l&&l.tagName==="input"&&"properties"in l&&typeof l.properties=="object"&&l.properties!==null&&"type"in l.properties&&l.properties.type==="checkbox"));return e.jsx("ul",{className:x("my-2 space-y-1 text-foreground",u?"list-none space-y-2":"list-disc list-outside pl-4"),...c})},ol:({node:p,...c})=>e.jsx("ol",{className:"list-decimal list-outside pl-4 my-2 space-y-1 text-foreground",...c}),li:({node:p,...c})=>{const u=p?.children?.some(f=>typeof f=="object"&&f!==null&&"type"in f&&f.type==="element"&&"tagName"in f&&f.tagName==="input"&&"properties"in f&&typeof f.properties=="object"&&f.properties!==null&&"type"in f.properties&&f.properties.type==="checkbox");return e.jsx("li",{className:x(u?"flex items-start gap-2":""),...c})},a:({node:p,...c})=>e.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...c}),p:({node:p,...c})=>e.jsx("p",{className:"mb-2 text-foreground leading-relaxed",...c}),blockquote:({node:p,...c})=>e.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2 rounded-r-md shadow-sm",...c}),hr:({node:p,...c})=>e.jsx("hr",{className:"my-6 border-t border-border opacity-50",...c}),img:({node:p,...c})=>e.jsx("img",{className:"max-w-full h-auto rounded-md border border-border my-4",loading:"lazy",...c})};return e.jsx("div",{ref:o,className:x("markdown-content prose prose-sm max-w-none dark:prose-invert",r),...i,children:e.jsx(Os,{remarkPlugins:[Dn],components:m,children:s})})});Se.displayName="Response";const wo={theme:"system",setTheme:()=>null,resolvedTheme:"light"},ks=d.createContext(wo);function vo({children:s,defaultTheme:t="system",storageKey:a="vite-ui-theme"}){const[n,r]=d.useState(()=>localStorage.getItem(a)||t),[i,o]=d.useState("light");d.useEffect(()=>{const p=window.document.documentElement;if(p.classList.remove("light","dark"),n==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";p.classList.add(c),o(c);return}p.classList.add(n),o(n)},[n]);const m={theme:n,setTheme:p=>{localStorage.setItem(a,p),r(p)},resolvedTheme:i};return e.jsx(ks.Provider,{value:m,children:s})}const Is=()=>{const s=d.useContext(ks);if(s===void 0)throw new Error("useTheme must be used within a ThemeProvider");return s},et={Globe:Rn,Image:In,Link:kn,Cloud:Tn,CheckSquare:Pe,Search:Cn,FileText:De,Edit:Sn,Wrench:Nn,BrainCircuit:zt};function me({toolCall:s}){const[t,a]=d.useState(!1),{resolvedTheme:n}=Is(),r=s.title==="todo_write",i=Me.useContext(Le),o=Me.useCallback(()=>{r&&i?i.panelSize!=="hidden"&&i.activeTab==="todo"?i.setPanelSize("hidden"):(i.setPanelSize("small"),i.setActiveTab("todo")):a(!t)},[r,i,t]),m=s.icon&&et[s.icon]?et[s.icon]:zt,p=s.prettyName||s.title,c=s.status==="failed"||!!s.error,u=s.status==="pending"&&(!s.rawInput||Object.keys(s.rawInput).length===0),f={fontSize:"11px",backgroundColor:"transparent",fontFamily:"inherit","--w-rjv-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-key-string":n==="dark"?"#fafafa":"#09090b","--w-rjv-background-color":"transparent","--w-rjv-line-color":n==="dark"?"#27272a":"#e4e4e7","--w-rjv-arrow-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-edit-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-info-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-update-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-color":n==="dark"?"#fafafa":"#09090b","--w-rjv-copied-success-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-curlybraces-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-colon-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-brackets-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-quotes-string-color":n==="dark"?"#a1a1aa":"#71717a","--w-rjv-type-string-color":n==="dark"?"#22c55e":"#16a34a","--w-rjv-type-int-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-float-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-bigint-color":n==="dark"?"#f59e0b":"#d97706","--w-rjv-type-boolean-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-date-color":n==="dark"?"#ec4899":"#db2777","--w-rjv-type-url-color":n==="dark"?"#3b82f6":"#2563eb","--w-rjv-type-null-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-nan-color":n==="dark"?"#ef4444":"#dc2626","--w-rjv-type-undefined-color":n==="dark"?"#ef4444":"#dc2626"};return u?e.jsx("div",{className:"flex flex-col my-4",children:e.jsxs("span",{className:"text-paragraph-sm text-muted-foreground/50",children:["Invoking ",p]})}):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",onClick:o,"aria-expanded":r?void 0:t,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("div",{className:"text-muted-foreground",children:e.jsx(m,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:p}),c&&e.jsx(En,{className:"h-3 w-3 text-destructive"}),r?e.jsx(fe,{className:"h-3 w-3 text-muted-foreground/70"}):e.jsx(ue,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${t?"rotate-180":""}`})]}),s.subline&&e.jsx("span",{className:"text-paragraph-sm text-muted-foreground/70 pl-4.5",children:s.subline})]}),!r&&t&&e.jsxs("div",{className:"mt-2 text-sm border border-border rounded-lg bg-card overflow-hidden w-full",children:[s.locations&&s.locations.length>0&&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:"Files"}),e.jsx("ul",{className:"space-y-1",children:s.locations.map(l=>e.jsxs("li",{className:"font-mono text-[11px] text-foreground bg-muted px-1.5 py-0.5 rounded w-fit",children:[l.path,l.line!==null&&l.line!==void 0&&`:${l.line}`]},`${l.path}:${l.line??""}`))})]}),s.rawInput&&Object.keys(s.rawInput).length>0&&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:"Input"}),e.jsx("div",{className:"text-[11px] font-mono text-foreground",children:e.jsx(Ve,{value:s.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:f})})]}),s.content&&s.content.length>0||s.error?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:"Output"}),e.jsxs("div",{className:"space-y-2 text-[11px] text-foreground",children:[s.content?.map((l,h)=>{const y=()=>l.type==="diff"&&"path"in l?`diff-${l.path}-${h}`:l.type==="terminal"&&"terminalId"in l?`terminal-${l.terminalId}`:l.type==="text"&&"text"in l?`text-${l.text.substring(0,20)}-${h}`:l.type==="content"&&"content"in l?`content-${l.content.text?.substring(0,20)}-${h}`:`block-${h}`,g=(b,w)=>{try{const j=JSON.parse(b);if(typeof j=="object"&&j!==null)return e.jsx("div",{className:"text-[11px]",children:e.jsx(Ve,{value:j,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:f})},w)}catch{}return e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] text-foreground overflow-x-auto",children:b},w)};if(l.type==="content"&&"content"in l){const b=l.content;if(b.type==="text"&&b.text)return g(b.text,y())}if(l.type==="text"&&"text"in l)return g(l.text,y());if(l.type==="image"){const b=l.alt||"Generated image";let w;if("data"in l)w=`data:${l.mimeType||"image/png"};base64,${l.data}`;else if("url"in l)w=l.url;else return null;return e.jsx("div",{className:"my-2",children:e.jsx("img",{src:w,alt:b,className:"max-w-full h-auto rounded-md border border-border"})},y())}return l.type==="diff"&&"path"in l&&"oldText"in l&&"newText"in l?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-muted-foreground border-b border-border",children:[l.path,"line"in l&&l.line!==null&&l.line!==void 0&&`:${l.line}`]}),e.jsxs("div",{className:"p-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"text-red-500 dark:text-red-400",children:["- ",l.oldText]}),e.jsxs("div",{className:"text-green-500 dark:text-green-400",children:["+ ",l.newText]})]})]},y()):l.type==="terminal"&&"terminalId"in l?e.jsxs("div",{className:"bg-neutral-900 text-neutral-100 p-2 rounded text-[11px] font-mono",children:["Terminal: ",l.terminalId]},y()):null}),s.error&&e.jsxs("div",{className:"text-destructive font-mono text-[11px] mt-2",children:["Error: ",s.error]})]})]}):null,s._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:s._meta.truncationWarning})]}),(s.tokenUsage||s.startedAt)&&e.jsxs("div",{className:"p-2 bg-muted/50 border-t border-border flex flex-wrap gap-4 text-[10px] text-muted-foreground font-sans",children:[s.tokenUsage&&e.jsxs("div",{className:"flex gap-3",children:[s.tokenUsage.inputTokens!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Input:"}),s.tokenUsage.inputTokens.toLocaleString()]}),s.tokenUsage.outputTokens!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Output:"}),s.tokenUsage.outputTokens.toLocaleString()]}),s.tokenUsage.totalTokens!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"uppercase tracking-wide font-semibold mr-1",children:"Total:"}),s.tokenUsage.totalTokens.toLocaleString()]})]}),s.startedAt&&e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsxs("span",{children:["Started: ",new Date(s.startedAt).toLocaleTimeString()]}),s.completedAt&&e.jsxs("span",{children:["Completed:"," ",new Date(s.completedAt).toLocaleTimeString()," (",Math.round((s.completedAt-s.startedAt)/1e3),"s)"]})]})]})]})]})}function tt({toolCalls:s}){const[t,a]=d.useState(!1);(()=>{const m=s.map(p=>p.status);return m.some(p=>p==="failed")?"failed":m.some(p=>p==="in_progress")?"in_progress":m.every(p=>p==="completed")?"completed":"pending"})();const r=s.map(m=>m.prettyName||m.title),i=[...new Set(r)],o=i.length<=2?i.join(", "):`${i.slice(0,2).join(", ")} +${i.length-2} more`;return e.jsxs("div",{className:"flex flex-col my-4",children:[e.jsxs("button",{type:"button",className:"flex flex-col items-start gap-0.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>a(!t),"aria-expanded":t,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("div",{className:"text-muted-foreground",children:e.jsx(Ut,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-paragraph-sm text-muted-foreground",children:"Parallel operation"}),e.jsx("span",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded text-muted-foreground/70",children:s.length}),e.jsx(ue,{className:`h-3 w-3 text-muted-foreground/70 transition-transform duration-200 ${t?"rotate-180":""}`})]}),!t&&e.jsx("span",{className:"text-paragraph-sm text-muted-foreground/70 pl-4.5",children:o})]}),t&&e.jsx("div",{className:"mt-1",children:s.map(m=>e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"w-2.5 h-4 border-l-2 border-b-2 border-border rounded-bl-[6px] mt-1 mr-0.5 shrink-0"}),e.jsx("div",{className:"flex-1 -mt-2",children:e.jsx(me,{toolCall:m})})]},m.id))})]})}const jo=re("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"}}),Rs=d.forwardRef(({role:s,variant:t,isStreaming:a,message:n,thinkingDisplayStyle:r="collapsible",className:i,children:o,...m},p)=>{const c=R(y=>y.streamingStartTime);R(y=>y.currentModel);const u=n&&!o,f=u?n.role:s||"assistant",l=u?n.isStreaming:a;let h=o;if(u){const y=n.metadata?.thinking,g=!!y,b=n.isStreaming&&!n.content&&n.role==="assistant";h=e.jsxs(e.Fragment,{children:[n.role==="assistant"&&g&&e.jsx(Ts,{content:y,isStreaming:n.isStreaming,mode:r,autoCollapse:!0}),b&&c&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"size-2.5 rounded-full bg-foreground animate-pulse-scale"})}),n.role==="assistant"?(()=>{const w=(n.toolCalls||[]).slice().sort((I,L)=>(I.contentPosition??1/0)-(L.contentPosition??1/0)),j=I=>I.status==="pending"&&(!I.rawInput||Object.keys(I.rawInput).length===0),C=I=>{const L=[],V=new Map;let q=[];const Y=()=>{q.length>1?L.push({type:"invoking",toolCalls:q}):q.length===1&&L.push(q[0]),q=[]};for(const k of I)if(k.batchId){Y();const T=V.get(k.batchId);if(T)T.push(k);else{const S=[k];V.set(k.batchId,S),L.push({type:"batch",toolCalls:S})}}else j(k)?q.push(k):(Y(),L.push(k));return Y(),L},P=(I,L)=>typeof I=="object"&&"type"in I&&I.type==="batch"?e.jsx(tt,{toolCalls:I.toolCalls},`batch-${I.toolCalls[0]?.batchId||L}`):typeof I=="object"&&"type"in I&&I.type==="invoking"?e.jsx(Xe,{toolCalls:I.toolCalls},`invoking-${I.toolCalls[0]?.id||L}`):e.jsx(me,{toolCall:I},I.id);if(w.length===0||!w.some(I=>I.contentPosition!==void 0)){const I=C(w);return e.jsxs(e.Fragment,{children:[I.length>0&&e.jsx("div",{className:"flex flex-col gap-2 mb-1",children:I.map((L,V)=>P(L,V))}),e.jsx(Se,{content:n.content,isStreaming:n.isStreaming,showEmpty:!1})]})}const E=[];let N=0,A=[],U;const F=()=>{A.length>1&&U?E.push(e.jsx(tt,{toolCalls:A},`group-${U}`)):A.length===1&&E.push(e.jsx("div",{children:e.jsx(me,{toolCall:A[0]})},`tool-${A[0].id}`)),A=[],U=void 0},K=w.filter(j),Z=w.filter(I=>!j(I));if(Z.forEach((I,L)=>{const V=I.contentPosition??n.content.length;if(V>N){F();const q=n.content.slice(N,V);q&&E.push(e.jsx(Se,{content:q,isStreaming:!1,showEmpty:!1},`text-before-${I.id}`))}I.batchId?U===I.batchId?A.push(I):(F(),U=I.batchId,A=[I]):(F(),E.push(e.jsx("div",{children:e.jsx(me,{toolCall:I})},`tool-${I.id}`))),N=V,L===Z.length-1&&F()}),N<n.content.length){const I=n.content.slice(N);I&&E.push(e.jsx(Se,{content:I,isStreaming:n.isStreaming,showEmpty:!1},"text-end"))}return K.length>0&&(K.length>1?E.push(e.jsx(Xe,{toolCalls:K},`invoking-group-${K[0].id}`)):E.push(e.jsx("div",{children:e.jsx(me,{toolCall:K[0]})},`tool-${K[0].id}`))),e.jsx(e.Fragment,{children:E})})():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((w,j)=>e.jsx("img",{src:`data:${w.mimeType};base64,${w.data}`,alt:`Attachment ${j+1}`,className:"max-w-[200px] max-h-[200px] rounded-lg object-cover"},j))}),n.content&&e.jsx("div",{className:"whitespace-pre-wrap",children:n.content})]})]})}return e.jsx("div",{ref:p,className:x(jo({role:f,variant:t}),l&&"animate-pulse-subtle",i),...m,children:h})});Rs.displayName="MessageContent";const We=d.forwardRef(({showIcons:s=!0,visibleTabs:t=["todo","files"],variant:a="default",className:n,...r},i)=>{const m=[{id:"todo",label:"To-do",icon:Pe},{id:"files",label:"Files",icon:De},{id:"database",label:"Database",icon:At},{id:"sources",label:"Sources",icon:Mt},{id:"settings",label:"Settings",icon:_t}].filter(c=>t.includes(c.id)),p=a==="compact"?"gap-[4px]":"gap-3";return e.jsx(ge,{ref:i,className:x("w-full justify-start bg-transparent p-0 h-auto",p,n),...r,children:m.map(c=>{const u=c.icon;return e.jsxs(he,{value:c.id,className:x("gap-2 px-3 py-1.5 rounded-lg text-paragraph-sm font-medium","data-[state=active]:bg-muted data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground hover:text-foreground transition-colors"),children:[s&&u&&e.jsx(u,{className:"size-4"}),c.label]},c.id)})})});We.displayName="PanelTabsHeader";const No=d.forwardRef(({className:s,children:t,...a},n)=>e.jsxs(jt,{ref:n,className:x("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",s),...a,children:[t,e.jsx(ln,{asChild:!0,children:e.jsx(An,{className:"h-4 w-4 opacity-50"})})]}));No.displayName=jt.displayName;const Es=d.forwardRef(({className:s,...t},a)=>e.jsx(Nt,{ref:a,className:x("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Dt,{className:"h-4 w-4"})}));Es.displayName=Nt.displayName;const As=d.forwardRef(({className:s,...t},a)=>e.jsx(St,{ref:a,className:x("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(ue,{className:"h-4 w-4"})}));As.displayName=St.displayName;const So=d.forwardRef(({className:s,children:t,position:a="popper",...n},r)=>e.jsx(cn,{children:e.jsxs(Ct,{ref:r,className:x("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",s),position:a,...n,children:[e.jsx(Es,{}),e.jsx(dn,{className:x("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(As,{})]})}));So.displayName=Ct.displayName;const Co=d.forwardRef(({className:s,...t},a)=>e.jsx(Tt,{ref:a,className:x("py-1.5 pl-8 pr-2 text-paragraph-sm font-semibold",s),...t}));Co.displayName=Tt.displayName;const To=d.forwardRef(({className:s,children:t,...a},n)=>e.jsxs(kt,{ref:n,className:x("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",s),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(un,{children:e.jsx(Rt,{className:"h-4 w-4"})})}),e.jsx(pn,{children:t})]}));To.displayName=kt.displayName;const ko=d.forwardRef(({className:s,...t},a)=>e.jsx(It,{ref:a,className:x("-mx-1 my-1 h-px bg-muted",s),...t}));ko.displayName=It.displayName;const Ms=d.forwardRef(({task:s,collapsible:t=!0,defaultExpanded:a=!1,onTaskClick:n,className:r,...i},o)=>{const[m,p]=d.useState(a),c=!!(s.details||s.files&&s.files.length>0),u={pending:_e,in_progress:Mn,completed:Et}[s.status],f=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},l=()=>{c&&t&&p(!m),n?.(s)};return e.jsxs("div",{ref:o,className:x("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",r),...i,children:[e.jsxs("button",{type:"button",onClick:l,className:x("w-full flex items-center gap-3 px-3 py-2.5 text-left",c&&t&&"cursor-pointer"),disabled:!c&&!t,children:[e.jsx(u,{className:x("w-4 h-4 shrink-0",f(),s.status==="in_progress"&&"animate-spin")}),e.jsx("span",{className:x("flex-1 text-paragraph-sm font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"font-medium"),children:s.text}),c&&t&&e.jsx(ue,{className:x("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",m&&"rotate-180"),"aria-hidden":"true"})]}),c&&m&&e.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[s.details&&e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-80 leading-relaxed mb-2",children:s.details}),s.files&&s.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:s.files.map(h=>e.jsx("div",{className:"text-caption font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:h},h))})]})]})]})});Ms.displayName="Subagent";const Io=d.forwardRef(({tasks:s,collapsible:t=!0,onTaskClick:a,emptyMessage:n="No subagents yet.",className:r,...i},o)=>e.jsx("div",{ref:o,className:x("space-y-2 max-h-96 overflow-y-auto",r),...i,children:s.length===0?e.jsx("p",{className:"text-paragraph-sm text-foreground opacity-60 italic py-4 text-center",children:n}):s.map(m=>e.jsx(Ms,{task:m,collapsible:t,...a?{onTaskClick:a}:{}},m.id))}));Io.displayName="SubagentList";const Ro=re("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"}}),Eo=d.forwardRef(({className:s,autoResize:t=!1,maxHeight:a=200,variant:n,...r},i)=>{const o=d.useRef(null),m=d.useCallback(c=>{o.current=c,typeof i=="function"?i(c):i&&(i.current=c)},[i]),p=d.useCallback(()=>{const c=o.current;if(!c||!t)return;c.style.height="auto";const u=Math.min(c.scrollHeight,a);c.style.height=`${u}px`,c.scrollHeight>a?c.style.overflowY="auto":c.style.overflowY="hidden"},[t,a]);return d.useEffect(()=>{p()},[p]),e.jsx("textarea",{className:x(Ro({variant:n}),t&&"overflow-y-hidden",s),ref:m,...r})});Eo.displayName="Textarea";function _s(){const{setTheme:s}=Is();return e.jsxs(fs,{children:[e.jsx(gs,{asChild:!0,children:e.jsxs(be,{children:[e.jsx(_n,{className:"size-4 text-muted-foreground rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Pn,{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(Fe,{align:"end",children:[e.jsx(oe,{onClick:()=>s("light"),children:"Light"}),e.jsx(oe,{onClick:()=>s("dark"),children:"Dark"}),e.jsx(oe,{onClick:()=>s("system"),children:"System"})]})]})}function Ao(){return"http://localhost:3100"}const st={agentServerUrl:Ao(),debuggerUrl:void 0};function Mo(){const{client:s,error:t,sessionId:a}=Gn({serverUrl:st.agentServerUrl});return e.jsx(vo,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:e.jsx(lo,{client:s,initialSessionId:a,error:t,...st.debuggerUrl})})}const Ps=document.getElementById("root");if(!Ps)throw new Error("Root element not found");$s.createRoot(Ps).render(e.jsx(Me.StrictMode,{children:e.jsx(Mo,{})}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as i,e,f as k}from"./vendor-
|
|
1
|
+
import{g as i,e,f as k}from"./vendor-C8TUcKlD.js";const c={};function d(s){const t=this,n=s||c,o=t.data(),r=o.micromarkExtensions||(o.micromarkExtensions=[]),a=o.fromMarkdownExtensions||(o.fromMarkdownExtensions=[]),m=o.toMarkdownExtensions||(o.toMarkdownExtensions=[]);r.push(i(n)),a.push(e()),m.push(k(n))}export{d as r};
|