@townco/gui-template 0.1.27 → 0.1.29
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-BiGbXeF1.js → acp-sdk-4ryhpmET.js} +1 -1
- package/dist/assets/{icons-B97fCJAR.js → icons-Cd_vS0Im.js} +1 -1
- package/dist/assets/index-BKwnhQCe.js +6 -0
- package/dist/assets/{markdown-DP5OEpQP.js → markdown-Bz1KRONC.js} +1 -1
- package/dist/assets/{radix-C1pEulHa.js → radix-R6uiGzM3.js} +1 -1
- package/dist/assets/{react-DWDN8s0r.js → react-CrKZJ-ak.js} +1 -1
- package/dist/assets/vendor-Ccy0WTO1.js +48 -0
- package/dist/index.html +7 -7
- package/package.json +4 -4
- package/src/App.tsx +8 -73
- package/dist/assets/index-EY7gwow8.js +0 -6
- package/dist/assets/vendor-BxtqxsLB.js +0 -48
- package/src/ChatView.tsx +0 -429
package/dist/index.html
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Agent Chat</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
-
<link rel="modulepreload" crossorigin href="/assets/vendor-
|
|
9
|
-
<link rel="modulepreload" crossorigin href="/assets/react-
|
|
10
|
-
<link rel="modulepreload" crossorigin href="/assets/acp-sdk-
|
|
11
|
-
<link rel="modulepreload" crossorigin href="/assets/radix-
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/assets/icons-
|
|
13
|
-
<link rel="modulepreload" crossorigin href="/assets/markdown-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-BKwnhQCe.js"></script>
|
|
8
|
+
<link rel="modulepreload" crossorigin href="/assets/vendor-Ccy0WTO1.js">
|
|
9
|
+
<link rel="modulepreload" crossorigin href="/assets/react-CrKZJ-ak.js">
|
|
10
|
+
<link rel="modulepreload" crossorigin href="/assets/acp-sdk-4ryhpmET.js">
|
|
11
|
+
<link rel="modulepreload" crossorigin href="/assets/radix-R6uiGzM3.js">
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/assets/icons-Cd_vS0Im.js">
|
|
13
|
+
<link rel="modulepreload" crossorigin href="/assets/markdown-Bz1KRONC.js">
|
|
14
14
|
<link rel="stylesheet" crossorigin href="/assets/index-DAh9842m.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@townco/gui-template",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.29",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -19,15 +19,15 @@
|
|
|
19
19
|
"check": "tsc --noEmit"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@townco/core": "0.0.
|
|
23
|
-
"@townco/ui": "0.1.
|
|
22
|
+
"@townco/core": "0.0.10",
|
|
23
|
+
"@townco/ui": "0.1.32",
|
|
24
24
|
"lucide-react": "^0.552.0",
|
|
25
25
|
"react": "^19.2.0",
|
|
26
26
|
"react-dom": "^19.2.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@tailwindcss/postcss": "^4.1.17",
|
|
30
|
-
"@townco/tsconfig": "0.1.
|
|
30
|
+
"@townco/tsconfig": "0.1.29",
|
|
31
31
|
"@types/react": "^19.2.2",
|
|
32
32
|
"@types/react-dom": "^19.2.2",
|
|
33
33
|
"@vitejs/plugin-react": "^5.1.0",
|
package/src/App.tsx
CHANGED
|
@@ -1,80 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { useEffect, useState } from "react";
|
|
4
|
-
import { ChatView } from "./ChatView.js";
|
|
1
|
+
import { useACPClient } from "@townco/ui";
|
|
2
|
+
import { ChatView } from "@townco/ui/gui";
|
|
5
3
|
import { config } from "./config.js";
|
|
6
4
|
|
|
7
|
-
const logger = createLogger("gui");
|
|
8
|
-
|
|
9
5
|
function App() {
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
useEffect(() => {
|
|
15
|
-
// Extract session ID from URL query parameter (?session=abc123)
|
|
16
|
-
const urlParams = new URLSearchParams(window.location.search);
|
|
17
|
-
const urlSessionId = urlParams.get("session");
|
|
18
|
-
|
|
19
|
-
if (urlSessionId) {
|
|
20
|
-
logger.info("Session ID found in URL", { sessionId: urlSessionId });
|
|
21
|
-
setSessionId(urlSessionId);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// Create AcpClient with HTTP transport
|
|
25
|
-
try {
|
|
26
|
-
logger.info("Initializing ACP client", {
|
|
27
|
-
serverUrl: config.agentServerUrl,
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
const acpClient = new AcpClient({
|
|
31
|
-
type: "http",
|
|
32
|
-
options: {
|
|
33
|
-
baseUrl: config.agentServerUrl,
|
|
34
|
-
},
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
setClient(acpClient);
|
|
38
|
-
logger.info("ACP client initialized successfully");
|
|
39
|
-
|
|
40
|
-
// Clean up on unmount
|
|
41
|
-
return () => {
|
|
42
|
-
logger.debug("Disconnecting ACP client");
|
|
43
|
-
acpClient.disconnect().catch((err) => {
|
|
44
|
-
logger.error("Failed to disconnect ACP client", {
|
|
45
|
-
error: err instanceof Error ? err.message : String(err),
|
|
46
|
-
});
|
|
47
|
-
});
|
|
48
|
-
};
|
|
49
|
-
} catch (err) {
|
|
50
|
-
const errorMessage =
|
|
51
|
-
err instanceof Error ? err.message : "Failed to initialize ACP client";
|
|
52
|
-
setError(errorMessage);
|
|
53
|
-
logger.error("Failed to initialize ACP client", {
|
|
54
|
-
error: err instanceof Error ? err.message : String(err),
|
|
55
|
-
stack: err instanceof Error ? err.stack : undefined,
|
|
56
|
-
});
|
|
57
|
-
return undefined;
|
|
58
|
-
}
|
|
59
|
-
}, []);
|
|
60
|
-
|
|
61
|
-
if (error) {
|
|
62
|
-
return (
|
|
63
|
-
<div className="flex items-center justify-center h-screen bg-background">
|
|
64
|
-
<div className="text-center p-8 max-w-md">
|
|
65
|
-
<h1 className="text-2xl font-bold text-destructive mb-4">
|
|
66
|
-
Initialization Error
|
|
67
|
-
</h1>
|
|
68
|
-
<p className="text-foreground mb-4">{error}</p>
|
|
69
|
-
<p className="text-sm text-muted-foreground">
|
|
70
|
-
Failed to initialize the ACP client. Check the console for details.
|
|
71
|
-
</p>
|
|
72
|
-
</div>
|
|
73
|
-
</div>
|
|
74
|
-
);
|
|
75
|
-
}
|
|
6
|
+
const { client, error, sessionId } = useACPClient({
|
|
7
|
+
serverUrl: config.agentServerUrl,
|
|
8
|
+
});
|
|
76
9
|
|
|
77
|
-
return
|
|
10
|
+
return (
|
|
11
|
+
<ChatView client={client} initialSessionId={sessionId} error={error} />
|
|
12
|
+
);
|
|
78
13
|
}
|
|
79
14
|
|
|
80
15
|
export default App;
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{r as i,j as t,P as os,e as rs,f as as,M as is,h as ls,a as cs}from"./react-DWDN8s0r.js";import{L as H,M as k,N as E,O as b,P as Ue,Q as D,R,S as L,T as z,U as ds,W as X,X as ne,Y as us,Z as ps,$ as fs,a0 as ms,a1 as W,a2 as gs,a3 as ve}from"./vendor-BxtqxsLB.js";import{P as Ne,a as hs}from"./acp-sdk-BiGbXeF1.js";import{S as J,L as Me,T as Ae,C as De,R as xs,O as _e,P as bs,a as Pe,b as ys,c as Le,D as ze,d as Fe,e as Oe,f as ws,g as He,I as $e,h as Be,i as We,j as Ve,k as qe,l as Qe,m as Ge,n as Ke,o as vs,p as Xe,q as Je,r as Ns,s as Ye,V as js,t as Ze,u as et,v as Ss,w as Cs,x as tt}from"./radix-C1pEulHa.js";import{C as st,S as Ts,P as ks,M as Is,A as Es,a as nt,F as ot,D as rt,L as at,X as Rs,b as it,c as lt,d as me,W as Us,e as ct,f as Ms,g as ge,h as As,i as Ds,j as dt,k as je,l as _s,m as Ps}from"./icons-B97fCJAR.js";import{r as Ls}from"./markdown-DP5OEpQP.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&o(d)}).observe(document,{childList:!0,subtree:!0});function n(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function o(a){if(a.ep)return;a.ep=!0;const l=n(a);fetch(a.href,l)}})();const ue=typeof process<"u"&&process.versions?.node;let zs,Fs=0;const Os=new Set;function Hs(s){for(const e of Os)e(s)}const Se={trace:0,debug:1,info:2,warn:3,error:4,fatal:5};class $s{service;minLevel;logFilePath;logsDir;writeQueue=[];isWriting=!1;constructor(e,n="debug"){this.service=e,this.minLevel=n,typeof process<"u"&&(this.minLevel="info")}setupFileLogging(){}async writeToFile(e){if(!(!this.logFilePath||!ue)&&(this.writeQueue.push(e),!this.isWriting)){for(this.isWriting=!0;this.writeQueue.length>0;){const o=`${this.writeQueue.splice(0,this.writeQueue.length).join(`
|
|
2
|
-
`)}
|
|
3
|
-
`;try{await require("node:fs").promises.appendFile(this.logFilePath,o,"utf-8")}catch{}}this.isWriting=!1}}shouldLog(e){return Se[e]>=Se[this.minLevel]}log(e,n,o){if(!this.shouldLog(e))return;const a={id:`log_${++Fs}`,timestamp:new Date().toISOString(),level:e,service:this.service,message:n,...o&&{metadata:o}};if(Hs(a),ue&&this.logFilePath,ue&&this.logFilePath){const l={timestamp:a.timestamp,level:a.level,service:a.service,message:a.message,...a.metadata&&{metadata:a.metadata}};this.writeToFile(JSON.stringify(l)).catch(()=>{})}}trace(e,n){this.log("trace",e,n)}debug(e,n){this.log("debug",e,n)}info(e,n){this.log("info",e,n)}warn(e,n){this.log("warn",e,n)}error(e,n){this.log("error",e,n)}fatal(e,n){this.log("fatal",e,n)}}function $(s,e="debug"){return new $s(s,e)}const ut=H(["pending","in_progress","completed","failed"]),Bs=H(["read","edit","delete","move","search","execute","think","fetch","switch_mode","other"]),pt=k({path:b(),line:E().nullable().optional()}),he=k({inputTokens:E().optional(),outputTokens:E().optional(),totalTokens:E().optional()}),ft=Ue("type",[k({type:D("content"),content:k({type:D("text"),text:b()})}),k({type:D("text"),text:b()}),k({type:D("diff"),path:b(),oldText:b(),newText:b(),line:E().nullable().optional()}),k({type:D("terminal"),terminalId:b()})]),mt=k({id:b(),title:b(),kind:Bs,status:ut,contentPosition:E().optional(),locations:R(pt).optional(),rawInput:L(b(),z()).optional(),rawOutput:L(b(),z()).optional(),content:R(ft).optional(),error:b().optional(),startedAt:E().optional(),completedAt:E().optional(),tokenUsage:he.optional()}),Ws=k({id:b(),status:ut.optional(),locations:R(pt).optional(),rawOutput:L(b(),z()).optional(),content:R(ft).optional(),error:b().optional(),completedAt:E().optional(),tokenUsage:he.optional()});function Ce(s,e){return{...s,status:e.status??s.status,locations:e.locations??s.locations,rawOutput:e.rawOutput??s.rawOutput,content:e.content?[...s.content??[],...e.content]:s.content,error:e.error??s.error,completedAt:e.completedAt??s.completedAt,tokenUsage:e.tokenUsage??s.tokenUsage}}const V=$("chat-store","debug"),C=ds(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},currentModel:"claude-sonnet-4-5-20250929",tokenDisplayMode:"context",logs:[],activeTab:"chat",input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:e=>s({connectionStatus:e}),setSessionId:e=>s({sessionId:e}),setError:e=>s({error:e}),addMessage:e=>s(n=>({messages:[...n.messages,e]})),updateMessage:(e,n)=>s(o=>{const a=o.messages.find(r=>r.id===e);let l=o.totalBilled,d=o.currentContext,p=n;if(n.tokenUsage){const r=a?.tokenUsage;V.debug("updateMessage: incoming tokenUsage",{incoming:n.tokenUsage,existing:r});const c={inputTokens:Math.max(n.tokenUsage.inputTokens??0,r?.inputTokens??0),outputTokens:Math.max(n.tokenUsage.outputTokens??0,r?.outputTokens??0),totalTokens:Math.max(n.tokenUsage.inputTokens??0,r?.inputTokens??0)+Math.max(n.tokenUsage.outputTokens??0,r?.outputTokens??0)};V.debug("updateMessage: merged tokenUsage",{merged:c}),p={...n,tokenUsage:c};const f=c.inputTokens-(r?.inputTokens??0),h=c.outputTokens-(r?.outputTokens??0),w=c.totalTokens-(r?.totalTokens??0);l={inputTokens:o.totalBilled.inputTokens+f,outputTokens:o.totalBilled.outputTokens+h,totalTokens:o.totalBilled.totalTokens+w},d={inputTokens:c.inputTokens,outputTokens:o.currentContext.outputTokens+h,totalTokens:c.totalTokens}}const u=o.messages.map(r=>r.id===e?{...r,...p}:r);if(n.tokenUsage&&p.tokenUsage){const r=a?.tokenUsage,c=p.tokenUsage,f=(c.inputTokens??0)-(r?.inputTokens??0),h=(c.outputTokens??0)-(r?.outputTokens??0),w=(c.totalTokens??0)-(r?.totalTokens??0),m=u.filter(y=>y.tokenUsage).map(y=>({id:y.id,role:y.role,tokens:y.tokenUsage})),x=u.reduce((y,N)=>({inputTokens:y.inputTokens+(N.tokenUsage?.inputTokens??0),outputTokens:y.outputTokens+(N.tokenUsage?.outputTokens??0),totalTokens:y.totalTokens+(N.tokenUsage?.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),v=x.inputTokens===l.inputTokens&&x.outputTokens===l.outputTokens&&x.totalTokens===l.totalTokens;V.debug("updateMessage: tokenUsage update",{messageId:e,updates:n.tokenUsage,existing:r,messageMax:c,delta:{inputDelta:f,outputDelta:h,totalDelta:w},totalBilled:l,currentContext:d,actualSum:x,billedCorrect:v?"✅":"❌",messageCount:u.length,messagesWithTokens:m.length,breakdown:m})}return{messages:u,totalBilled:l,currentContext:d}}),clearMessages:()=>s({messages:[]}),setIsStreaming:e=>s({isStreaming:e}),setStreamingStartTime:e=>s({streamingStartTime:e}),addToolCall:(e,n)=>s(o=>({toolCalls:{...o.toolCalls,[e]:[...o.toolCalls[e]||[],n]}})),addToolCallToCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(u=>u.role==="assistant");if(o===-1)return V.warn("No assistant message found to add tool call to"),n;const a=[...n.messages],l=a[o];if(!l)return n;const d=l.content.length,p={...e,contentPosition:d};return a[o]={...l,toolCalls:[...l.toolCalls||[],p]},{messages:a}}),updateToolCallInCurrentMessage:e=>s(n=>{const o=n.messages.findLastIndex(c=>c.role==="assistant");if(o===-1)return V.warn("No assistant message found to update tool call in"),n;const a=[...n.messages],l=a[o];if(!l)return n;const d=l.toolCalls||[],p=d.findIndex(c=>c.id===e.id);if(p===-1)return V.warn(`Tool call ${e.id} not found in message`),n;const u=d[p];if(!u)return n;const r=[...d];return r[p]=Ce(u,e),a[o]={...l,toolCalls:r},{messages:a}}),updateToolCall:(e,n)=>s(o=>{const a=o.toolCalls[e]||[],l=a.findIndex(u=>u.id===n.id);if(l===-1)return o;const d=a[l];if(!d)return o;const p=[...a];return p[l]=Ce(d,n),{toolCalls:{...o.toolCalls,[e]:p}}}),setInputValue:e=>s(n=>({input:{...n.input,value:e}})),setInputSubmitting:e=>s(n=>({input:{...n.input,isSubmitting:e}})),addFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,e]}})),removeFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((o,a)=>a!==e)}})),clearInput:()=>s(e=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}})),addTokenUsage:e=>s(n=>({totalBilled:{inputTokens:n.totalBilled.inputTokens+(e.inputTokens??0),outputTokens:n.totalBilled.outputTokens+(e.outputTokens??0),totalTokens:n.totalBilled.totalTokens+(e.totalTokens??0)},currentContext:{inputTokens:e.inputTokens??n.currentContext.inputTokens,outputTokens:n.currentContext.outputTokens+(e.outputTokens??0),totalTokens:(e.inputTokens??n.currentContext.inputTokens)+(n.currentContext.outputTokens+(e.outputTokens??0))}})),setCurrentModel:e=>s({currentModel:e}),resetTokens:()=>s({totalBilled:{inputTokens:0,outputTokens:0,totalTokens:0},currentContext:{inputTokens:0,outputTokens:0,totalTokens:0}}),cycleTokenDisplayMode:()=>s(e=>{const n=["context","input","output"],a=(n.indexOf(e.tokenDisplayMode)+1)%n.length,l=n[a];return l?{tokenDisplayMode:l}:e}),addLog:e=>s(n=>({logs:[...n.logs,e]})),clearLogs:()=>s({logs:[]}),setActiveTab:e=>s({activeTab:e})})),pe=$("use-chat-messages","debug");function gt(s){const e=C(c=>c.messages),n=C(c=>c.isStreaming),o=C(c=>c.sessionId),a=C(c=>c.setIsStreaming),l=C(c=>c.setStreamingStartTime),d=C(c=>c.addMessage),p=C(c=>c.updateMessage),u=C(c=>c.setError),r=i.useCallback(async c=>{if(!s){pe.error("No client available"),u("No client available");return}if(!o){pe.error("No active session"),u("No active session");return}try{const f=Date.now();a(!0),l(f);const h={id:`msg_${Date.now()}_user`,role:"user",content:c,timestamp:new Date().toISOString(),isStreaming:!1};d(h);const w=`msg_${Date.now()}_assistant`,m={id:w,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:f};d(m);const x=s.receiveMessages();s.sendMessage(c,o).catch(y=>{const N=y instanceof Error?y.message:String(y);u(N),a(!1),l(null)});let v="";for await(const y of x)if(y.tokenUsage&&pe.debug("chunk.tokenUsage",{tokenUsage:y.tokenUsage}),y.isComplete){p(w,{content:v,isStreaming:!1,streamingStartTime:void 0,...y.tokenUsage?{tokenUsage:y.tokenUsage}:{}}),a(!1),l(null);break}else y.contentDelta.type==="text"&&(v+=y.contentDelta.text,p(w,{content:v,...y.tokenUsage?{tokenUsage:y.tokenUsage}:{}}),await new Promise(N=>setTimeout(N,16)))}catch(f){const h=f instanceof Error?f.message:String(f);u(h),a(!1),l(null)}},[s,o,d,p,a,l,u]);return{messages:e,isStreaming:n,sendMessage:r}}const Vs=$("use-chat-input","debug");function qs(s){const e=C(f=>f.input),n=C(f=>f.setInputValue),o=C(f=>f.setInputSubmitting),a=C(f=>f.addFileAttachment),l=C(f=>f.removeFileAttachment),{sendMessage:d}=gt(s),p=i.useCallback(f=>{n(f)},[n]),u=i.useCallback(async()=>{if(!e.value.trim()||e.isSubmitting)return;const f=e.value;n(""),o(!0);try{await d(f)}catch(h){Vs.error("Failed to send message",{error:h instanceof Error?h.message:String(h)})}finally{o(!1)}},[e,n,o,d]),r=i.useCallback(f=>{a(f)},[a]),c=i.useCallback(f=>{l(f)},[l]);return{value:e.value,isSubmitting:e.isSubmitting,attachedFiles:e.attachedFiles,onChange:p,onSubmit:u,onAttachFile:r,onRemoveFile:c}}const q=$("use-chat-session","debug");function Qs(s,e){const n=C(m=>m.connectionStatus),o=C(m=>m.sessionId),a=C(m=>m.setConnectionStatus),l=C(m=>m.setSessionId),d=C(m=>m.setError),p=C(m=>m.clearMessages),u=C(m=>m.resetTokens),r=C(m=>m.addMessage);i.useEffect(()=>s?s.onSessionUpdate(x=>{if(x.message&&(q.debug("Session update with message",{message:x.message}),x.message.role!=="tool")){const v={id:x.message.id,role:x.message.role,content:x.message.content.map(y=>y.type==="text"?y.text:"").join(""),timestamp:x.message.timestamp,isStreaming:!1};r(v)}}):void 0,[s,r]);const c=i.useCallback(async()=>{if(!s){d("No client available");return}try{a("connecting"),d(null),await s.connect(),a("connected")}catch(m){q.error("Failed to connect",{error:m instanceof Error?m.message:String(m)});const x=m instanceof Error?m.message:String(m);d(x),a("error")}},[s,a,d]),f=i.useCallback(async m=>{if(!s){d("No client available");return}try{a("connecting"),d(null);const x=await s.loadSession(m);l(x),a("connected"),u(),q.info("Session loaded successfully",{sessionId:x})}catch(x){q.warn("Failed to load session, creating new one instead",{sessionId:m,error:x instanceof Error?x.message:String(x)});try{await c();const v=await s.startSession();if(l(v),p(),u(),typeof window<"u"){const y=new URL(window.location.href);y.searchParams.set("session",v),window.history.replaceState({},"",y.toString())}q.info("Created new session after failed load",{sessionId:v})}catch(v){const y=v instanceof Error?v.message:String(v);d(`Failed to load or create session: ${y}`),a("error")}}},[s,a,l,d,p,u,c]),h=i.useCallback(async()=>{if(!s){d("No client available");return}try{const m=await s.startSession();if(l(m),p(),u(),typeof window<"u"){const x=new URL(window.location.href);x.searchParams.set("session",m),window.history.pushState({},"",x.toString())}}catch(m){const x=m instanceof Error?m.message:String(m);d(x)}},[s,l,d,p,u]),w=i.useCallback(async()=>{if(s)try{await s.disconnect(),a("disconnected"),l(null)}catch(m){const x=m instanceof Error?m.message:String(m);d(x)}},[s,a,l,d]);return i.useEffect(()=>{!s||n!=="disconnected"||(e?(q.info("Loading initial session from URL",{sessionId:e}),f(e)):c())},[s,n,e,c,f]),i.useEffect(()=>{n==="connected"&&!o&&!e&&h()},[n,o,e,h]),{connectionStatus:n,sessionId:o,connect:c,loadSession:f,startSession:h,disconnect:w}}function Gs(s){const e=C(d=>d.toolCalls),n=C(d=>d.addToolCall),o=C(d=>d.updateToolCall),a=C(d=>d.addToolCallToCurrentMessage),l=C(d=>d.updateToolCallInCurrentMessage);return i.useEffect(()=>{if(!s)return;const d=s.onSessionUpdate(p=>{p.type==="tool_call"?(n(p.sessionId,p.toolCall),a(p.toolCall)):p.type==="tool_call_update"&&(o(p.sessionId,p.toolCallUpdate),l(p.toolCallUpdate))});return()=>{d()}},[s,n,o,a,l]),{toolCalls:e,getToolCallsForSession:d=>{const p=e[d];return p&&p.length>0?p:Object.values(e).flat()}}}const Ks=k({id:b(),role:H(["user","assistant","system"]),content:b(),timestamp:ne(),isStreaming:X().default(!1),streamingStartTime:E().optional(),metadata:L(b(),z()).optional(),toolCalls:R(mt).optional(),tokenUsage:he.optional()}),Xs=k({value:b(),isSubmitting:X(),attachedFiles:R(k({name:b(),path:b(),size:E(),mimeType:b()}))});k({sessionId:b().nullable(),isConnected:X(),isStreaming:X(),messages:R(Ks),input:Xs,error:b().nullable()});H(["disconnected","connecting","connected","error"]);const j=$("http-transport");class Js{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;constructor(e){this.options={...e,baseUrl:e.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const e={protocolVersion:Ne,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",e);j.info("ACP connection initialized",{initResponse:n});const o={cwd:"/",mcpServers:[]},a=await this.sendRpcRequest("session/new",o);this.currentSessionId=a.sessionId,j.info("Session created",{sessionId:this.currentSessionId}),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(e){this.connected=!1;const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async loadSession(e){this.connected&&(j.warn("Transport already connected, disconnecting first",{sessionId:e}),await this.disconnect());try{this.abortController=new AbortController;const n={protocolVersion:Ne,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}};j.info("Loading session - initializing connection",{sessionId:e});const o=await this.sendRpcRequest("initialize",n);if(!o.agentCapabilities?.loadSession)throw j.error("Agent does not support loading sessions",{capabilities:o.agentCapabilities}),new Error("Agent does not support loading sessions");j.info("ACP connection initialized, loading session",{sessionId:e,capabilities:o.agentCapabilities}),this.currentSessionId=e,await this.connectSSE();const a={sessionId:e,cwd:"/",mcpServers:[]};j.info("Sending session/load request",{loadRequest:a});const l=await this.sendRpcRequest("session/load",a);j.info("Session loaded successfully",{sessionId:this.currentSessionId,loadResponse:l}),this.connected=!0,this.reconnectAttempts=0}catch(n){this.connected=!1;const o=n instanceof Error?n:new Error(String(n));throw j.error("Failed to load session",{sessionId:e,error:o.message,stack:o.stack}),this.notifyError(o),o}}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(e){const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async send(e){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");try{this.streamComplete=!1,this.messageQueue=[];const n=e.content.filter(d=>d.type==="text").map(d=>d.text).join(`
|
|
4
|
-
`),o={sessionId:this.currentSessionId,prompt:[{type:"text",text:n}]},a=await this.sendRpcRequest("session/prompt",o);j.debug("Prompt sent",{promptResponse:a}),this.streamComplete=!0;const l=this.chunkResolvers.shift();l?l({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(n){this.streamComplete=!0;const o=n instanceof Error?n:new Error(String(n));throw this.notifyError(o),o}}async*receive(){this.isReceivingMessages=!0;try{for(;!this.streamComplete;)if(this.messageQueue.length>0){const e=this.messageQueue.shift();if(e&&(yield e,e.isComplete))return}else{const e=await new Promise(n=>{this.chunkResolvers.push(n)});if(e.isComplete){yield e;return}else yield e}for(;this.messageQueue.length>0;){const e=this.messageQueue.shift();e&&(yield e)}yield{id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}finally{this.isReceivingMessages=!1}}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}async sendRpcRequest(e,n){const a={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:n};j.debug("Sending RPC request",{method:e,params:n,request:a});const l={"Content-Type":"application/json",...this.options.headers},d=this.options.timeout??600*1e3,p=new AbortController,u=setTimeout(()=>p.abort(),d);try{const r=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:l,body:JSON.stringify(a),signal:p.signal});if(clearTimeout(u),!r.ok){const f=await r.text();throw new Error(`HTTP ${r.status}: ${f}`)}const c=await r.json();if(c.error)throw new Error(`ACP error: ${c.error.message||JSON.stringify(c.error)}`);return c.result||c}catch(r){throw clearTimeout(u),r instanceof Error&&r.name==="AbortError"?new Error(`Request timeout after ${d}ms`):r}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const e=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const o=await fetch(e,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!o.ok)throw new Error(`SSE connection failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response body is null");j.debug("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const a=o.body.getReader(),l=new TextDecoder;let d="";(async()=>{try{for(;;){const{done:p,value:u}=await a.read();if(p){j.debug("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}d+=l.decode(u,{stream:!0});const r=d.split(`
|
|
5
|
-
`);d=r.pop()||"";let c={event:"message",data:""};for(const f of r)f.startsWith("event:")?c.event=f.substring(6).trim():f.startsWith("data:")?c.data=f.substring(5).trim():f===""&&(c.event==="message"&&c.data&&this.handleSSEMessage(c.data),c={event:"message",data:""})}}catch(p){if(p instanceof Error&&p.name==="AbortError"){j.debug("SSE stream aborted");return}j.error("Error reading SSE stream",{error:p}),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(o){throw j.error("SSE connection error",{error:o}),o}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const n=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(n),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);j.debug("SSE reconnecting",{delay:e,attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),await new Promise(n=>setTimeout(n,e));try{await this.connectSSE(),j.info("SSE reconnected successfully"),this.reconnecting=!1}catch(n){j.error("SSE reconnection failed",{error:n}),this.reconnecting=!1}}handleSSEMessage(e){try{const n=JSON.parse(e);j.debug("Received SSE message",{message:n});const o=hs.safeParse(n);if(!o.success){j.error("Invalid ACP message from SSE",{issues:o.error.issues});return}const a=o.data;j.debug("Parsed ACP message",{method:"method"in a?a.method:"(no method)"}),"method"in a&&a.method==="session/update"&&(j.debug("Received session/update notification"),"params"in a&&a.params&&(j.debug("Calling handleSessionNotification",{params:a.params}),this.handleSessionNotification(a.params)))}catch(n){j.error("Error parsing SSE message",{error:n}),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(e){j.debug("handleSessionNotification called",{params:e});const o=e.update,a=this.currentSessionId||e.sessionId;if(j.debug("Update session type",{sessionUpdate:o?.sessionUpdate}),o?.sessionUpdate==="tool_call"){j.debug("Tool call notification",{tokenUsage:o.tokenUsage});const l=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,d={id:o.toolCallId??"",title:o.title??"",kind:o.kind||"other",status:o.status||"pending",locations:o.locations,rawInput:o.rawInput,tokenUsage:o.tokenUsage,content:o.content?.map(u=>{if(typeof u!="object"||u===null)return{type:"text",text:""};const r=u;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const c=r.content;if(c.type==="text")return{type:"content",content:{type:"text",text:typeof c.text=="string"?c.text:""}}}return r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:r.type==="diff"?{type:"diff",path:typeof r.path=="string"?r.path:"",oldText:typeof r.oldText=="string"?r.oldText:"",newText:typeof r.newText=="string"?r.newText:"",line:typeof r.line=="number"?r.line:null}:r.type==="terminal"?{type:"terminal",terminalId:typeof r.terminalId=="string"?r.terminalId:""}:{type:"text",text:""}}),startedAt:Date.now()},p={type:"tool_call",sessionId:a,status:"active",toolCall:d,messageId:l};this.notifySessionUpdate(p)}else if(o?.sessionUpdate==="tool_call_update"){const l=o._meta&&typeof o._meta=="object"&&"messageId"in o._meta?String(o._meta.messageId):void 0,d={id:o.toolCallId??"",status:o.status,locations:o.locations,rawOutput:o.rawOutput,tokenUsage:o.tokenUsage,content:o.content?.map(u=>{if(typeof u!="object"||u===null)return{type:"text",text:""};const r=u;if(r.type==="content"&&typeof r.content=="object"&&r.content!==null){const c=r.content;if(c.type==="text")return{type:"content",content:{type:"text",text:typeof c.text=="string"?c.text:""}}}return r.type==="text"?{type:"text",text:typeof r.text=="string"?r.text:""}:r.type==="diff"?{type:"diff",path:typeof r.path=="string"?r.path:"",oldText:typeof r.oldText=="string"?r.oldText:"",newText:typeof r.newText=="string"?r.newText:"",line:typeof r.line=="number"?r.line:null}:r.type==="terminal"?{type:"terminal",terminalId:typeof r.terminalId=="string"?r.terminalId:""}:{type:"text",text:""}}),error:o.error,completedAt:o.status==="completed"||o.status==="failed"?Date.now():void 0},p={type:"tool_call_update",sessionId:a,status:"active",toolCallUpdate:d,messageId:l};j.debug("Notifying tool_call_update session update",{sessionUpdate:p}),this.notifySessionUpdate(p)}else if(o&&"sessionUpdate"in o&&o.sessionUpdate==="tool_output"){const l=o,d=l._meta&&typeof l._meta=="object"&&"messageId"in l._meta?String(l._meta.messageId):void 0,p={id:l.toolCallId??"",rawOutput:l.rawOutput,content:l.content?.map(r=>{if(typeof r!="object"||r===null)return{type:"text",text:""};const c=r;if(c.type==="content"&&typeof c.content=="object"&&c.content!==null){const f=c.content;if(f.type==="text")return{type:"content",content:{type:"text",text:typeof f.text=="string"?f.text:""}}}return c.type==="text"?{type:"text",text:typeof c.text=="string"?c.text:""}:c.type==="diff"?{type:"diff",path:typeof c.path=="string"?c.path:"",oldText:typeof c.oldText=="string"?c.oldText:"",newText:typeof c.newText=="string"?c.newText:"",line:typeof c.line=="number"?c.line:null}:c.type==="terminal"?{type:"terminal",terminalId:typeof c.terminalId=="string"?c.terminalId:""}:{type:"text",text:""}})},u={type:"tool_call_update",sessionId:a,status:"active",toolCallUpdate:p,messageId:d};j.debug("Notifying tool_output as tool_call_update",{sessionUpdate:u}),this.notifySessionUpdate(u)}else if(o?.sessionUpdate==="agent_message_chunk"){const l={type:"generic",sessionId:a,status:"active"},d=o._meta&&typeof o._meta=="object"&&"tokenUsage"in o._meta?o._meta.tokenUsage:void 0;j.debug("Agent message chunk",{tokenUsage:d});const p=o.content;if(p&&typeof p=="object"){const u=p;let r=null;if(u.type==="text"&&typeof u.text=="string"&&(r={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:u.text},tokenUsage:d,isComplete:!1}),r){const c=this.chunkResolvers.shift();c?c(r):this.messageQueue.push(r)}if(r&&typeof u.text=="string"&&!this.isReceivingMessages){const c={type:"generic",sessionId:a,status:"active",message:{id:`msg_${Date.now()}_assistant`,role:"assistant",content:[{type:"text",text:u.text}],timestamp:new Date().toISOString()}};this.notifySessionUpdate(c)}}this.notifySessionUpdate(l)}else if(o?.sessionUpdate==="user_message_chunk"){j.debug("Received user_message_chunk",{update:o});const l=o.content;if(l&&typeof l=="object"){const d=l;if(d.type==="text"&&typeof d.text=="string"){const p={type:"generic",sessionId:a,status:"active",message:{id:`msg_${Date.now()}_user`,role:"user",content:[{type:"text",text:d.text}],timestamp:new Date().toISOString()}};j.debug("Notifying session update for user message"),this.notifySessionUpdate(p)}}}else{const l={type:"generic",sessionId:a,status:"active"};this.notifySessionUpdate(l)}}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(e){for(const n of this.sessionUpdateCallbacks)try{n(e)}catch(o){j.error("Error in session update callback",{error:o})}}notifyError(e){for(const n of this.errorCallbacks)try{n(e)}catch(o){j.error("Error in error callback",{error:o})}}}class Ys{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 Zs{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(e){}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(e){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(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}}const fe=$("acp-client","debug");class en{config;transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;constructor(e){this.config=e,this.transport=this.createTransport(),this.setupTransportListeners(),e.autoConnect&&this.connect().catch(n=>{fe.error("Failed to auto-connect",{error:n instanceof Error?n.message:String(n)})})}async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(e){const n="currentSessionId"in this.transport?this.transport.currentSessionId:void 0;if(n){const d=new Date().toISOString(),p={id:n,status:"connected",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:d}};return this.sessions.set(n,p),this.currentSessionId=n,n}const o=this.generateSessionId(),a=new Date().toISOString(),l={id:o,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:a}};return this.sessions.set(o,l),this.currentSessionId=o,this.updateSessionStatus(o,"connected"),o}async loadSession(e,n){if(!this.transport.loadSession)throw new Error("Transport does not support loading sessions");const o=new Date().toISOString(),a={id:e,status:"connecting",config:n?{...n,agentPath:n.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:o}};return this.sessions.set(e,a),this.currentSessionId=e,await this.transport.loadSession(e),this.updateSessionStatus(e,"connected"),e}async sendMessage(e,n){const o=n||this.currentSessionId;if(!o)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(o);if(!a)throw new Error(`Session ${o} not found`);const l={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};a.messages.push(l),this.updateSessionStatus(o,"active"),await this.transport.send(l)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(e){return this.sessions.get(e)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(e){return this.sessionUpdateHandlers.add(e),()=>{this.sessionUpdateHandlers.delete(e)}}onError(e){return this.errorHandlers.add(e),()=>{this.errorHandlers.delete(e)}}createTransport(){switch(this.config.type){case"stdio":return new Ys(this.config.options);case"http":return new Js(this.config.options);case"websocket":return new Zs(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(e=>{this.handleSessionUpdate(e)}),this.transport.onError(e=>{this.handleError(e)})}handleSessionUpdate(e){if(e.sessionId){const n=this.sessions.get(e.sessionId);n&&(e.status&&(n.status=e.status),e.message&&n.messages.push(e.message),e.error&&(n.error=e.error))}for(const n of this.sessionUpdateHandlers)try{n(e)}catch(o){fe.error("Error in session update handler",{error:o instanceof Error?o.message:String(o)})}}handleError(e){for(const n of this.errorHandlers)try{n(e)}catch(o){fe.error("Error in error handler",{error:o instanceof Error?o.message:String(o)})}}updateSessionStatus(e,n){const o=this.sessions.get(e);o&&(o.status=n,this.handleSessionUpdate({sessionId:e,status:n}))}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 tn=k({name:b(),description:b().optional(),parameters:L(b(),z()).optional()}),sn=k({name:b(),description:b(),parameters:L(b(),z()),required:R(b()).optional()}),nn=k({name:b(),version:b().optional(),description:b().optional(),author:b().optional(),capabilities:R(tn).optional(),tools:R(sn).optional(),supportedFormats:R(b()).optional()}),on=H(["initializing","ready","busy","error","terminated"]);k({status:on,info:nn.optional(),pid:E().optional(),error:b().optional(),uptime:E().optional()});const ht=H(["user","assistant","system","tool"]),rn=H(["text","image","file","tool_call","tool_result"]),Y=k({type:rn}),an=Y.extend({type:D("text"),text:b()}),ln=Y.extend({type:D("image"),url:b().url().optional(),data:b().optional(),mimeType:b().optional()}),cn=Y.extend({type:D("file"),name:b(),path:b().optional(),url:b().url().optional(),mimeType:b(),size:E().optional()}),dn=Y.extend({type:D("tool_call"),id:b(),name:b(),arguments:L(b(),z())}),un=Y.extend({type:D("tool_result"),callId:b(),result:z(),error:b().optional()}),xt=Ue("type",[an,ln,cn,dn,un]),bt=k({id:b(),role:ht,content:R(xt),timestamp:ne(),metadata:L(b(),z()).optional()});k({id:b(),role:ht,contentDelta:xt,isComplete:X(),tokenUsage:k({inputTokens:E().optional(),outputTokens:E().optional(),totalTokens:E().optional()}).optional()});const yt=H(["idle","connecting","connected","active","streaming","error","disconnected"]),pn=k({agentPath:b(),agentArgs:R(b()).optional(),environment:L(b(),b()).optional(),workingDirectory:b().optional(),timeout:E().optional()}),fn=k({agentName:b().optional(),agentVersion:b().optional(),capabilities:R(b()).optional(),startedAt:ne(),lastActivityAt:ne().optional()});k({id:b(),status:yt,config:pn,metadata:fn.optional(),messages:R(bt),error:b().optional()});const oe=k({sessionId:b(),status:yt.optional(),message:bt.optional(),error:b().optional()}),mn=oe.extend({type:D("tool_call"),toolCall:mt,messageId:b().optional()}),gn=oe.extend({type:D("tool_call_update"),toolCallUpdate:Ws,messageId:b().optional()}),hn=oe.extend({type:D("tool_output"),toolOutput:k({id:b(),content:R(us()).optional(),rawOutput:L(b(),z()).optional()}),messageId:b().optional()}),xn=oe.extend({type:D("generic").optional()});ps([mn,gn,hn,xn]);function g(...s){return fs(ms(s))}const bn=W("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-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"}}),Z=i.forwardRef(({className:s,variant:e,size:n,asChild:o=!1,...a},l)=>{const d=o?J:"button";return t.jsx(d,{className:g(bn({variant:e,size:n,className:s})),ref:l,...a})});Z.displayName="Button";const yn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));yn.displayName="Card";const wn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex flex-col space-y-1.5 p-6",s),...e}));wn.displayName="CardHeader";const vn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-2xl font-semibold leading-none tracking-tight",s),...e}));vn.displayName="CardTitle";const Nn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("text-sm text-muted-foreground",s),...e}));Nn.displayName="CardDescription";const jn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("p-6 pt-0",s),...e}));jn.displayName="CardContent";const Sn=i.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:g("flex items-center p-6 pt-0",s),...e}));Sn.displayName="CardFooter";const wt=i.forwardRef(({title:s,description:e,guideUrl:n,guideText:o="Guide",suggestedPrompts:a=[],onPromptClick:l,onGuideClick:d,className:p,...u},r)=>{const c=w=>{l?.(w)},f=()=>{n&&window.open(n,"_blank","noopener,noreferrer"),d?.()},h=[];for(let w=0;w<a.length;w+=2)h.push(a.slice(w,w+2));return t.jsxs("div",{ref:r,className:g("flex flex-col items-start gap-6",p),...u,children:[t.jsx("h3",{className:"text-heading-3 text-text-primary hidden lg:block",children:s}),t.jsx("p",{className:"text-subheading text-text-secondary max-w-prose",children:e}),(n||d)&&t.jsxs("button",{type:"button",onClick:f,className:"flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-accent transition-colors",children:[t.jsx("span",{className:"text-sm font-medium leading-normal text-text-primary",children:o}),t.jsx(st,{className:"size-4 text-text-primary"})]}),a.length>0&&t.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-prompt-container",children:[t.jsx("p",{className:"text-label text-text-tertiary",children:"Suggested Prompts"}),t.jsx("div",{className:"flex flex-col gap-2.5",children:h.map(w=>t.jsx("div",{className:"flex gap-2.5 items-center",children:w.map(m=>t.jsx("button",{type:"button",onClick:()=>c(m),className:"flex-1 flex items-start gap-2 p-3 bg-secondary hover:bg-secondary/80 rounded-2xl transition-colors min-w-0",children:t.jsx("span",{className:"text-base font-normal leading-normal text-text-tertiary truncate",children:m})},m))},w.join("-")))})]})]})});wt.displayName="ChatEmptyState";const vt=i.createContext(void 0),xe=()=>{const s=i.useContext(vt);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},Nt=i.forwardRef(({defaultExpanded:s=!1,expanded:e,onExpandedChange:n,className:o,children:a,...l},d)=>{const[p,u]=i.useState(s),r=e??p,c=i.useCallback(m=>{u(m),n?.(m)},[n]),f=i.Children.toArray(a),h=f.find(m=>i.isValidElement(m)&&typeof m.type=="function"&&m.type.displayName==="ChatHeader.ExpandablePanel"),w=f.filter(m=>m!==h);return t.jsxs(vt.Provider,{value:{isExpanded:r,setIsExpanded:c},children:[t.jsx("div",{ref:d,className:g("flex items-center justify-between px-6 py-4",o),...l,children:w}),h]})});Nt.displayName="ChatHeader.Root";const Cn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("h1",{ref:o,className:g("m-0 text-xl font-semibold",s),...n,children:e}));Cn.displayName="ChatHeader.Title";const Tn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center gap-3",s),...n,children:e}));Tn.displayName="ChatHeader.Actions";const kn=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"}},In=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},En=i.forwardRef(({status:s,statusText:e,className:n,...o},a)=>{const l=e??In(s),d=kn(s);return t.jsxs("div",{ref:a,className:g("flex items-center gap-2",n),...o,children:[t.jsx("div",{className:g("h-2 w-2 rounded-full",d)}),t.jsx("span",{className:"text-sm text-muted-foreground",children:l})]})});En.displayName="ChatHeader.StatusIndicator";const Rn=i.forwardRef(({icon:s,className:e,children:n,onClick:o,...a},l)=>{const{isExpanded:d,setIsExpanded:p}=xe(),u=r=>{p(!d),o?.(r)};return t.jsxs("button",{ref:l,type:"button",onClick:u,className:g("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":d?"Collapse header":"Expand header",...a,children:[s&&t.jsx("div",{className:g("transition-transform duration-200",d&&"rotate-180"),children:s}),n]})});Rn.displayName="ChatHeader.Toggle";const jt=i.forwardRef(({className:s,children:e,...n},o)=>{const{isExpanded:a}=xe();return a?t.jsx("div",{ref:o,className:g("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",s),...n,children:e}):null});jt.displayName="ChatHeader.ExpandablePanel";const St=i.forwardRef(({commands:s=[],showCommandMenu:e,commandMenuQuery:n,selectedMenuIndex:o,setSelectedMenuIndex:a,setMenuItemCount:l,triggerCounter:d,onChange:p,className:u,...r},c)=>{const f=i.useCallback((w,m)=>{const x=w.toLowerCase(),v=m.toLowerCase();if(!m)return 1;if(x.includes(v))return 1-v.length/x.length;let y=0;for(let N=0;N<x.length&&y<v.length;N++)x[N]===v[y]&&y++;return y===v.length?.5-y/x.length:0},[]),h=i.useMemo(()=>s.map(w=>({...w,score:Math.max(f(w.label,n),w.description?f(w.description,n):0)})).filter(w=>w.score>0).sort((w,m)=>m.score-w.score),[s,n,f]);return i.useEffect(()=>{l(h.length)},[h.length,l]),i.useEffect(()=>{a(0)},[a]),i.useEffect(()=>{d>0&&h[o]&&(h[o].onSelect(),p(""))},[d,h,o,p]),!e||h.length===0?null:t.jsxs("div",{ref:c,className:g("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",u),...r,children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),t.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map((w,m)=>t.jsxs("button",{type:"button",onClick:()=>w.onSelect(),className:g("w-full rounded-sm px-2 py-2 text-left text-sm transition-colors","flex items-start gap-2","hover:bg-muted",m===o&&"bg-muted"),children:[w.icon&&t.jsx("span",{className:"shrink-0 mt-0.5",children:w.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-medium",children:w.label}),w.description&&t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:w.description})]})]},w.id))})]})});St.displayName="ChatInputCommandMenu";const Ct=i.createContext(void 0),re=()=>{const s=i.useContext(Ct);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},Tt=i.forwardRef(({client:s,value:e,onChange:n,onSubmit:o,disabled:a=!1,isSubmitting:l,submitOnEnter:d=!0,className:p,children:u,...r},c)=>{const f=i.useRef(null),h=qs(s??null),w=C(M=>M.isStreaming),m=h?h.value:e||"",x=h?h.onChange:n||(()=>{}),v=h?h.onSubmit:o||(async()=>{}),y=h?h.isSubmitting||w:l||!1,[N,T]=i.useState(!1),[U,I]=i.useState(""),[A,S]=i.useState(0),[_,F]=i.useState(0),[ce,de]=i.useState(0),Zt=i.useCallback(()=>{de(M=>M+1)},[]),es=async M=>{M.preventDefault(),m.trim()&&!y&&!a&&(await v(),setTimeout(()=>{f.current?.focus()},0))},ts=M=>{const O=M.target;!(O.tagName==="BUTTON"||O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.closest("button"))&&f.current&&f.current.focus()},ss=M=>{const O=M.target;!(O.tagName==="BUTTON"||O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.closest("button"))&&M.key===" "&&(M.preventDefault(),f.current&&f.current.focus())};return i.useEffect(()=>{const M=document.querySelector('textarea[name="chat-input"]');M&&f.current!==M&&(f.current=M)},[]),i.useEffect(()=>{!m&&f.current&&(f.current.style.height="auto",f.current.style.overflowY="hidden")},[m]),t.jsx(Ct.Provider,{value:{value:m,onChange:x,onSubmit:v,disabled:a,isSubmitting:y,submitOnEnter:d,showCommandMenu:N,setShowCommandMenu:T,commandMenuQuery:U,setCommandMenuQuery:I,selectedMenuIndex:A,setSelectedMenuIndex:S,menuItemCount:_,setMenuItemCount:F,triggerMenuSelect:Zt,triggerCounter:ce},children:t.jsx("form",{ref:c,onSubmit:es,onClick:ts,onKeyDown:ss,className:g("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...r,children:u})})});Tt.displayName="ChatInput.Root";const kt=i.forwardRef(({asChild:s=!1,className:e,onKeyDown:n,children:o,...a},l)=>{const{value:d,onChange:p,onSubmit:u,disabled:r,isSubmitting:c,submitOnEnter:f,showCommandMenu:h,setShowCommandMenu:w,setCommandMenuQuery:m,setSelectedMenuIndex:x,menuItemCount:v,triggerMenuSelect:y}=re(),N=i.useRef(null),A={ref:i.useCallback(S=>{N.current=S,typeof l=="function"?l(S):l&&(l.current=S)},[l]),name:"chat-input",value:d,onChange:S=>{const _=S.target.value;if(p(_),_.startsWith("/")&&!_.includes(`
|
|
6
|
-
`)){w(!0);const de=_.slice(1);m(de)}else w(!1),m("");const F=N.current;if(!F)return;F.style.height="auto";const ce=Math.min(F.scrollHeight,164);F.style.height=`${ce}px`,F.scrollHeight>164?F.style.overflowY="auto":F.style.overflowY="hidden"},onKeyDown:S=>{if(h&&v>0){if(S.key==="ArrowDown"){S.preventDefault(),x(_=>(_+1)%v);return}else if(S.key==="ArrowUp"){S.preventDefault(),x(_=>(_-1+v)%v);return}else if(S.key==="Enter"&&!S.shiftKey){S.preventDefault(),y();return}else if(S.key==="Escape"){S.preventDefault(),w(!1),m("");return}}f&&S.key==="Enter"&&!S.shiftKey&&(d.trim()&&!c&&!r?(S.preventDefault(),u()):(c||r)&&S.preventDefault()),n?.(S)},disabled:r,...a};return s&&i.isValidElement(o)?i.cloneElement(o,A):t.jsx("textarea",{...A,className:g("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 field-sizing-content max-h-[6lh]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});kt.displayName="ChatInput.Field";const It=i.forwardRef(({asChild:s=!1,className:e,disabled:n,children:o,...a},l)=>{const{value:d,disabled:p,isSubmitting:u}=re(),r=n||p||u||!d.trim(),c=s?J:Z;return t.jsx(c,{ref:l,type:"submit",disabled:r,variant:s?void 0:"default",size:"icon",className:g(!s&&"gap-1.5 rounded-full",e),...a,children:o})});It.displayName="ChatInput.Submit";const Et=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center justify-between p-2",s),...n,children:e}));Et.displayName="ChatInput.Toolbar";const Rt=i.forwardRef(({asChild:s=!1,className:e,children:n,onClick:o,...a},l)=>{const{value:d,onChange:p,setShowCommandMenu:u,setCommandMenuQuery:r}=re(),c=h=>{d.startsWith("/")||(p("/"),u(!0),r("")),o?.(h)},f=s?J:Z;return t.jsx(f,{ref:l,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),onClick:c,...a,children:n||t.jsx(Ts,{className:"size-4"})})});Rt.displayName="ChatInput.Actions";const Ut=i.forwardRef(({asChild:s=!1,className:e,children:n,...o},a)=>{const l=s?J:Z;return t.jsx(l,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(ks,{className:"size-4"})})});Ut.displayName="ChatInput.Attachment";const Mt=i.forwardRef(({asChild:s=!1,className:e,children:n,...o},a)=>{const l=s?J:Z;return t.jsx(l,{ref:a,type:"button",variant:"ghost",size:"icon",className:g("rounded-full",e),...o,children:n||t.jsx(Is,{className:"size-4"})})});Mt.displayName="ChatInput.VoiceInput";const At=i.forwardRef(({commands:s=[],className:e,onChange:n,...o},a)=>{const{showCommandMenu:l,commandMenuQuery:d,selectedMenuIndex:p,setSelectedMenuIndex:u,setMenuItemCount:r,triggerCounter:c,onChange:f}=re();return t.jsx(St,{ref:a,commands:s,showCommandMenu:l,commandMenuQuery:d,selectedMenuIndex:p,setSelectedMenuIndex:u,setMenuItemCount:r,triggerCounter:c,onChange:f,className:e,...o})});At.displayName="ChatInput.CommandMenu";const Un=({className:s,...e})=>t.jsx(os,{className:g("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",s),...e}),Dt=({className:s,...e})=>t.jsx(rs,{className:g(s),...e}),Mn=({withHandle:s,className:e,...n})=>t.jsx(as,{className:g("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",e),...n,children:s&&t.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:t.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:[t.jsx("title",{children:"Resize Handle"}),t.jsx("circle",{cx:"9",cy:"12",r:"1"}),t.jsx("circle",{cx:"9",cy:"5",r:"1"}),t.jsx("circle",{cx:"9",cy:"19",r:"1"}),t.jsx("circle",{cx:"15",cy:"12",r:"1"}),t.jsx("circle",{cx:"15",cy:"5",r:"1"}),t.jsx("circle",{cx:"15",cy:"19",r:"1"})]})})}),An=({...s})=>t.jsx(gs,{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}),_t=i.createContext(void 0),be=()=>{const s=i.useContext(_t);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},Pt=i.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:e="hidden",defaultActiveTab:n="todo",className:o,children:a,...l},d)=>{const[p,u]=i.useState(s),[r,c]=i.useState(e),[f,h]=i.useState(n);return t.jsx(_t.Provider,{value:{sidebarOpen:p,setSidebarOpen:u,panelSize:r,setPanelSize:c,activeTab:f,setActiveTab:h},children:t.jsx("div",{ref:d,className:g("flex h-screen flex-row bg-background text-foreground",o),...l,children:t.jsx(Un,{direction:"horizontal",className:"flex-1",children:a})})})});Pt.displayName="ChatLayout.Root";const Dn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("relative z-10 border-b border-border bg-card shrink-0",s),...n,children:e}));Dn.displayName="ChatLayout.Header";const Lt=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx(Dt,{defaultSize:75,minSize:50,children:t.jsx("div",{ref:o,className:g("flex flex-1 flex-col overflow-hidden h-full",s),...n,children:e})}));Lt.displayName="ChatLayout.Main";const zt=i.forwardRef(({showToaster:s=!0,className:e,children:n,...o},a)=>t.jsxs("div",{ref:a,className:g("relative flex flex-1 flex-col overflow-hidden",e),...o,children:[n,s&&t.jsx(An,{})]}));zt.displayName="ChatLayout.Body";const Ft=i.forwardRef(({className:s,children:e,onScrollChange:n,showScrollToBottom:o=!0,...a},l)=>{const[d,p]=i.useState(!1),u=i.useRef(null);i.useImperativeHandle(l,()=>u.current);const r=i.useCallback(()=>{const h=u.current;if(!h)return;const{scrollTop:w,scrollHeight:m,clientHeight:x}=h,y=m-w-x<100;p(!y&&o),n?.(y)},[n,o]),c=i.useCallback(()=>{r()},[r]),f=i.useCallback(()=>{const h=u.current;h&&h.scrollTo({top:h.scrollHeight,behavior:"smooth"})},[]);return i.useEffect(()=>{r()},[r]),t.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[t.jsx("div",{ref:u,className:g("h-full overflow-y-auto",s),onScroll:c,...a,children:t.jsx("div",{className:"mx-auto max-w-chat min-h-full flex flex-col",children:e})}),d&&t.jsx("button",{type:"button",onClick:f,className:g("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:t.jsx(Es,{className:"size-4"})})]})});Ft.displayName="ChatLayout.Messages";const Ot=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("bg-linear-to-t from-background to-transparent px-4 pb-4",s),...n,children:t.jsx("div",{className:"mx-auto max-w-chat",children:e})}));Ot.displayName="ChatLayout.Footer";const _n=i.forwardRef(({className:s,children:e,...n},o)=>{const{sidebarOpen:a}=be();return a?t.jsx("div",{ref:o,className:g("border-r border-border bg-card w-64 overflow-y-auto",s),...n,children:e}):null});_n.displayName="ChatLayout.Sidebar";const Ht=i.forwardRef(({breakpoint:s="lg",className:e,children:n,...o},a)=>{const{panelSize:l}=be();return l==="hidden"?null:t.jsxs(t.Fragment,{children:[t.jsx(Mn,{withHandle:!0}),t.jsx(Dt,{defaultSize:25,minSize:15,maxSize:50,children:t.jsx("div",{ref:a,className:g("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",e),...o,children:n})})]})});Ht.displayName="ChatLayout.Aside";const $t=i.forwardRef(({source:s,isSelected:e,className:n,...o},a)=>t.jsxs("button",{ref:a,type:"button",className:g("flex w-full text-left gap-2 items-start p-3 rounded-lg transition-colors cursor-pointer border border-transparent","hover:bg-accent-hover hover:border-border/50",e&&"bg-accent-hover border-border/50",n),onClick:()=>window.open(s.url,"_blank"),...o,children:[t.jsx("div",{className:"flex gap-2 items-center py-[2px] shrink-0",children:t.jsx("div",{className:"relative rounded-[3px] shrink-0 size-4 overflow-hidden bg-muted",children:s.favicon?t.jsx("img",{alt:s.sourceName,className:"size-full object-cover",src:s.favicon}):t.jsx("div",{className:"size-full bg-muted"})})}),t.jsxs("div",{className:"flex flex-1 flex-col gap-1 min-w-0",children:[t.jsxs("div",{className:"text-xs leading-normal text-foreground",children:[t.jsx("span",{className:"font-medium",children:s.sourceName}),t.jsxs("span",{className:"text-muted-foreground",children:[" · ",s.title]})]}),t.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground line-clamp-3",children:s.snippet})]})]}));$t.displayName="SourceListItem";const ae=i.forwardRef(({todos:s,className:e,...n},o)=>t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No todos yet"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a.text},a.id))}));ae.displayName="TodoTabContent";const ie=i.forwardRef(({files:s=[],className:e,...n},o)=>t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No files attached"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a},a))}));ie.displayName="FilesTabContent";const le=i.forwardRef(({sources:s=[],className:e,...n},o)=>t.jsx("div",{ref:o,className:g("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No sources available"})}):s.map(a=>t.jsx($t,{source:a},a.id))}));le.displayName="SourcesTabContent";const Pn=i.forwardRef(({data:s,className:e,...n},o)=>t.jsxs("div",{ref:o,className:g("space-y-4",e),...n,children:[t.jsx("h3",{className:"font-semibold text-lg",children:"Database"}),t.jsxs("div",{className:"text-sm text-muted-foreground",children:[t.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),t.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[t.jsx("p",{children:"Your large data table would go here"}),s&&typeof s=="object"?t.jsx("pre",{className:"mt-2 text-xs overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));Pn.displayName="DatabaseTabContent";const ye=xs,G=i.forwardRef(({className:s,...e},n)=>t.jsx(Me,{ref:n,className:g("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...e}));G.displayName=Me.displayName;const K=i.forwardRef(({className:s,...e},n)=>t.jsx(Ae,{ref:n,className:g("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-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),...e}));K.displayName=Ae.displayName;const P=i.forwardRef(({className:s,...e},n)=>t.jsx(De,{ref:n,className:g("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...e}));P.displayName=De.displayName;const Bt=i.forwardRef(({todo:s,className:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex items-center gap-3 px-3 py-2 rounded-lg",e),...n,children:t.jsx("span",{className:g("flex-1 text-[var(--font-size)] font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"shimmer-animation"),children:s.text})}));Bt.displayName="TodoListItem";const Wt=i.forwardRef(({client:s,todos:e,className:n,...o},a)=>{const l=e||[];return t.jsx("div",{ref:a,className:g("space-y-2 max-h-64 overflow-y-auto",n),...o,children:l.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic",children:"No tasks yet."}):l.map(d=>t.jsx(Bt,{todo:d},d.id))})});Wt.displayName="TodoList";const Ln=i.forwardRef(({client:s,todos:e,variant:n="animated",showIcons:o=!1,visibleTabs:a=["todo","files","database"],className:l,...d},p)=>{const u=e||[],[r,c]=i.useState(a[0]||"todo"),f=i.useRef(null),h=i.useRef(null);i.useEffect(()=>{const v=setTimeout(()=>{const y=f.current;if(r&&y){const N=h.current;if(N){const T=y.getBoundingClientRect(),U=N.getBoundingClientRect(),I=U.left-T.left,A=U.width,S=I/T.width*100,_=100-(I+A)/T.width*100;y.style.clipPath=`inset(0 ${_.toFixed(2)}% 0 ${S.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(v)},[r]);const m=[{id:"todo",label:n==="pills"?"To-do":"To-Do List",icon:nt},{id:"files",label:"Files",icon:ot},{id:"database",label:"Database",icon:rt},{id:"sources",label:"Sources",icon:at}].filter(x=>a.includes(x.id));return t.jsx("div",{ref:p,className:g("select-none",l),...d,children:t.jsxs(ye,{value:r,onValueChange:c,className:"w-full",children:[n==="pills"?t.jsx(G,{className:g("w-full justify-start bg-transparent p-0 h-auto","gap-1"),children:m.map(x=>{const v=x.icon;return t.jsxs(K,{value:x.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[o&&v&&t.jsx(v,{className:"size-4"}),x.label]},x.id)})}):t.jsxs("div",{className:"relative mb-4 border-border",children:[t.jsx(G,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:m.map(x=>t.jsx(K,{value:x.id,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:x.label},x.id))}),t.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:t.jsx(G,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:m.map(x=>t.jsx(K,{value:x.id,ref:r===x.id?h:null,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:x.label},x.id))})})]}),t.jsx(P,{value:"todo",className:n==="pills"?"mt-0":"",children:n==="pills"?t.jsx(ae,{todos:u}):t.jsx(Wt,{todos:u})}),t.jsx(P,{value:"files",className:n==="pills"?"mt-0":"",children:t.jsx(ie,{})}),t.jsx(P,{value:"database",className:n==="pills"?"mt-0":"",children:t.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})}),t.jsx(P,{value:"sources",className:n==="pills"?"mt-0":"",children:t.jsx(le,{})})]})})});Ln.displayName="ChatSecondaryPanel";const zn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex h-full flex-col",s),...n,children:e}));zn.displayName="ChatSidebar.Root";const Fn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("border-b border-border px-4 py-3",s),...n,children:e}));Fn.displayName="ChatSidebar.Header";const On=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("flex-1 overflow-y-auto p-4",s),...n,children:e}));On.displayName="ChatSidebar.Content";const Hn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsx("div",{ref:o,className:g("border-t border-border px-4 py-3",s),...n,children:e}));Hn.displayName="ChatSidebar.Footer";const $n=i.forwardRef(({children:s,className:e,...n},o)=>{const[a,l]=i.useState(s),[d,p]=i.useState(!1),u=i.useRef(s),r=i.useRef(!0);return i.useEffect(()=>{if(r.current){r.current=!1,u.current=s;return}if(u.current===s)return;p(!0);const c=setTimeout(()=>{l(s),u.current=s,requestAnimationFrame(()=>{p(!1)})},150);return()=>{clearTimeout(c)}},[s]),t.jsx("span",{ref:o,className:g("text-sm text-foreground opacity-60 transition-opacity duration-300",d?"opacity-0":"opacity-60",e),...n,children:a})});$n.displayName="ChatStatus";const Bn=i.forwardRef(({autoScroll:s=!0,isStreaming:e=!1,scrollBehavior:n="smooth",scrollThreshold:o=100,showScrollButton:a=!0,scrollButton:l,className:d,children:p,...u},r)=>{const c=i.useRef(null),[f,h]=i.useState(!0),[w,m]=i.useState(!1),x=i.useRef(0);i.useImperativeHandle(r,()=>{if(!c.current)throw new Error("Container ref not initialized");return c.current});const v=i.useCallback(()=>{const N=c.current;if(!N)return;const{scrollTop:T,scrollHeight:U,clientHeight:I}=N,S=U-T-I<o;h(S),m(!S&&a),x.current=T},[o,a]),y=i.useCallback((N=n)=>{const T=c.current;T&&T.scrollTo({top:T.scrollHeight,behavior:N})},[n]);return i.useEffect(()=>{!s||!c.current||(e&&f?y("auto"):!e&&f&&y())},[s,e,f,y]),i.useEffect(()=>{const N=c.current;if(!N)return;const T=()=>{v()};return N.addEventListener("scroll",T,{passive:!0}),v(),()=>{N.removeEventListener("scroll",T)}},[v]),i.useEffect(()=>{const N=c.current;if(!N)return;const T=new ResizeObserver(()=>{f&&s&&y("auto")});return T.observe(N),()=>{T.disconnect()}},[f,s,y]),t.jsxs("div",{className:"relative flex-1",children:[t.jsx("div",{ref:c,className:g("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",d),...u,children:t.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:p})}),w&&t.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:l||t.jsxs("button",{type:"button",onClick:()=>y(),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:[t.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:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})}),"Scroll to bottom"]})})]})});Bn.displayName="Conversation";const Wn=bs,Vt=i.forwardRef(({className:s,...e},n)=>t.jsx(_e,{ref:n,className:g("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),...e}));Vt.displayName=_e.displayName;const Vn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Wn,{children:[t.jsx(Vt,{}),t.jsxs(Pe,{ref:o,className:g("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),...n,children:[e,t.jsxs(ys,{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:[t.jsx(Rs,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Vn.displayName=Pe.displayName;const qn=i.forwardRef(({className:s,...e},n)=>t.jsx(Le,{ref:n,className:g("text-lg font-semibold leading-none tracking-tight",s),...e}));qn.displayName=Le.displayName;const Qn=i.forwardRef(({className:s,...e},n)=>t.jsx(ze,{ref:n,className:g("text-sm text-muted-foreground",s),...e}));Qn.displayName=ze.displayName;const Gn=i.forwardRef(({className:s,inset:e,children:n,...o},a)=>t.jsxs(Fe,{ref:a,className:g("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",s),...o,children:[n,t.jsx(st,{className:"ml-auto h-4 w-4"})]}));Gn.displayName=Fe.displayName;const Kn=i.forwardRef(({className:s,...e},n)=>t.jsx(Oe,{ref:n,className:g("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),...e}));Kn.displayName=Oe.displayName;const Xn=i.forwardRef(({className:s,sideOffset:e=4,...n},o)=>t.jsx(ws,{children:t.jsx(He,{ref:o,sideOffset:e,className:g("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 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),...n})}));Xn.displayName=He.displayName;const Jn=i.forwardRef(({className:s,inset:e,...n},o)=>t.jsx($e,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",s),...n}));Jn.displayName=$e.displayName;const Yn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Be,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(We,{children:t.jsx(it,{className:"h-4 w-4"})})}),e]}));Yn.displayName=Be.displayName;const Zn=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Ve,{ref:o,className:g("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(We,{children:t.jsx(lt,{className:"h-2 w-2 fill-current"})})}),e]}));Zn.displayName=Ve.displayName;const eo=i.forwardRef(({className:s,inset:e,...n},o)=>t.jsx(qe,{ref:o,className:g("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",s),...n}));eo.displayName=qe.displayName;const to=i.forwardRef(({className:s,...e},n)=>t.jsx(Qe,{ref:n,className:g("-mx-1 my-1 h-px bg-border",s),...e}));to.displayName=Qe.displayName;const so=W("flex h-10 w-full rounded-md border bg-input-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-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"}}),no=i.forwardRef(({className:s,type:e,variant:n,...o},a)=>t.jsx("input",{type:e,className:g(so({variant:n,className:s})),ref:a,...o}));no.displayName="Input";const oo=i.forwardRef(({className:s,...e},n)=>t.jsx(Ge,{ref:n,className:g("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...e}));oo.displayName=Ge.displayName;const ro=W("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"}}),qt=i.forwardRef(({message:s,role:e,layout:n,className:o,children:a,messageId:l,autoScroll:d,isLastMessage:p=!1,...u},r)=>{const c=s?s.role:e||"assistant",f=s?s.id:l,h=i.useRef(null),[w,m]=i.useState(void 0);return i.useImperativeHandle(r,()=>h.current),i.useEffect(()=>{if(!p||c!=="assistant"){m(void 0);return}const x=()=>{const y=h.current;if(!y)return;let N=y.parentElement;for(;N&&!N.classList.contains("overflow-y-auto");)N=N.parentElement;if(!N)return;const T=y.previousElementSibling;if(!T||T.getAttribute("aria-label")!=="user message"){m(void 0);return}const U=N.clientHeight,I=T.offsetHeight,S=Math.max(0,U-I-32);m(S)};x();const v=new ResizeObserver(x);if(h.current){v.observe(h.current);let y=h.current.parentElement;for(;y&&!y.classList.contains("overflow-y-auto");)y=y.parentElement;y&&v.observe(y)}return()=>v.disconnect()},[p,c]),i.useEffect(()=>{if((d!==void 0?d:c==="user")&&h.current){const v=setTimeout(()=>{h.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(v)}},[c,d]),t.jsx("article",{ref:h,"aria-label":`${c} message`,"data-message-id":f,className:g(ro({role:c,layout:n}),o),style:{minHeight:w!==void 0?`${w}px`:void 0},...u,children:a})});qt.displayName="Message";const te=128e3,Te={"claude-sonnet-4-5-20250929":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-haiku-20240307":2e5,"gpt-4-turbo":128e3,"gpt-4-turbo-preview":128e3,"gpt-4-0125-preview":128e3,"gpt-4-1106-preview":128e3,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,default:te};function ao(s){if(!s)return te;if(s in Te)return Te[s]??te;const e=s.toLowerCase();return e.includes("claude")?2e5:e.includes("gpt-4-turbo")?128e3:e.includes("gpt-4-32k")?32768:e.includes("gpt-4")?8192:e.includes("gpt-3.5")?16385:te}function io(s,e){const n=ao(e);return s/n*100}function lo(s,e,n=1){return`${io(s,e).toFixed(n)}%`}const ke=W("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"}}),co=W("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),Qt=i.forwardRef(({content:s,isStreaming:e=!1,mode:n="collapsible",defaultExpanded:o=!1,autoExpand:a=!1,autoCollapse:l=!0,autoCollapseDelay:d=2e3,label:p="Thinking",variant:u,className:r},c)=>{const[f,h]=i.useState(n==="inline"?!0:o),[w,m]=i.useState(!1);return i.useEffect(()=>{if(l&&!e&&s&&n==="collapsible"){const x=setTimeout(()=>{m(!0),h(!1)},d);return()=>clearTimeout(x)}},[e,s,l,d,n]),i.useEffect(()=>{a&&e&&n==="collapsible"&&!w&&h(!0)},[a,e,n,w]),!s&&!e?null:n==="inline"?t.jsxs("div",{ref:c,className:g(ke({variant:u}),"p-3",r),children:[t.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:p}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse"})]}),t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):t.jsxs("div",{ref:c,className:g("mb-3",r),children:[t.jsxs("button",{type:"button",onClick:()=>{h(!f),m(!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:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide shrink-0",children:p}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!f&&s&&t.jsxs("span",{className:"text-xs text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),t.jsx(me,{className:co({expanded:f}),"aria-hidden":"true"})]}),f&&t.jsx("div",{className:g(ke({variant:u}),"mt-2 p-3 animate-fadeIn"),children:t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});Qt.displayName="Reasoning";const se=i.forwardRef(({content:s,isStreaming:e=!1,showEmpty:n=!0,emptyMessage:o="",className:a,...l},d)=>{if(!s&&e&&n)return t.jsx("div",{ref:d,className:g("opacity-70 italic text-sm",a),...l,children:o});if(!s)return null;const p={table:({node:u,...r})=>t.jsx("div",{className:"overflow-x-auto my-4",children:t.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...r})}),thead:({node:u,...r})=>t.jsx("thead",{className:"bg-card border-b border-border",...r}),tbody:({node:u,...r})=>t.jsx("tbody",{...r}),tr:({node:u,...r})=>t.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...r}),th:({node:u,...r})=>t.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...r}),td:({node:u,...r})=>t.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...r}),input:({node:u,checked:r,...c})=>c.type==="checkbox"?t.jsx("input",{type:"checkbox",checked:r||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...c}):t.jsx("input",{...c}),code:({node:u,...r})=>r.className?.includes("language-")?t.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-sm font-mono text-foreground shadow-sm",...r}):t.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-sm font-mono text-foreground",...r}),pre:({node:u,...r})=>t.jsx("pre",{className:"my-4 rounded-lg",...r}),h1:({node:u,...r})=>t.jsx("h1",{className:"text-2xl font-bold mt-6 mb-4 text-foreground border-b border-border pb-2",...r}),h2:({node:u,...r})=>t.jsx("h2",{className:"text-xl font-semibold mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...r}),h3:({node:u,...r})=>t.jsx("h3",{className:"text-lg font-semibold mt-4 mb-2 text-foreground",...r}),h4:({node:u,...r})=>t.jsx("h4",{className:"text-base font-semibold mt-3 mb-2 text-foreground",...r}),ul:({node:u,...r})=>{const c=u?.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(h=>typeof h=="object"&&h!==null&&"type"in h&&h.type==="element"&&"tagName"in h&&h.tagName==="input"&&"properties"in h&&typeof h.properties=="object"&&h.properties!==null&&"type"in h.properties&&h.properties.type==="checkbox"));return t.jsx("ul",{className:g("my-2 space-y-1 text-foreground",c?"list-none space-y-2":"list-disc list-inside"),...r})},ol:({node:u,...r})=>t.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...r}),li:({node:u,...r})=>{const c=u?.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 t.jsx("li",{className:g("flex items-start",c?"gap-2":"ml-2"),...r})},a:({node:u,...r})=>t.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...r}),p:({node:u,...r})=>t.jsx("p",{className:"my-2 text-foreground leading-relaxed",...r}),blockquote:({node:u,...r})=>t.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2 rounded-r-md shadow-sm",...r}),hr:({node:u,...r})=>t.jsx("hr",{className:"my-6 border-t border-border opacity-50",...r})};return t.jsxs("div",{ref:d,className:g("markdown-content prose prose-sm max-w-none dark:prose-invert",a),...l,children:[t.jsx(is,{remarkPlugins:[Ls],components:p,children:s}),e&&s&&t.jsx("span",{className:"inline-block ml-1 animate-typing text-primary",children:"..."})]})});se.displayName="Response";const uo={pending:"bg-transparent text-muted-foreground",in_progress:"bg-transparent text-muted-foreground",completed:"bg-transparent text-muted-foreground",failed:"bg-transparent text-muted-foreground"};function Ie({toolCall:s}){const[e,n]=i.useState(!1);return t.jsxs("div",{className:"flex flex-col",children:[t.jsxs("button",{type:"button",className:"flex items-center gap-1.5 cursor-pointer bg-transparent border-none p-0 text-left group w-fit",onClick:()=>n(!e),"aria-expanded":e,children:[t.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded ${uo[s.status]}`,children:[t.jsx(Us,{className:"h-3 w-3"}),t.jsx("span",{children:s.title}),s.status==="completed"&&t.jsx("span",{children:"✓"})]}),t.jsx("span",{className:"text-muted-foreground text-xs opacity-0 group-hover:opacity-100 transition-opacity",children:e?"▲":"▼"})]}),e&&t.jsxs("div",{className:"mt-2 space-y-3 text-sm border border-border rounded-md p-3 bg-card shadow-sm max-w-full",children:[s.locations&&s.locations.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5",children:"Files"}),t.jsx("ul",{className:"space-y-1",children:s.locations.map(o=>t.jsxs("li",{className:"font-mono text-xs text-foreground bg-muted px-2 py-1 rounded",children:[o.path,o.line!==null&&o.line!==void 0&&`:${o.line}`]},`${o.path}:${o.line??""}`))})]}),s.rawInput&&Object.keys(s.rawInput).length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5",children:"Input"}),t.jsx("div",{className:"bg-muted p-2 rounded border border-border",children:t.jsx(ve,{value:s.rawInput,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent"}})})]}),s.content&&s.content.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5",children:"Output"}),t.jsx("div",{className:"space-y-2",children:s.content.map((o,a)=>{const l=()=>o.type==="diff"&&"path"in o?`diff-${o.path}-${a}`:o.type==="terminal"&&"terminalId"in o?`terminal-${o.terminalId}`:o.type==="text"&&"text"in o?`text-${o.text.substring(0,20)}-${a}`:o.type==="content"&&"content"in o?`content-${o.content.text?.substring(0,20)}-${a}`:`block-${a}`,d=(p,u)=>{try{const r=JSON.parse(p);if(typeof r=="object"&&r!==null)return t.jsx("div",{className:"bg-muted p-2 rounded border border-border",children:t.jsx(ve,{value:r,collapsed:!1,displayDataTypes:!1,displayObjectSize:!1,enableClipboard:!0,style:{fontSize:"11px",backgroundColor:"transparent"}})},u)}catch{}return t.jsx("pre",{className:"bg-muted p-2.5 rounded border border-border text-xs overflow-x-auto font-mono text-foreground",children:p},u)};if(o.type==="content"&&"content"in o){const p=o.content;if(p.type==="text"&&p.text)return d(p.text,l())}return o.type==="text"&&"text"in o?d(o.text,l()):o.type==="diff"&&"path"in o&&"oldText"in o&&"newText"in o?t.jsxs("div",{className:"border rounded",children:[t.jsxs("div",{className:"bg-muted px-2 py-1 text-xs font-mono",children:[o.path,"line"in o&&o.line!==null&&o.line!==void 0&&`:${o.line}`]}),t.jsxs("div",{className:"p-2 font-mono text-xs",children:[t.jsxs("div",{className:"text-red-600",children:["- ",o.oldText]}),t.jsxs("div",{className:"text-green-600",children:["+ ",o.newText]})]})]},l()):o.type==="terminal"&&"terminalId"in o?t.jsxs("div",{className:"bg-black text-green-400 p-2 rounded text-xs font-mono",children:["Terminal: ",o.terminalId]},l()):null})})]}),s.error&&t.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded p-2.5 text-destructive",children:[t.jsx("div",{className:"text-xs font-semibold text-destructive uppercase tracking-wide mb-1.5",children:"Error"}),t.jsx("div",{className:"text-xs",children:s.error})]}),s.tokenUsage&&t.jsxs("div",{className:"bg-muted border border-border rounded p-2.5",children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2",children:"Token Usage"}),t.jsxs("div",{className:"grid grid-cols-3 gap-3 text-xs text-foreground",children:[s.tokenUsage.inputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-muted-foreground text-[10px] uppercase tracking-wide mb-0.5",children:"Input"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.inputTokens.toLocaleString()})]}),s.tokenUsage.outputTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-muted-foreground text-[10px] uppercase tracking-wide mb-0.5",children:"Output"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.outputTokens.toLocaleString()})]}),s.tokenUsage.totalTokens!==void 0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-muted-foreground text-[10px] uppercase tracking-wide mb-0.5",children:"Total"}),t.jsx("div",{className:"font-medium",children:s.tokenUsage.totalTokens.toLocaleString()})]})]})]}),s.startedAt&&t.jsxs("div",{className:"text-xs text-muted-foreground",children:["Started: ",new Date(s.startedAt).toLocaleTimeString(),s.completedAt&&t.jsxs(t.Fragment,{children:[" ","| Completed:"," ",new Date(s.completedAt).toLocaleTimeString()," (",Math.round((s.completedAt-s.startedAt)/1e3),"s)"]})]})]})]})}const ee=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],Ee=["...","·..",".·.","..·",".·.","·.."];function po({startTime:s}){const[e,n]=i.useState(0),[o,a]=i.useState(()=>ee[Math.floor(Math.random()*ee.length)]),[l,d]=i.useState(0);i.useEffect(()=>{const r=setInterval(()=>{const f=Date.now()-s;n(f)},100);return()=>clearInterval(r)},[s]),i.useEffect(()=>{const r=setInterval(()=>{const c=Math.floor(Math.random()*ee.length);a(ee[c])},1500);return()=>clearInterval(r)},[]),i.useEffect(()=>{const r=setInterval(()=>{d(c=>(c+1)%Ee.length)},100);return()=>clearInterval(r)},[]);const p=(e/1e3).toFixed(1),u=Ee[l];return t.jsxs("span",{className:"text-muted-foreground text-sm",children:[o,u," ",p,"s"]})}const fo=W("w-full px-4 py-3 rounded-xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-primary text-primary-foreground shadow-sm",assistant:"text-foreground",system:"bg-card border border-border text-foreground opacity-80 text-sm"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),Gt=i.forwardRef(({role:s,variant:e,isStreaming:n,message:o,thinkingDisplayStyle:a="collapsible",className:l,children:d,...p},u)=>{const r=C(x=>x.streamingStartTime),c=C(x=>x.currentModel),f=o&&!d,h=f?o.role:s||"assistant",w=f?o.isStreaming:n;let m=d;if(f){const x=o.metadata?.thinking,v=!!x,y=o.isStreaming&&!o.content&&o.role==="assistant";m=t.jsxs(t.Fragment,{children:[o.role==="assistant"&&v&&t.jsx(Qt,{content:x,isStreaming:o.isStreaming,mode:a,autoCollapse:!0}),y&&r&&t.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[t.jsx(ct,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx(po,{startTime:r})]}),o.role==="assistant"?(()=>{const N=(o.toolCalls||[]).slice().sort((I,A)=>(I.contentPosition??1/0)-(A.contentPosition??1/0));if(N.length===0||!N.some(I=>I.contentPosition!==void 0))return t.jsxs(t.Fragment,{children:[N.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mb-3",children:N.map(I=>t.jsx(Ie,{toolCall:I},I.id))}),t.jsx(se,{content:o.content,isStreaming:o.isStreaming,showEmpty:!1})]});const T=[];let U=0;if(N.forEach(I=>{const A=I.contentPosition??o.content.length;if(A>U){const S=o.content.slice(U,A);S&&T.push(t.jsx(se,{content:S,isStreaming:!1,showEmpty:!1},`text-before-${I.id}`))}T.push(t.jsx("div",{className:"my-2",children:t.jsx(Ie,{toolCall:I})},`tool-${I.id}`)),U=A}),U<o.content.length){const I=o.content.slice(U);I&&T.push(t.jsx(se,{content:I,isStreaming:o.isStreaming,showEmpty:!1},"text-end"))}return t.jsx(t.Fragment,{children:T})})():t.jsx("div",{className:"whitespace-pre-wrap",children:o.content}),o.role==="assistant"&&o.tokenUsage&&t.jsx("div",{className:"mt-3 pt-2 border-t border-border/30 text-xs text-muted-foreground/60",children:t.jsxs("span",{children:["Context:"," ",lo(o.tokenUsage.totalTokens??0,c??void 0)," ","(",(o.tokenUsage.totalTokens??0).toLocaleString()," ","tokens)"]})})]})}return t.jsx("div",{ref:u,className:g(fo({role:h,variant:e}),w&&"animate-pulse-subtle",l),...p,children:m})});Gt.displayName="MessageContent";const we=i.forwardRef(({showIcons:s=!0,visibleTabs:e=["todo","files"],variant:n="default",className:o,...a},l)=>{const p=[{id:"todo",label:"To-do",icon:nt},{id:"files",label:"Files",icon:ot},{id:"database",label:"Database",icon:rt},{id:"sources",label:"Sources",icon:at}].filter(r=>e.includes(r.id)),u=n==="compact"?"gap-[4px]":"gap-3";return t.jsx(G,{ref:l,className:g("w-full justify-start bg-transparent p-0 h-auto",u,o),...a,children:p.map(r=>{const c=r.icon;return t.jsxs(K,{value:r.id,className:g("gap-2 px-3 py-1.5 rounded-lg text-sm font-medium","data-[state=active]:bg-zinc-100 data-[state=active]:text-foreground","data-[state=inactive]:text-muted-foreground"),children:[s&&c&&t.jsx(c,{className:"size-4"}),r.label]},r.id)})})});we.displayName="PanelTabsHeader";const mo=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(Ke,{ref:o,className:g("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-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),...n,children:[e,t.jsx(vs,{asChild:!0,children:t.jsx(Ms,{className:"h-4 w-4 opacity-50"})})]}));mo.displayName=Ke.displayName;const Kt=i.forwardRef(({className:s,...e},n)=>t.jsx(Xe,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(ge,{className:"h-4 w-4"})}));Kt.displayName=Xe.displayName;const Xt=i.forwardRef(({className:s,...e},n)=>t.jsx(Je,{ref:n,className:g("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(me,{className:"h-4 w-4"})}));Xt.displayName=Je.displayName;const go=i.forwardRef(({className:s,children:e,position:n="popper",...o},a)=>t.jsx(Ns,{children:t.jsxs(Ye,{ref:a,className:g("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:n,...o,children:[t.jsx(Kt,{}),t.jsx(js,{className:g("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),t.jsx(Xt,{})]})}));go.displayName=Ye.displayName;const ho=i.forwardRef(({className:s,...e},n)=>t.jsx(Ze,{ref:n,className:g("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...e}));ho.displayName=Ze.displayName;const xo=i.forwardRef(({className:s,children:e,...n},o)=>t.jsxs(et,{ref:o,className:g("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(Ss,{children:t.jsx(it,{className:"h-4 w-4"})})}),t.jsx(Cs,{children:e})]}));xo.displayName=et.displayName;const bo=i.forwardRef(({className:s,...e},n)=>t.jsx(tt,{ref:n,className:g("-mx-1 my-1 h-px bg-muted",s),...e}));bo.displayName=tt.displayName;const Jt=i.forwardRef(({task:s,collapsible:e=!0,defaultExpanded:n=!1,onTaskClick:o,className:a,...l},d)=>{const[p,u]=i.useState(n),r=!!(s.details||s.files&&s.files.length>0),c={pending:lt,in_progress:ct,completed:As}[s.status],f=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},h=()=>{r&&e&&u(!p),o?.(s)};return t.jsxs("div",{ref:d,className:g("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",a),...l,children:[t.jsxs("button",{type:"button",onClick:h,className:g("w-full flex items-center gap-3 px-3 py-2.5 text-left",r&&e&&"cursor-pointer"),disabled:!r&&!e,children:[t.jsx(c,{className:g("w-4 h-4 shrink-0",f(),s.status==="in_progress"&&"animate-spin")}),t.jsx("span",{className:g("flex-1 text-sm font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"font-medium"),children:s.text}),r&&e&&t.jsx(me,{className:g("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",p&&"rotate-180"),"aria-hidden":"true"})]}),r&&p&&t.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[s.details&&t.jsx("p",{className:"text-sm text-foreground opacity-80 leading-relaxed mb-2",children:s.details}),s.files&&s.files.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),t.jsx("div",{className:"space-y-1",children:s.files.map(w=>t.jsx("div",{className:"text-xs font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:w},w))})]})]})]})});Jt.displayName="Task";const yo=i.forwardRef(({tasks:s,collapsible:e=!0,onTaskClick:n,emptyMessage:o="No tasks yet.",className:a,...l},d)=>t.jsx("div",{ref:d,className:g("space-y-2 max-h-96 overflow-y-auto",a),...l,children:s.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic py-4 text-center",children:o}):s.map(p=>t.jsx(Jt,{task:p,collapsible:e,...n?{onTaskClick:n}:{}},p.id))}));yo.displayName="TaskList";const wo=W("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-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"}}),vo=i.forwardRef(({className:s,autoResize:e=!1,maxHeight:n=200,variant:o,...a},l)=>{const d=i.useRef(null),p=i.useCallback(r=>{d.current=r,typeof l=="function"?l(r):l&&(l.current=r)},[l]),u=i.useCallback(()=>{const r=d.current;if(!r||!e)return;r.style.height="auto";const c=Math.min(r.scrollHeight,n);r.style.height=`${c}px`,r.scrollHeight>n?r.style.overflowY="auto":r.style.overflowY="hidden"},[e,n]);return i.useEffect(()=>{u()},[u]),t.jsx("textarea",{className:g(wo({variant:o}),e&&"overflow-y-hidden",s),ref:p,...a})});vo.displayName="Textarea";const B=$("gui");function No({agentName:s}){const{isExpanded:e,setIsExpanded:n}=xe();return t.jsxs("div",{className:"flex lg:hidden items-center gap-2 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx("h1",{className:"text-[20px] font-semibold leading-[1.2] tracking-[-0.4px] text-foreground",children:s}),t.jsx("div",{className:"flex items-center justify-center shrink-0",children:t.jsx(ge,{className:"size-4 rotate-180 text-muted-foreground"})})]}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle menu",onClick:()=>n(!e),children:t.jsx(dt,{className:"size-4 text-muted-foreground"})})]})}function jo({agentName:s,todos:e,sources:n,showHeader:o}){const{panelSize:a,setPanelSize:l}=be();return t.jsxs(Nt,{className:g("border-b border-border bg-card relative lg:p-0","[border-bottom-width:0.5px]"),children:[t.jsxs("div",{className:"hidden lg:flex items-center gap-2 w-full h-16 py-5 pl-6 pr-4",children:[o&&t.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[t.jsx("h1",{className:"text-[20px] font-semibold leading-[1.2] tracking-[-0.4px] text-foreground",children:s}),t.jsx("div",{className:"flex items-center justify-center shrink-0",children:t.jsx(ge,{className:"size-4 rotate-180 text-muted-foreground"})})]}),!o&&t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",className:"flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Toggle sidebar",onClick:()=>{l(a==="hidden"?"small":"hidden")},children:t.jsx(dt,{className:"size-4 text-muted-foreground"})})]}),t.jsx(No,{agentName:s}),t.jsx(jt,{className:g("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:t.jsxs(ye,{defaultValue:"todo",className:"w-full",children:[t.jsx(we,{showIcons:!0,visibleTabs:["todo","files","sources"],variant:"default"}),t.jsx(P,{value:"todo",className:"mt-4",children:t.jsx(ae,{todos:e})}),t.jsx(P,{value:"files",className:"mt-4",children:t.jsx(ie,{})}),t.jsx(P,{value:"sources",className:"mt-4",children:t.jsx(le,{sources:n})})]})})]})}function So({client:s,initialSessionId:e}){const{connectionStatus:n,connect:o,sessionId:a}=Qs(s,e),{messages:l}=gt(s);Gs(s);const d=C(m=>m.error),[p,u]=i.useState("Agent"),[r,c]=i.useState(typeof window<"u"?window.innerWidth>=1024:!0);i.useEffect(()=>{B.debug("Connection status changed",{status:n}),n==="error"&&d&&B.error("Connection error occurred",{error:d})},[n,d]),i.useEffect(()=>{if(s&&a){const m=s.getCurrentSession();m?.metadata?.agentName&&u(m.metadata.agentName)}},[s,a]),i.useEffect(()=>{const m=window.matchMedia("(min-width: 1024px)"),x=v=>{c(v.matches)};return c(m.matches),m.addEventListener("change",x),()=>{m.removeEventListener("change",x)}},[]);const f=[],h=[{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"}],w=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:t.jsx(je,{className:"h-4 w-4"}),category:"model",onSelect:()=>{B.info("User selected Sonnet 4.5 model")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:t.jsx(je,{className:"h-4 w-4"}),category:"model",onSelect:()=>{B.info("User selected Opus model")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:t.jsx(_s,{className:"h-4 w-4"}),category:"action",onSelect:()=>{B.info("User opened settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:t.jsx(Ps,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{B.info("User enabled code mode")}}];return t.jsxs(Pt,{defaultPanelSize:"hidden",defaultActiveTab:"todo",children:[t.jsxs(Lt,{children:[t.jsx(jo,{agentName:p,todos:f,sources:h,showHeader:l.length>0}),n==="error"&&d&&t.jsx("div",{className:"border-b border-destructive/20 bg-destructive/10 px-6 py-4",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"mb-1 text-sm font-semibold text-destructive",children:"Connection Error"}),t.jsx("p",{className:"whitespace-pre-line text-sm text-foreground",children:d})]}),t.jsx("button",{type:"button",onClick:o,className:"rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive-hover",children:"Retry"})]})}),t.jsxs(zt,{children:[t.jsx(Ft,{className:l.length>0?"pt-4":"",children:l.length===0?t.jsx("div",{className:"flex flex-1 items-center px-4",children:t.jsx(wt,{title:p,description:"This agent can help you with your tasks. Start a conversation by typing a message below.",suggestedPrompts:["Help me debug this code","Explain how this works","Create a new feature","Review my changes"],onPromptClick:m=>{B.info("Prompt clicked",{prompt:m})}})}):t.jsx("div",{className:"flex flex-col gap-4 px-4",children:l.map((m,x)=>t.jsx(qt,{message:m,isLastMessage:x===l.length-1,children:t.jsx(Gt,{message:m,thinkingDisplayStyle:"collapsible"})},m.id))})}),t.jsx(Ot,{children:t.jsxs(Tt,{client:s,children:[t.jsx(At,{commands:w}),t.jsx(kt,{placeholder:"Type a message or / for commands...",autoFocus:!0}),t.jsxs(Et,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Rt,{}),t.jsx(Ut,{})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Mt,{}),t.jsx(It,{children:t.jsx(Ds,{className:"size-4"})})]})]})]})})]})]}),r&&t.jsx(Ht,{breakpoint:"lg",children:t.jsxs(ye,{defaultValue:"todo",className:"flex flex-col h-full",children:[t.jsx("div",{className:g("border-b border-border bg-card","px-6 py-2 h-16","flex items-center","[border-bottom-width:0.5px]"),children:t.jsx(we,{showIcons:!0,visibleTabs:["todo","files","sources"],variant:"compact"})}),t.jsx(P,{value:"todo",className:"flex-1 p-4 mt-0",children:t.jsx(ae,{todos:f})}),t.jsx(P,{value:"files",className:"flex-1 p-4 mt-0",children:t.jsx(ie,{})}),t.jsx(P,{value:"sources",className:"flex-1 p-4 mt-0",children:t.jsx(le,{sources:h})})]})})]})}function Co(){return"http://localhost:3100"}const Re={agentServerUrl:Co()},Q=$("gui");function To(){const[s,e]=i.useState(null),[n,o]=i.useState(null),[a,l]=i.useState(null);return i.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("session");p&&(Q.info("Session ID found in URL",{sessionId:p}),l(p));try{Q.info("Initializing ACP client",{serverUrl:Re.agentServerUrl});const u=new en({type:"http",options:{baseUrl:Re.agentServerUrl}});return e(u),Q.info("ACP client initialized successfully"),()=>{Q.debug("Disconnecting ACP client"),u.disconnect().catch(r=>{Q.error("Failed to disconnect ACP client",{error:r instanceof Error?r.message:String(r)})})}}catch(u){const r=u instanceof Error?u.message:"Failed to initialize ACP client";o(r),Q.error("Failed to initialize ACP client",{error:u instanceof Error?u.message:String(u),stack:u instanceof Error?u.stack:void 0});return}},[]),n?t.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:t.jsxs("div",{className:"text-center p-8 max-w-md",children:[t.jsx("h1",{className:"text-2xl font-bold text-destructive mb-4",children:"Initialization Error"}),t.jsx("p",{className:"text-foreground mb-4",children:n}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to initialize the ACP client. Check the console for details."})]})}):t.jsx(So,{client:s,initialSessionId:a})}const Yt=document.getElementById("root");if(!Yt)throw new Error("Root element not found");ls.createRoot(Yt).render(t.jsx(cs.StrictMode,{children:t.jsx(To,{})}));
|