import{b as Ft,d as Sr,c as Le,a as l,f as h,t as yt}from"../chunks/bmn8XlW7.js";import{o as Tr}from"../chunks/CJbqisBi.js";import{t as J,o as Bt,v as qt,Z as Dr,aS as Rr,C as zt,aq as jr,aF as Or,aM as Pr,aG as Mr,V as Er,ai as at,f as Y,p as ut,e as i,r as s,a as ft,g as e,h as le,u as kt,c as o,s as T,d as c,b as st,n as it,ag as Ar}from"../chunks/DpkolLiq.js";import{s as fe,d as Nr,e as lt}from"../chunks/pfhwnV1O.js";import{l as Ct,s as St,p as Qt,i as b,a as Lr,b as Ur}from"../chunks/TXeUdaq1.js";import{I as Tt,s as Dt,f as Ke,e as dt,S as Ir,p as Jt,b as ze,n as Vt,o as Fr,g as ct,a as Wt}from"../chunks/DxBGAPM1.js";import{L as $t,b as Br}from"../chunks/C8B7Gptd.js";import{b as bt}from"../chunks/BlA1NA_K.js";import{p as qr}from"../chunks/CNEWdp3h.js";import{r as zr}from"../chunks/CiPTfhJW.js";import{e as Ht,f as er,g as tr,h as rr,j as or,S as Jr,i as Vr,B as Ne,a as Wr,C as wt,b as Xt,E as Hr}from"../chunks/SxayRmdi.js";import{c as Ve}from"../chunks/DdiL7vrO.js";import{C as nr}from"../chunks/C-DQPpgP.js";import{B as Xr,W as ar}from"../chunks/BVEGB_EG.js";import"../chunks/EMQoTJgY.js";import{U as Gr}from"../chunks/DmFIkIoV.js";import{X as Gt}from"../chunks/U2J7jvDs.js";import{S as Kr}from"../chunks/CWwN5y2H.js";function Yr(ce,w,q=!1,z=!1,ee=!1){var Z=ce,H="";J(()=>{var _=Dr;if(H===(H=w()??"")){Bt&&qt();return}if(_.nodes!==null&&(Rr(_.nodes.start,_.nodes.end),_.nodes=null),H!==""){if(Bt){zt.data;for(var E=qt(),L=E;E!==null&&(E.nodeType!==jr||E.data!=="");)L=E,E=Or(E);if(E===null)throw Pr(),Mr;Ft(zt,L),Z=Er(E);return}var C=H+"";q?C=`<svg>${C}</svg>`:z&&(C=`<math>${C}</math>`);var Q=Sr(C);if((q||z)&&(Q=at(Q)),Ft(at(Q),Q.lastChild),q||z)for(;at(Q);)Z.before(at(Q));else Z.before(Q)}})}function Je(ce,w){const q=Ct(w,["children","$$slots","$$events","$$legacy"]);/**
 * @license lucide-svelte v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const z=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];Tt(ce,St({name:"bot"},()=>q,{get iconNode(){return z},children:(ee,Z)=>{var H=Le(),_=Y(H);Dt(_,w,"default",{}),l(ee,H)},$$slots:{default:!0}}))}function Zr(ce,w){const q=Ct(w,["children","$$slots","$$events","$$legacy"]);/**
 * @license lucide-svelte v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const z=[["path",{d:"M13.234 20.252 21 12.3"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486"}]];Tt(ce,St({name:"paperclip"},()=>q,{get iconNode(){return z},children:(ee,Z)=>{var H=Le(),_=Y(H);Dt(_,w,"default",{}),l(ee,H)},$$slots:{default:!0}}))}function Qr(ce,w){const q=Ct(w,["children","$$slots","$$events","$$legacy"]);/**
 * @license lucide-svelte v0.469.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const z=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];Tt(ce,St({name:"send"},()=>q,{get iconNode(){return z},children:(ee,Z)=>{var H=Le(),_=Y(H);Dt(_,w,"default",{}),l(ee,H)},$$slots:{default:!0}}))}var eo=h("<div><!></div>");function Kt(ce,w){ut(w,!0);let q=Qt(w,"class",3,"");Ht.setOptions({breaks:!0,gfm:!0});const z=le(()=>Ht.parse(w.content));var ee=eo(),Z=i(ee);Yr(Z,()=>e(z)),s(ee),J(()=>Ke(ee,1,`prose prose-sm dark:prose-invert max-w-none ${q()??""}`)),l(ce,ee),ft()}var to=h("<!> <!> <span> </span>",1),ro=h('<div class="mt-2 pl-6 border-l-2 border-muted text-sm text-muted-foreground italic whitespace-pre-wrap"> </div>'),oo=h("<!> <!>",1),no=h('<div class="my-2"><!></div>');function Yt(ce,w){ut(w,!0);let q=Qt(w,"streaming",3,!1),z=T(!1);kt(()=>{q()?o(z,!0):w.duration!==void 0&&o(z,!1)});const ee=le(()=>q()?"Thinking...":w.duration!==void 0?`Thought for ${w.duration.toFixed(1)}s`:"Thinking");var Z=no(),H=i(Z);Ve(H,()=>or,(_,E)=>{E(_,{get open(){return e(z)},set open(L){o(z,L,!0)},children:(L,C)=>{var Q=oo(),xe=Y(Q);Ve(xe,()=>er,(me,ye)=>{ye(me,{class:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:(P,X)=>{var M=to(),re=Y(M);{var A=U=>{nr(U,{class:"w-4 h-4"})},he=U=>{rr(U,{class:"w-4 h-4"})};b(re,U=>{e(z)?U(A):U(he,!1)})}var ge=c(re,2);{var be=U=>{$t(U,{class:"w-4 h-4 animate-spin"})},oe=U=>{Xr(U,{class:"w-4 h-4"})};b(ge,U=>{q()?U(be):U(oe,!1)})}var se=c(ge,2),we=i(se,!0);s(se),J(()=>fe(we,e(ee))),l(P,M)},$$slots:{default:!0}})});var te=c(xe,2);Ve(te,()=>tr,(me,ye)=>{ye(me,{children:(P,X)=>{var M=ro(),re=i(M,!0);s(M),J(()=>fe(re,w.content)),l(P,M)},$$slots:{default:!0}})}),l(L,Q)},$$slots:{default:!0}})}),s(Z),l(ce,Z),ft()}var ao=h("<!> <!> <span> </span>",1),so=h('<div class="mt-1 text-xs text-muted-foreground">Result:</div> <pre class="mt-0.5 p-2 rounded bg-green-50 dark:bg-green-950/30 text-xs font-mono overflow-x-auto whitespace-pre-wrap text-green-700 dark:text-green-300"> </pre>',1),io=h('<div class="mt-1 text-xs text-red-600 dark:text-red-400"> </div>'),lo=h('<div class="text-sm"><div class="font-medium text-foreground"> </div> <pre class="mt-1 p-2 rounded bg-muted text-xs font-mono overflow-x-auto whitespace-pre-wrap"> </pre> <!> <!></div>'),co=h('<div class="mt-2 pl-6 border-l-2 border-amber-300 dark:border-amber-700 space-y-3"></div>'),uo=h("<!> <!>",1),fo=h('<div class="my-2"><!></div>');function Zt(ce,w){ut(w,!0);let q=T(!1);const z=le(()=>w.calls.length===1?`Tool: ${w.calls[0].name}`:`Tool Calls: ${w.calls.length}`);function ee(_){try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}var Z=fo(),H=i(Z);Ve(H,()=>or,(_,E)=>{E(_,{get open(){return e(q)},set open(L){o(q,L,!0)},children:(L,C)=>{var Q=uo(),xe=Y(Q);Ve(xe,()=>er,(me,ye)=>{ye(me,{class:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:(P,X)=>{var M=ao(),re=Y(M);{var A=se=>{nr(se,{class:"w-4 h-4"})},he=se=>{rr(se,{class:"w-4 h-4"})};b(re,se=>{e(q)?se(A):se(he,!1)})}var ge=c(re,2);ar(ge,{class:"w-4 h-4"});var be=c(ge,2),oe=i(be,!0);s(be),J(()=>fe(oe,e(z))),l(P,M)},$$slots:{default:!0}})});var te=c(xe,2);Ve(te,()=>tr,(me,ye)=>{ye(me,{children:(P,X)=>{var M=co();dt(M,21,()=>w.calls,re=>re.id,(re,A)=>{var he=lo(),ge=i(he),be=i(ge,!0);s(ge);var oe=c(ge,2),se=i(oe,!0);s(oe);var we=c(oe,2);{var U=ie=>{var I=so(),Re=c(Y(I),2),N=i(Re,!0);s(Re),J(()=>fe(N,e(A).result)),l(ie,I)};b(we,ie=>{e(A).result&&ie(U)})}var Ye=c(we,2);{var We=ie=>{var I=io(),Re=i(I,!0);s(I),J(()=>fe(Re,e(A).error)),l(ie,I)};b(Ye,ie=>{e(A).error&&ie(We)})}s(he),J(ie=>{fe(be,e(A).name),fe(se,ie)},[()=>ee(e(A).arguments)]),l(re,he)}),s(M),l(P,M)},$$slots:{default:!0}})}),l(L,Q)},$$slots:{default:!0}})}),s(Z),l(ce,Z),ft()}var po=h("<option> </option>"),vo=h("<option>Select a profile...</option> <!>",1),mo=h("<!> ",1),ho=h("<!> <!>",1),go=h('<div class="text-center"><!> <p class="text-muted-foreground mb-4">No running chat-capable profiles.</p> <!></div>'),_o=h('<div class="text-center"><!> <p class="text-muted-foreground">Select a profile to start chatting.</p></div>'),xo=h('<div class="h-full flex items-center justify-center"><div class="text-center text-muted-foreground"><!> <p>Start a conversation with <strong> </strong></p> <p class="text-sm mt-1"> </p></div></div>'),yo=h('<div class="flex gap-3 opacity-60"><div class="flex-shrink-0 w-8 h-8 rounded-full bg-muted flex items-center justify-center"><!></div> <div class="flex-1 min-w-0"><p class="text-xs text-muted-foreground mb-1 italic">System Prompt</p> <div class="text-sm text-muted-foreground italic whitespace-pre-wrap"> </div></div></div>'),bo=h('<div class="flex items-center gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg px-3 py-2" id="system-prompt-hint"><!> <span>No system prompt set.</span> <a class="text-primary hover:underline">Set one in profile settings</a> <button class="ml-auto text-muted-foreground hover:text-foreground" type="button"><!></button></div>'),wo=h('<div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0"><!></div>'),ko=h("<!> <!> <!>",1),$o=h('<p class="whitespace-pre-wrap"> </p>'),Co=h('<div class="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0"><!></div>'),So=h("<div><!> <div><!></div> <!></div>"),To=h('<div class="flex items-center gap-2 text-sm text-muted-foreground animate-pulse px-4 py-2"><!> <span> </span></div>'),Do=h('<div class="flex gap-3"><div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0"><!></div> <div class="max-w-[80%] rounded-lg px-4 py-2 bg-muted"><!> <!> <!></div></div>'),Ro=h('<div class="flex gap-3"><div class="w-8 h-8 rounded-full bg-destructive/10 flex items-center justify-center flex-shrink-0"><!></div> <div class="max-w-[80%]"><!></div></div>'),jo=h('<div class="flex justify-center py-2"><!></div>'),Oo=h("<!> <!> <!> <!> <!> <!>",1),Po=h('<img alt="Attachment" class="w-16 h-16 object-cover rounded-lg border"/>'),Mo=h('<video class="w-16 h-16 object-cover rounded-lg border"><track kind="captions"/></video>',2),Eo=h('<div class="w-16 h-16 flex flex-col items-center justify-center rounded-lg border bg-muted text-muted-foreground text-xs p-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mb-1"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14 2 14 8 20 8"></polyline></svg> <span class="truncate w-full text-center"> </span></div>'),Ao=h('<div class="relative group"><!> <button type="button" class="absolute -top-2 -right-2 w-5 h-5 bg-destructive text-destructive-foreground rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"><!></button></div>'),No=h('<div class="px-4 pt-4 flex gap-2 flex-wrap"></div>'),Lo=h('<div class="flex-1 overflow-y-auto p-4 space-y-4"><!></div> <form class="p-4 border-t"><!> <div class="flex gap-2"><!> <!> <textarea placeholder="Type a message..." class="flex-1 resize-none overflow-hidden rounded-md border border-input 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-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50" rows="1"></textarea> <!></div> <input type="file" multiple class="hidden"/></form>',1),Uo=h('<div class="flex-1 overflow-hidden" role="region" aria-label="Chat message area with drag-drop file upload"><!></div>'),Io=h('<div class="space-y-6 h-[calc(100vh-8rem)] flex flex-col"><div class="flex items-center justify-between"><h1 class="text-2xl font-bold">Chat</h1> <div class="flex items-center gap-4"><!> <div class="flex items-center rounded-lg border bg-muted p-0.5"><button type="button">OpenAI</button> <button type="button">Anthropic</button></div> <!></div></div> <!></div>');function nn(ce,w){ut(w,!0);const q=()=>Ur(qr,"$page",z),[z,ee]=Lr(),Z=new Set(["txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css","sh","sql","conf","ini","toml"]),H=new Set(["readme","makefile","dockerfile","license","procfile","gemfile","brewfile","vagrantfile","rakefile","guardfile","podfile","fastfile","dangerfile","berksfile","thorfile","capfile","puppetfile","appraisals","codeowners","changelog","contributing","authors","todo","copying","notice","patents","version","manifest",".gitignore",".dockerignore",".editorconfig",".env.example",".npmrc",".nvmrc",".prettierrc",".eslintrc",".babelrc",".gitattributes",".mailmap",".env",".env.local",".env.development",".env.production",".env.test"]);let _=T(st([])),E=T(""),L=T(!1),C=T(null),Q=T(void 0),xe=T(null),te=T(st([])),me=T(!1),ye=T(void 0),P=T(""),X=T(""),M=T(void 0),re=new Ir,A=T(st([])),he=T(0),ge=3,be=T(!1),oe=T(null),se=T(null),we=T(!1),U=T(st([])),Ye=T(!1),We=T(!1),ie=T(null),I=T("openai");const Re=le(()=>Jt.profiles.filter(r=>Vr(r.model_type)&&ze.isRunning(r.id))),N=le(()=>e(Re).find(r=>r.id===e(xe))),Ze=le(()=>{var r;return((r=e(N))==null?void 0:r.model_type)==="vision"}),sr=le(()=>e(Ze)?e(I)==="anthropic"?"image/*,.txt,.md,.csv,.json,.xml,.yaml,.yml,.log,.py,.js,.ts,.html,.css,.sh,.sql,.conf,.ini,.toml":"image/*,video/*,.txt,.md,.csv,.json,.xml,.yaml,.yml,.log,.py,.js,.ts,.html,.css,.sh,.sql,.conf,.ini,.toml":".txt,.md,.csv,.json,.xml,.yaml,.yml,.log,.py,.js,.ts,.html,.css,.sh,.sql,.conf,.ini,.toml");let Qe=T(null);Tr(async()=>{Jt.refresh(),ze.refresh();const r=q().url.searchParams.get("profile");r&&o(Qe,parseInt(r,10),!0);try{o(U,await Vt.listTools(),!0),o(Ye,!0)}catch{}}),kt(()=>{e(Qe)!==null&&e(xe)===null&&e(Re).some(t=>t.id===e(Qe))&&o(xe,e(Qe),!0)}),kt(()=>{!e(E)&&e(se)&&(e(se).style.height="auto")});async function ir(r){return new Promise(t=>{const a=document.createElement("video");a.preload="metadata",a.onloadedmetadata=()=>{URL.revokeObjectURL(a.src),t(a.duration<=120)},a.onerror=()=>{URL.revokeObjectURL(a.src),t(!1)},a.src=URL.createObjectURL(r)})}async function Rt(r){var p;if(e(te).length>=3){o(C,{summary:"Maximum 3 attachments per message"},!0);return}const t=r.type.startsWith("video/"),a=r.type.startsWith("image/"),n=r.name.split("."),u=n.length>1,d=u&&((p=n.pop())==null?void 0:p.toLowerCase())||"",f=u?Z.has(d):H.has(r.name.toLowerCase());if(!f&&!t&&!a){const V=e(Ze)?"images, videos, and text files (.txt, .md, .py, .js, .json, .csv, .log, etc.)":"text files (.txt, .md, .py, .js, .json, .csv, .log, .yaml, .xml, etc.)";o(C,{summary:`Unsupported file type. Accepted: ${V}`},!0);return}if(!e(Ze)&&(a||t)){o(C,{summary:"This model only supports text file attachments"},!0);return}if(t&&e(I)==="anthropic"){o(C,{summary:"Video attachments are not supported with the Anthropic protocol"},!0);return}if(t&&!await ir(r)){o(C,{summary:"Video must be 2 minutes or less"},!0);return}const y=f?r.name:URL.createObjectURL(r);e(te).push({file:r,preview:y,type:f?"text":t?"video":"image"})}function lr(r){const t=e(te)[r];t.type!=="text"&&URL.revokeObjectURL(t.preview),e(te).splice(r,1)}async function cr(r){const t=r.target,a=Array.from(t.files||[]);for(const n of a)await Rt(n);t.value=""}function dr(r){var a;r.preventDefault(),o(me,!1);const t=Array.from(((a=r.dataTransfer)==null?void 0:a.files)||[]);for(const n of t)Rt(n)}function ur(r){r.preventDefault(),o(me,!0)}function fr(r){r.preventDefault(),o(me,!1)}async function jt(r){return new Promise((t,a)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=a,n.readAsDataURL(r)})}async function Ot(r){return new Promise((t,a)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=a,n.readAsText(r)})}async function pr(r,t){if(t.length===0)return r;if(e(I)==="anthropic"){const a=[{type:"text",text:r}];for(const n of t)if(n.type==="text"){const u=await Ot(n.file);a.push({type:"text",text:`[File: ${n.file.name}]
${u}`})}else if(n.type==="image"){const u=await jt(n.file),d=u.indexOf(","),f=d>=0?u.slice(d+1):u,y=u.match(/^data:([^;]+);/),p=y?y[1]:"image/png";a.push({type:"image",source:{type:"base64",media_type:p,data:f}})}return a}else{const a=[{type:"text",text:r}];for(const n of t)if(n.type==="text"){const u=await Ot(n.file);a.push({type:"text",text:`[File: ${n.file.name}]
${u}`})}else{const u=await jt(n.file);a.push({type:"image_url",image_url:{url:u}})}return a}}async function Pt(r){var V,pe,S,de,ke;const t={content:"",thinking:"",thinkingDur:void 0,toolCalls:[],toolCallsDone:!1,error:null},a=(V=r.body)==null?void 0:V.getReader();if(!a)return t;const n=new TextDecoder;let u="",d=!1,f=null;const y={};for(;;){const{done:_e,value:je}=await a.read();if(_e)break;u+=n.decode(je,{stream:!0});const W=u.split(`
`);u=W.pop()||"";for(const F of W){const D=F.trim();if(!D.startsWith("data: "))continue;const m=D.slice(6);if(m==="[DONE]"){const ne=Object.values(y);ne.length>0&&(t.toolCalls=ne,t.toolCallsDone=!0),f!==null&&t.thinkingDur===void 0&&(t.thinkingDur=(Date.now()-f)/1e3,o(M,t.thinkingDur,!0));continue}try{const ne=JSON.parse(m);if(ne.error){const Te=typeof ne.error=="string"?ne.error:ne.error.message||JSON.stringify(ne.error);t.error={summary:"Inference error",details:Te};continue}const He=(pe=ne.choices)==null?void 0:pe[0];if(!He)continue;const $e=He.delta||{},Se=He.finish_reason;if($e.reasoning_content&&(f===null&&(f=Date.now()),t.thinking+=$e.reasoning_content,o(P,e(P)+$e.reasoning_content),d||(d=!0,ze.refresh())),$e.content&&(f!==null&&t.thinkingDur===void 0&&(t.thinkingDur=(Date.now()-f)/1e3,o(M,t.thinkingDur,!0)),t.content+=$e.content,o(X,e(X)+$e.content),d||(d=!0,ze.refresh())),$e.tool_calls)for(const Te of $e.tool_calls){const tt=Te.index??0,rt=y[tt];rt?(S=Te.function)!=null&&S.arguments&&(rt.arguments+=Te.function.arguments):y[tt]={id:Te.id||"",name:((de=Te.function)==null?void 0:de.name)||"",arguments:((ke=Te.function)==null?void 0:ke.arguments)||""}}Se==="tool_calls"&&(t.toolCalls=Object.values(y),t.toolCallsDone=!0)}catch{}}}const p=Object.values(y);return p.length>0&&t.toolCalls.length===0&&(t.toolCalls=p,t.toolCallsDone=!0),t}async function Mt(r){var V,pe,S;const t={content:"",thinking:"",thinkingDur:void 0,toolCalls:[],toolCallsDone:!1,error:null},a=(V=r.body)==null?void 0:V.getReader();if(!a)return t;const n=new TextDecoder;let u="",d=!1,f="";const y={};let p=null;for(;;){const{done:de,value:ke}=await a.read();if(de)break;u+=n.decode(ke,{stream:!0});const _e=u.split(`
`);u=_e.pop()||"";for(const je of _e){const W=je.trim();if(W.startsWith("event: ")){f=W.slice(7).trim();continue}if(!W.startsWith("data: "))continue;const F=W.slice(6);try{const D=JSON.parse(F);if(D.type==="error"||D.error){const m=((pe=D.error)==null?void 0:pe.message)||D.message||JSON.stringify(D);t.error={summary:"Inference error",details:m};continue}switch(f){case"message_start":{d||(d=!0,ze.refresh());break}case"content_block_start":{const m=D.content_block;(m==null?void 0:m.type)==="tool_use"?y[D.index]={id:m.id||"",name:m.name||"",arguments:""}:(m==null?void 0:m.type)==="thinking"&&(re.add(D.index),p===null&&(p=Date.now()));break}case"content_block_delta":{const m=D.delta;if((m==null?void 0:m.type)==="text_delta")re.has(D.index)?(t.thinking+=m.text||"",o(P,e(P)+(m.text||"")),p===null&&(p=Date.now())):(t.content+=m.text||"",o(X,e(X)+(m.text||""))),d||(d=!0,ze.refresh());else if((m==null?void 0:m.type)==="thinking_delta")t.thinking+=m.thinking||"",o(P,e(P)+(m.thinking||"")),p===null&&(p=Date.now());else if((m==null?void 0:m.type)==="input_json_delta"){const ne=y[D.index];ne&&(ne.arguments+=m.partial_json||"")}break}case"content_block_stop":break;case"message_delta":{((S=D.delta)==null?void 0:S.stop_reason)==="tool_use"&&(t.toolCalls=Object.values(y),t.toolCallsDone=!0),p!==null&&t.thinkingDur===void 0&&(t.thinkingDur=(Date.now()-p)/1e3,o(M,t.thinkingDur,!0));break}case"message_stop":{const m=Object.values(y);m.length>0&&t.toolCalls.length===0&&(t.toolCalls=m,t.toolCallsDone=!0);break}}}catch{}}}return t}function Et(r){var t,a,n;return{url:"/v1/chat/completions",body:{model:e(N).model_repo_id,messages:r,stream:!0,temperature:((t=e(N).inference)==null?void 0:t.temperature)??.7,max_tokens:((a=e(N).inference)==null?void 0:a.max_tokens)??4096,top_p:((n=e(N).inference)==null?void 0:n.top_p)??1,...e(we)&&e(U).length>0?{tools:e(U),tool_choice:"auto"}:{}}}}function At(r){var a,n,u;const t=r.filter(d=>d.role!=="system");return{url:"/v1/messages",body:{model:e(N).model_repo_id,max_tokens:((a=e(N).inference)==null?void 0:a.max_tokens)??4096,messages:t,stream:!0,temperature:Math.min(((n=e(N).inference)==null?void 0:n.temperature)??.7,1),top_p:((u=e(N).inference)==null?void 0:u.top_p)??1,...e(we)&&e(U).length>0?{tools:e(U).map(d=>({name:d.function.name,description:d.function.description,input_schema:d.function.parameters}))}:{}}}}async function et(r,t,a=1){var u,d;if(o(he,a,!0),o(be,a>1),!e(N))return!1;const n=[];for(const f of e(_).slice(0,-1))n.push({role:f.role,content:f.content});n.push({role:"user",content:r});try{o(ie,new AbortController,!0);const{url:f,body:y}=e(I)==="anthropic"?At(n):Et(n),p=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wt.token}`},body:JSON.stringify(y),signal:e(ie).signal});if(!p.ok){const _e=p.status>=500&&p.status<600,je=[502,503,504].includes(p.status);if((_e||je)&&a<ge){const W=a*2e3;return await new Promise(F=>setTimeout(F,W)),et(r,t,a+1)}throw new Error(`Server error: ${p.status}`)}const V=e(I)==="anthropic"?await Mt(p):await Pt(p);if(V.error)return o(C,V.error,!0),!1;const pe=3;let S=V,de=0,ke=S.content;for(;S.toolCallsDone&&S.toolCalls.length>0&&de<pe;){de++;for(const F of S.toolCalls){const D={id:F.id,name:F.name,arguments:F.arguments};try{const m=JSON.parse(F.arguments),ne=await Vt.executeTool(F.name,m);D.result=JSON.stringify(ne)}catch{D.error="Tool execution failed"}o(A,[...e(A),D],!0),e(I)==="anthropic"?(n.push({role:"assistant",content:[{type:"tool_use",id:F.id,name:F.name,input:JSON.parse(F.arguments||"{}")}]}),n.push({role:"user",content:[{type:"tool_result",tool_use_id:F.id,content:D.result||D.error||""}]})):(n.push({role:"assistant",content:"",tool_calls:[{id:F.id,type:"function",function:{name:F.name,arguments:F.arguments}}]}),n.push({role:"tool",tool_call_id:F.id,content:D.result||D.error||""}))}const{url:_e,body:je}=e(I)==="anthropic"?At(n):Et(n),W=await fetch(_e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wt.token}`},body:JSON.stringify(je)});if(!W.ok){console.error("Follow-up request failed:",W.status,W.statusText),o(C,{summary:"Tool follow-up failed",details:`Status: ${W.status}`},!0);break}if(S=e(I)==="anthropic"?await Mt(W):await Pt(W),console.log("Follow-up result:",{content:(u=S.content)==null?void 0:u.slice(0,100),thinking:(d=S.thinking)==null?void 0:d.slice(0,100),toolCalls:S.toolCalls.length,error:S.error}),ke+=S.content,o(X,ke,!0),S.error){o(C,S.error,!0);break}}if(de>=pe&&S.toolCallsDone&&(ke+=`

*[Tool call limit reached (3 rounds). Stopping automatic execution.]*`,o(X,ke,!0)),e(X)||e(P)||e(A).length>0){const _e=Nt(e(X));e(_).push({role:"assistant",content:_e,thinking:e(P)||void 0,toolCalls:e(A).length>0?[...e(A)]:void 0,thinkingDuration:e(M)})}return o(he,0),o(be,!1),o(oe,null),!0}catch(f){if(f instanceof DOMException&&f.name==="AbortError")return!0;const y=f instanceof TypeError,p=f instanceof Error?f.message:"Failed to send message",V=p.toLowerCase().includes("failed to fetch")||p.toLowerCase().includes("network")||p.toLowerCase().includes("connection");if((y||V)&&a<ge){const pe=a*2e3;return await new Promise(S=>setTimeout(S,pe)),et(r,t,a+1)}return o(he,0),o(be,!1),o(oe,{content:r,attachments:t},!0),o(C,{summary:"Failed to get response after 3 attempts",details:`The model may still be loading or the request may have failed.

Error: ${p}`},!0),!1}}async function vr(r){var u;if(r.preventDefault(),!e(E).trim()||!e(N)||e(L))return;(u=e(Q))==null||u.collapse(),o(C,null);const t=e(E).trim();o(E,"");const a=await pr(t,e(te)),n=[...e(te)];for(const d of e(te))d.type!=="text"&&URL.revokeObjectURL(d.preview);o(te,[],!0),e(_).push({role:"user",content:t}),o(P,""),o(X,""),o(M,void 0),re.clear(),o(A,[],!0),o(L,!0);try{await et(a,n,1)||e(_).pop()}finally{o(L,!1),o(ie,null)}}function mr(){o(_,[],!0),o(C,null)}async function hr(){var a;if(e(_).length===0)return;const r=[];r.push("# Chat Transcript"),r.push(`Model: ${((a=e(N))==null?void 0:a.model_repo_id)||"Unknown"}`),r.push(`Protocol: ${e(I)==="openai"?"OpenAI":"Anthropic"}`),r.push(`Date: ${new Date().toISOString()}`),r.push("");for(const n of e(_)){if(n.role==="user")r.push("## User"),r.push(typeof n.content=="string"?n.content:"[multipart content]");else{if(r.push("## Assistant"),n.thinking&&(r.push(`### Thinking${n.thinkingDuration?` (${n.thinkingDuration.toFixed(1)}s)`:""}`),r.push(n.thinking),r.push("")),n.toolCalls&&n.toolCalls.length>0){r.push("### Tool Calls");for(const d of n.toolCalls)r.push(`**${d.name}**(${d.arguments})`),d.result&&r.push(`Result: ${d.result}`),d.error&&r.push(`Error: ${d.error}`);r.push("")}const u=typeof n.content=="string"?n.content:"";u&&(r.push("### Response"),r.push(u))}r.push("")}const t=r.join(`
`);await navigator.clipboard.writeText(t),o(We,!0),setTimeout(()=>o(We,!1),2e3)}function gr(){if(e(ie)&&(e(ie).abort(),o(ie,null)),o(L,!1),e(X)||e(P)){const t=Nt(e(X))+`

*[Generation stopped by user]*`;e(_).push({role:"assistant",content:t,thinking:e(P)||void 0,toolCalls:e(A).length>0?[...e(A)]:void 0,thinkingDuration:e(M)})}o(P,""),o(X,""),o(M,void 0),re.clear(),o(A,[],!0)}function _r(r){const t=r.target;o(xe,t.value?parseInt(t.value,10):null,!0),o(_,[],!0),o(C,null);for(const a of e(te))a.type!=="text"&&URL.revokeObjectURL(a.preview);o(te,[],!0)}function xr(r){const t=r.split("/");return t.length>1?t[t.length-1]:r}function Nt(r){let t=r;t=t.replace(/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:\s*\{[^{}]*\}\s*\}/g,""),t=t.replace(/<tool_call>[\s\S]*?<\/tool_call>/g,"");const a=["<|endoftext|>","<|im_end|>","<|im_start|>","<|end|>","<|eot_id|>","<|start_header_id|>","<|end_header_id|>"];for(const n of a)t=t.replaceAll(n,"");return t=t.replace(/\n{3,}/g,`

`),t=t.trim(),t}var pt=Io(),vt=i(pt),Lt=c(i(vt),2),Ut=i(Lt);{let r=le(()=>{var t;return((t=e(xe))==null?void 0:t.toString())??""});Jr(Ut,{onchange:_r,get value(){return e(r)},children:(t,a)=>{var n=vo(),u=Y(n);u.value=u.__value="";var d=c(u,2);dt(d,17,()=>e(Re),f=>f.id,(f,y)=>{var p=po(),V=i(p);s(p);var pe={};J((S,de)=>{fe(V,`${e(y).name??""} (${S??""})`),pe!==(pe=de)&&(p.value=(p.__value=de)??"")},[()=>xr(e(y).model_repo_id??e(y).name),()=>e(y).id.toString()]),l(f,p)}),l(t,n)},$$slots:{default:!0}})}var mt=c(Ut,2),ht=i(mt);ht.__click=()=>{o(I,"openai"),o(_,[],!0),o(C,null)};var It=c(ht,2);It.__click=()=>{o(I,"anthropic"),o(_,[],!0),o(C,null)},s(mt);var yr=c(mt,2);{var br=r=>{var t=ho(),a=Y(t);Ne(a,{variant:"outline",onclick:hr,title:"Copy chat transcript to clipboard",children:(u,d)=>{var f=mo(),y=Y(f);Wr(y,{class:"w-4 h-4 mr-2"});var p=c(y);J(()=>fe(p,` ${e(We)?"Copied!":"Copy"}`)),l(u,f)},$$slots:{default:!0}});var n=c(a,2);Ne(n,{variant:"outline",onclick:mr,children:(u,d)=>{it();var f=yt("Clear Chat");l(u,f)},$$slots:{default:!0}}),l(r,t)};b(yr,r=>{e(_).length>0&&r(br)})}s(Lt),s(vt);var wr=c(vt,2);{var kr=r=>{wt(r,{class:"flex-1 flex items-center justify-center",children:(t,a)=>{var n=go(),u=i(n);Je(u,{class:"w-16 h-16 mx-auto text-muted-foreground mb-4"});var d=c(u,4);Ne(d,{href:"/profiles",children:(f,y)=>{it();var p=yt("Manage Profiles");l(f,p)},$$slots:{default:!0}}),s(n),l(t,n)},$$slots:{default:!0}})},$r=r=>{var t=Le(),a=Y(t);{var n=d=>{wt(d,{class:"flex-1 flex items-center justify-center",children:(f,y)=>{var p=_o(),V=i(p);Je(V,{class:"w-16 h-16 mx-auto text-muted-foreground mb-4"}),it(2),s(p),l(f,p)},$$slots:{default:!0}})},u=d=>{var f=Uo(),y=i(f);{let p=le(()=>e(me)?"ring-2 ring-primary":"");wt(y,{get class(){return`h-full overflow-hidden flex flex-col ${e(p)??""}`},children:(V,pe)=>{var S=Lo(),de=Y(S),ke=i(de);{var _e=g=>{var R=xo(),G=i(R),ue=i(G);Je(ue,{class:"w-12 h-12 mx-auto mb-4"});var Ee=c(ue,2),Oe=c(i(Ee)),Ue=i(Oe,!0);s(Oe),s(Ee);var Be=c(Ee,2),qe=i(Be);s(Be),s(G),s(R),J(()=>{fe(Ue,e(N).name),fe(qe,`Model: ${e(N).model_repo_id??"Unknown"??""} (${e(I)==="openai"?"OpenAI":"Anthropic"} API)`)}),l(g,R)},je=g=>{var R=Oo(),G=Y(R);{var ue=$=>{var v=yo(),x=i(v),j=i(x);Je(j,{class:"w-4 h-4 text-muted-foreground"}),s(x);var B=c(x,2),O=c(i(B),2),ae=i(O,!0);s(O),s(B),s(v),J(()=>fe(ae,e(N).context.system_prompt)),l($,v)},Ee=$=>{var v=Le(),x=Y(v);{var j=B=>{var O=bo(),ae=i(O);Xt(ae,{class:"w-3 h-3"});var Ce=c(ae,4),De=c(Ce,2);De.__click=Pe=>{var K;(K=Pe.currentTarget.closest("#system-prompt-hint"))==null||K.remove()};var Fe=i(De);Gt(Fe,{class:"w-3 h-3"}),s(De),s(O),J(Pe=>ct(Ce,"href",Pe),[()=>zr(`/profiles/${e(N).id}`)]),l(B,O)};b(x,B=>{var O;e(N)&&!((O=e(N).context)!=null&&O.system_prompt)&&B(j)},!0)}l($,v)};b(G,$=>{var v,x;(x=(v=e(N))==null?void 0:v.context)!=null&&x.system_prompt?$(ue):$(Ee,!1)})}var Oe=c(G,2);dt(Oe,16,()=>e(_),$=>$,($,v)=>{var x=So(),j=i(x);{var B=K=>{var k=wo(),ve=i(k);Je(ve,{class:"w-5 h-5 text-primary"}),s(k),l(K,k)};b(j,K=>{v.role==="assistant"&&K(B)})}var O=c(j,2),ae=i(O);{var Ce=K=>{var k=ko(),ve=Y(k);{var xt=Me=>{Yt(Me,{get content(){return v.thinking},get duration(){return v.thinkingDuration}})};b(ve,Me=>{v.thinking&&Me(xt)})}var nt=c(ve,2);{var Ge=Me=>{Zt(Me,{get calls(){return v.toolCalls}})};b(nt,Me=>{v.toolCalls&&v.toolCalls.length>0&&Me(Ge)})}var Cr=c(nt,2);{let Me=le(()=>typeof v.content=="string"?v.content:"");Kt(Cr,{get content(){return e(Me)}})}l(K,k)},De=K=>{var k=$o(),ve=i(k,!0);s(k),J(()=>fe(ve,typeof v.content=="string"?v.content:"")),l(K,k)};b(ae,K=>{v.role==="assistant"?K(Ce):K(De,!1)})}s(O);var Fe=c(O,2);{var Pe=K=>{var k=Co(),ve=i(k);Gr(ve,{class:"w-5 h-5 text-primary-foreground"}),s(k),l(K,k)};b(Fe,K=>{v.role==="user"&&K(Pe)})}s(x),J(()=>{Ke(x,1,`flex gap-3 ${v.role==="user"?"justify-end":""}`),Ke(O,1,`max-w-[80%] rounded-lg px-4 py-2 ${v.role==="user"?"bg-primary text-primary-foreground":"bg-muted"}`)}),l($,x)});var Ue=c(Oe,2);{var Be=$=>{var v=To(),x=i(v);$t(x,{class:"w-4 h-4 animate-spin"});var j=c(x,2),B=i(j);s(j),s(v),J(()=>fe(B,`Connecting to model... (attempt ${e(he)??""}/3)`)),l($,v)};b(Ue,$=>{e(be)&&$(Be)})}var qe=c(Ue,2);{var Xe=$=>{var v=Do(),x=i(v),j=i(x);Je(j,{class:"w-5 h-5 text-primary"}),s(x);var B=c(x,2),O=i(B);{var ae=k=>{{let ve=le(()=>e(M)===void 0);Yt(k,{get content(){return e(P)},get duration(){return e(M)},get streaming(){return e(ve)}})}};b(O,k=>{e(P)&&k(ae)})}var Ce=c(O,2);{var De=k=>{Zt(k,{get calls(){return e(A)}})};b(Ce,k=>{e(A).length>0&&k(De)})}var Fe=c(Ce,2);{var Pe=k=>{Kt(k,{get content(){return e(X)}})},K=k=>{var ve=Le(),xt=Y(ve);{var nt=Ge=>{$t(Ge,{class:"w-5 h-5 animate-spin"})};b(xt,Ge=>{!e(P)&&e(A).length===0&&Ge(nt)},!0)}l(k,ve)};b(Fe,k=>{e(X)?k(Pe):k(K,!1)})}s(B),s(v),l($,v)};b(qe,$=>{e(L)&&$(Xe)})}var ot=c(qe,2);{var Ae=$=>{var v=Ro(),x=i(v),j=i(x);Xt(j,{class:"w-5 h-5 text-destructive"}),s(x);var B=c(x,2),O=i(B);bt(Hr(O,{get summary(){return e(C).summary},get details(){return e(C).details}}),ae=>o(Q,ae,!0),()=>e(Q)),s(B),s(v),l($,v)};b(ot,$=>{e(C)&&$(Ae)})}var Ie=c(ot,2);{var _t=$=>{var v=jo(),x=i(v);Ne(x,{variant:"outline",size:"sm",onclick:async()=>{var j,B;if(e(oe)&&e(N)){(j=e(Q))==null||j.collapse(),o(C,null);const O=typeof e(oe).content=="string"?e(oe).content:((B=e(oe).content.find(ae=>ae.type==="text"))==null?void 0:B.text)||"";e(_).push({role:"user",content:O}),o(P,""),o(X,""),o(M,void 0),re.clear(),o(L,!0);try{await et(e(oe).content,e(oe).attachments,1)||e(_).pop()}finally{o(L,!1)}}},get disabled(){return e(L)},children:(j,B)=>{it();var O=yt("Retry");l(j,O)},$$slots:{default:!0}}),s(v),l($,v)};b(Ie,$=>{e(oe)&&$(_t)})}l(g,R)};b(ke,g=>{e(_).length===0?g(_e):g(je,!1)})}s(de);var W=c(de,2),F=i(W);{var D=g=>{var R=No();dt(R,23,()=>e(te),G=>G.preview,(G,ue,Ee)=>{var Oe=Ao(),Ue=i(Oe);{var Be=Ae=>{var Ie=Po();J(()=>ct(Ie,"src",e(ue).preview)),l(Ae,Ie)},qe=Ae=>{var Ie=Le(),_t=Y(Ie);{var $=x=>{var j=Mo();j.muted=!0,J(()=>ct(j,"src",e(ue).preview)),l(x,j)},v=x=>{var j=Le(),B=Y(j);{var O=ae=>{var Ce=Eo(),De=c(i(Ce),2),Fe=i(De,!0);s(De),s(Ce),J(Pe=>fe(Fe,Pe),[()=>e(ue).preview.split(".").pop()]),l(ae,Ce)};b(B,ae=>{e(ue).type==="text"&&ae(O)},!0)}l(x,j)};b(_t,x=>{e(ue).type==="video"?x($):x(v,!1)},!0)}l(Ae,Ie)};b(Ue,Ae=>{e(ue).type==="image"?Ae(Be):Ae(qe,!1)})}var Xe=c(Ue,2);Xe.__click=()=>lr(e(Ee));var ot=i(Xe);Gt(ot,{class:"w-3 h-3"}),s(Xe),s(Oe),l(G,Oe)}),s(R),l(g,R)};b(F,g=>{e(te).length>0&&g(D)})}var m=c(F,2),ne=i(m);{var He=g=>{{let R=le(()=>e(we)?"default":"ghost"),G=le(()=>e(we)?`Tools enabled (${e(U).length})`:"Enable tools");Ne(g,{type:"button",get variant(){return e(R)},size:"icon",onclick:()=>o(we,!e(we)),get title(){return e(G)},children:(ue,Ee)=>{ar(ue,{class:"w-4 h-4"})},$$slots:{default:!0}})}};b(ne,g=>{e(Ye)&&g(He)})}var $e=c(ne,2);{let g=le(()=>e(L)||e(te).length>=3),R=le(()=>e(I)==="anthropic"&&e(Ze)?"Attach files (video not supported with Anthropic)":"Attach files");Ne($e,{type:"button",variant:"ghost",size:"icon",onclick:()=>{var G;return(G=e(ye))==null?void 0:G.click()},get disabled(){return e(g)},get title(){return e(R)},children:(G,ue)=>{Zr(G,{class:"w-4 h-4"})},$$slots:{default:!0}})}var Se=c($e,2);Ar(Se),Se.__input=g=>{const R=g.currentTarget;R.style.height="auto",R.style.height=Math.min(R.scrollHeight,150)+"px"},Se.__keydown=g=>{if(g.key==="Enter"&&!g.shiftKey){g.preventDefault();const R=g.currentTarget.closest("form");R&&e(E).trim()&&R.requestSubmit()}},bt(Se,g=>o(se,g),()=>e(se));var Te=c(Se,2);{var tt=g=>{Ne(g,{type:"button",variant:"destructive",onclick:gr,title:"Stop generation",children:(R,G)=>{Kr(R,{class:"w-4 h-4"})},$$slots:{default:!0}})},rt=g=>{{let R=le(()=>!e(E).trim());Ne(g,{type:"submit",get disabled(){return e(R)},children:(G,ue)=>{Qr(G,{class:"w-4 h-4"})},$$slots:{default:!0}})}};b(Te,g=>{e(L)?g(tt):g(rt,!1)})}s(m);var gt=c(m,2);gt.__change=cr,bt(gt,g=>o(ye,g),()=>e(ye)),s(W),J(g=>{Se.disabled=e(L),Fr(Se,`max-height: 150px; overflow-y: ${g??""}`),ct(gt,"accept",e(sr))},[()=>e(E).split(`
`).length>4?"auto":"hidden"]),lt("submit",W,vr),Br(Se,()=>e(E),g=>o(E,g)),l(V,S)},$$slots:{default:!0}})}s(f),lt("dragover",f,ur),lt("dragleave",f,fr),lt("drop",f,dr),l(d,f)};b(a,d=>{e(N)?d(u,!1):d(n)},!0)}l(r,t)};b(wr,r=>{e(Re).length===0?r(kr):r($r,!1)})}s(pt),J(()=>{Ke(ht,1,`px-3 py-1 text-xs font-medium rounded-md transition-colors ${e(I)==="openai"?"bg-background shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"}`),Ke(It,1,`px-3 py-1 text-xs font-medium rounded-md transition-colors ${e(I)==="anthropic"?"bg-background shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"}`)}),l(ce,pt),ft(),ee()}Nr(["click","input","keydown","change"]);export{nn as component};
