@workerdeck/web 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{r,R as x,L as d,j as f,A as p}from"./index-p6gzNhpM.js";var N=({code:i,language:e,raw:a,className:u,startLine:n,lineNumbers:g,...m})=>{let{shikiTheme:l}=r.useContext(x),s=d(),[h,t]=r.useState(a);return r.useEffect(()=>{if(!s){t(a);return}let o=s.highlight({code:i,language:e,themes:l},c=>{t(c)});o&&t(o)},[i,e,l,s,a]),f.jsx(p,{className:u,language:e,lineNumbers:g,result:h,startLine:n,...m})};export{N as HighlightedCodeBlockBody};
1
+ import{r,R as x,L as d,j as f,A as p}from"./index-DylL4Hn2.js";var N=({code:i,language:e,raw:a,className:u,startLine:n,lineNumbers:g,...m})=>{let{shikiTheme:l}=r.useContext(x),s=d(),[h,t]=r.useState(a);return r.useEffect(()=>{if(!s){t(a);return}let o=s.highlight({code:i,language:e,themes:l},c=>{t(c)});o&&t(o)},[i,e,l,s,a]),f.jsx(p,{className:u,language:e,lineNumbers:g,result:h,startLine:n,...m})};export{N as HighlightedCodeBlockBody};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ffi-CdNMd84O.js","assets/index-Cw8epeIo.js"])))=>i.map(i=>d[i]);
2
- import{_ as r}from"./index-p6gzNhpM.js";var _={type:"async",importFFI:()=>r(()=>import("./ffi-CdNMd84O.js"),__vite__mapDeps([0,1])).then(t=>t.QuickJSAsyncFFI),importModuleLoader:()=>r(()=>import("./emscripten-module.browser-5SUE27GY-ntU7dq9B.js"),[]).then(t=>t.default)},o=_;export{o as default};
2
+ import{_ as r}from"./index-DylL4Hn2.js";var _={type:"async",importFFI:()=>r(()=>import("./ffi-CdNMd84O.js"),__vite__mapDeps([0,1])).then(t=>t.QuickJSAsyncFFI),importModuleLoader:()=>r(()=>import("./emscripten-module.browser-5SUE27GY-ntU7dq9B.js"),[]).then(t=>t.default)},o=_;export{o as default};
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/module-asyncify-R6PWJ6ZV-V2kApR_G.js","assets/index-Cw8epeIo.js"])))=>i.map(i=>d[i]);
2
- import{_ as v}from"./index-p6gzNhpM.js";function h(t){const e=[];for(const n of t.split("/"))if(!(n===""||n===".")){if(n===".."){e.pop();continue}e.push(n)}return"/"+e.join("/")}function P(t){const e=new Map,n=(o,s)=>{e.set(h(o),s)};for(const[o,s]of Object.entries(t??{}))n(o,s);return{read(o){return e.get(h(o))},write:n,list(o="/"){const s=h(o);return[...e.keys()].filter(u=>s==="/"||u===s||u.startsWith(s+"/")).sort()},snapshot(){return Object.fromEntries(e)}}}async function x(t){let e=S(await t),[n,o,{QuickJSAsyncWASMModule:s}]=await Promise.all([e.importModuleLoader().then(S),e.importFFI(),v(()=>import("./module-asyncify-R6PWJ6ZV-V2kApR_G.js"),__vite__mapDeps([0,1])).then(S)]),u=await n();u.type="async";let r=new o(u);return new s(u,r)}function S(t){return t&&"default"in t&&t.default?t.default&&"default"in t.default&&t.default.default?t.default.default:t.default:t}async function A(t){const e=await t,n="default"in e?e.default:e;return{module:await x(n)}}const b=`
2
+ import{_ as v}from"./index-DylL4Hn2.js";function h(t){const e=[];for(const n of t.split("/"))if(!(n===""||n===".")){if(n===".."){e.pop();continue}e.push(n)}return"/"+e.join("/")}function P(t){const e=new Map,n=(o,s)=>{e.set(h(o),s)};for(const[o,s]of Object.entries(t??{}))n(o,s);return{read(o){return e.get(h(o))},write:n,list(o="/"){const s=h(o);return[...e.keys()].filter(u=>s==="/"||u===s||u.startsWith(s+"/")).sort()},snapshot(){return Object.fromEntries(e)}}}async function x(t){let e=S(await t),[n,o,{QuickJSAsyncWASMModule:s}]=await Promise.all([e.importModuleLoader().then(S),e.importFFI(),v(()=>import("./module-asyncify-R6PWJ6ZV-V2kApR_G.js"),__vite__mapDeps([0,1])).then(S)]),u=await n();u.type="async";let r=new o(u);return new s(u,r)}function S(t){return t&&"default"in t&&t.default?t.default&&"default"in t.default&&t.default.default?t.default.default:t.default:t}async function A(t){const e=await t,n="default"in e?e.default:e;return{module:await x(n)}}const b=`
3
3
  "use strict";
4
4
  (() => {
5
5
  const fmt = (v) => {
@@ -342,7 +342,7 @@ ${LB(e,t)}
342
342
  `})}else if(fi(z)){const ue=z.textContent??"";ue&&(me.push({type:"text",text:ue}),se=!0)}}return!se&&!re?[]:me},[]),L=S.useCallback(W=>{const me=_.current;if(!me)return;ee.current=!0;const se=mB(me);for(;me.firstChild;)me.removeChild(me.firstChild);for(const re of W)if(re.type==="text"){const V=re.text.split(`
343
343
  `);for(let z=0;z<V.length;z++)V[z]&&me.appendChild(document.createTextNode(V[z])),z<V.length-1&&me.appendChild(document.createElement("br"))}else{const V=document.createElement("span");if(V.contentEditable="false",V.dataset.chipTrigger=re.trigger,V.dataset.chipValue=re.value,V.dataset.chipDisplay=re.displayText,re.data!==void 0){const ke=Fd(re.data);ke&&(V.dataset.chipData=ke)}re.autoResolved&&(V.dataset.chipAutoResolved="true");const z=n.find(ke=>ke.char===re.trigger),ue=z?.chipStyle??"pill";V.dataset.chipStyle=ue,V.className=He("prompt-area-chip",ue==="inline"&&"prompt-area-chip--inline",z?.chipClassName),V.textContent=`${re.trigger}${re.displayText}`,V.setAttribute("role","button"),V.setAttribute("tabindex","-1"),me.appendChild(V)}if(me.lastChild&&ph(me.lastChild)){const re=document.createElement("br");re.dataset.sentinel="true",me.appendChild(re)}eS(me,w),se&&gB(me,se),le.current=W,ee.current=!1},[n,w]),ae=S.useCallback((W,me)=>se=>{const re=og(W,me,{value:se.value,displayText:se.displayText,data:se.data});t(re.segments),L(re.segments),c?.({type:"chip",trigger:me.config.char,value:se.value,displayText:se.displayText,...se.data!==void 0?{data:se.data}:{}});const V=_.current;V&&sr(V,re.cursorOffset)},[t,L,c]),ie=S.useCallback(()=>{const W=_.current;if(!W)return;const me=q(),se=Hn(me),re=Hi(W);if(re===null)return;const V=$7(se,re,n);if(U.current=null,$.current=null,V){M(V),P(0);const z=bB(W,V.startOffset);if(z){const ue=z.getBoundingClientRect();(ue.height>0||ue.left>0||ue.top>0)&&Y(ue)}V.config.mode==="dropdown"&&V.config.onSearch&&H(V.query,V.config),V.config.mode==="callback"&&V.config.onActivate&&V.config.onActivate({text:se,cursorPosition:re,insertChip:ae(me,V)})}else M(null),K()},[n,q,ae,K,H]),fe=S.useCallback(()=>{U.current=null,$.current=null,M(null),P(0),K()},[K]),de=BB({editorRef:_,readSegmentsFromDOM:q,onChange:t,renderSegmentsToDOM:L,runTriggerDetection:ie,dismissTrigger:fe,triggers:n,markdownEnabled:w,normalizeBullets:k,onPaste:m,onRawPaste:p,onUndo:b,onRedo:y,onChipAdd:c,onImagePaste:E});S.useEffect(()=>{if(!ee.current&&!Q7(e,le.current)){if(w&&k){const W=G2(e,!0);if(W!==e){t(W);return}}L(e)}},[e,L,w,k,t]);const he=S.useRef(w);S.useEffect(()=>{if(he.current===w)return;he.current=w;const W=k?G2(e,w):e;W!==e?t(W):L(e)},[w,k,L,e,t]),S.useEffect(()=>()=>{I.current&&clearTimeout(I.current)},[]);const ve=S.useCallback(()=>{if(ee.current)return;if(de.isComposing.current){const z=q();le.current=z,t(z);return}const W=_.current,me=W?Hi(W):null;W&&lb(W);const se=q();if(A!=null&&W&&Hn(se).length>A){const z=Hi(W),ue=V7(se,A);le.current=ue,t(ue),L(ue),sr(W,z!=null?Math.min(z,A):A),ie();return}if(w&&k&&W&&me!==null){const z=W7(se,me);if(z){le.current=z.segments,t(z.segments),L(z.segments),sr(W,z.cursorOffset),ie();return}}let re=se,V=null;if(w&&me!==null&&nA(Hn(se))){const z=K2(se);z.edits.length>0&&(re=z.segments,V=X2(me,z.edits))}B.current||(B.current=le.current),le.current=re,t(re),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{B.current&&(de.pushUndo(B.current),B.current=null),I.current=null},HB),W&&(V!==null?(L(re),sr(W,V)):(eS(W,w),me!==null&&sr(W,me))),ie()},[t,q,ie,L,w,k,A,de]),Ue=S.useCallback(W=>{const me=W.target;if(!(me instanceof Node))return;const se=_.current;if(!se)return;let re=me;for(;re&&re!==se;){if(iB(re)){if(W.metaKey||W.ctrlKey){W.preventDefault(),d?.(re.href),window.open(re.href,"_blank","noopener,noreferrer");return}break}if(Xn(re)){const V=re.getBoundingClientRect(),z=document.createElement("span");z.className="prompt-area-chip-ripple";const ue=Math.max(V.width,V.height);z.style.width=`${ue}px`,z.style.height=`${ue}px`,z.style.left=`${W.clientX-V.left-ue/2}px`,z.style.top=`${W.clientY-V.top-ue/2}px`,re.appendChild(z),z.addEventListener("animationend",()=>z.remove());const ke=mh(re);if(ke){const Re=n.find(rt=>rt.char===ke.trigger),qe=Q.current===re;if(Q.current=null,!r&&!qe&&Re?.reopenOnChipClick&&Re.mode==="dropdown"&&Re.onSearch){const rt=Vd(se,re);U.current={chip:ke,segIndex:lg(se,rt)},$.current=re,M({config:Re,startOffset:0,query:""}),P(0),Y(V),H("",Re)}l?.(ke)}return}re=re.parentNode}},[l,d,n,H,r]),Pe=S.useCallback(W=>{const me=W.target,se=_.current;if(!se||!(me instanceof Node)){Q.current=null;return}let re=me;for(;re&&re!==se;){if(Xn(re)){Q.current=$.current===re?re:null;return}re=re.parentNode}Q.current=null},[]),Te=S.useCallback((W,me)=>{const se=q(),re=Vd(W,me);if(re===-1)return!1;const V=lg(W,re),z=se[V],ue=q7(se,V);return t(ue),L(ue),z?.type==="chip"&&f?.(z),!0},[q,t,L,f]),Ie=S.useCallback((W,me)=>{const se=q(),re=Vd(W,me);if(re===-1)return!1;const V=lg(W,re),z=se[V],ue=Y7(se,V);if(!ue)return!1;let ke=0;for(let Re=0;Re<V;Re++){const qe=se[Re];qe.type==="text"?ke+=qe.text.length:ke+=qe.trigger.length+qe.displayText.length}return ke+=ue.revertedText.length,t(ue.segments),L(ue.segments),sr(W,ke),z?.type==="chip"&&f?.(z),!0},[q,t,L,f]),Be=S.useCallback(()=>{const W=_.current;if(!W)return!1;const me=ks();if(!me||!me.collapsed)return!1;const se=me.startContainer,re=me.startOffset;if(se===W&&re>0){const V=W.childNodes[re-1];if(V&&Xn(V))return ab(V)?Ie(W,V):Te(W,V)}if(se.nodeType===Node.TEXT_NODE&&re===0){const V=ob(W,se);if(!V)return!1;let z=V.previousSibling;for(;z&&z.nodeType===Node.TEXT_NODE&&z.textContent==="";)z=z.previousSibling;if(z&&Xn(z))return ab(z)?Ie(W,z):Te(W,z)}return!1},[Te,Ie]),We=S.useCallback(()=>{const W=_.current;if(!W)return!1;const me=ks();if(!me||!me.collapsed)return!1;const se=me.startContainer,re=me.startOffset;if(se===W&&re<W.childNodes.length){const V=W.childNodes[re];if(V&&Xn(V))return Te(W,V)}if(se.nodeType===Node.TEXT_NODE&&re===(se.textContent??"").length){const V=ob(W,se);if(!V)return!1;let z=V.nextSibling;for(;z&&z.nodeType===Node.TEXT_NODE&&z.textContent==="";)z=z.nextSibling;if(z&&Xn(z))return Te(W,z)}return!1},[Te]),Xe=S.useCallback(W=>{const me=q(),se=W.query,re={value:se,label:se},V=W.config.onSelect?.(re)??se,z={value:se,displayText:V||se,autoResolved:!0},ue=og(me,W,z);t(ue.segments),L(ue.segments),c?.({type:"chip",trigger:W.config.char,...z});const ke=_.current;ke&&sr(ke,ue.cursorOffset),fe()},[q,t,L,fe,c]),Me=S.useCallback(W=>{if(!N)return;const me=q(),se=N.config.onSelect?.(W)??W.label,re={value:W.value,displayText:se||W.label,data:W.data},V=U.current;if(V){const ke=_.current;if(ke&&!r){const Re=me[V.segIndex],rt=Re?.type==="chip"&&Re.trigger===V.chip.trigger&&Re.value===V.chip.value?V.segIndex:(()=>{const ot=[];return me.forEach((ut,Fe)=>{ut.type==="chip"&&ut.trigger===V.chip.trigger&&ut.value===V.chip.value&&ot.push(Fe)}),ot.length===1?ot[0]:-1})(),et=rt!==-1?me[rt]:void 0;if(et?.type==="chip"){const ot={type:"chip",trigger:N.config.char,...re};let ut=me.map((Ot,Qt)=>Qt===rt?ot:Ot);const Fe=ut[rt+1],Dt=!Fe||Fe.type!=="text"||Fe.text.length===0;Dt&&(ut=[...ut.slice(0,rt+1),{type:"text",text:" "},...ut.slice(rt+1)]),de.pushUndo(me),t(ut),L(ut),et.value===ot.value&&et.displayText===ot.displayText&&Fd(et.data)===Fd(ot.data)||(f?.(et),c?.(ot));const at=Hn(ut.slice(0,rt+1)).length+(Dt?1:0);sr(ke,at)}}fe(),setTimeout(()=>{_.current?.focus()},0);return}const z=og(me,N,re);t(z.segments),L(z.segments),c?.({type:"chip",trigger:N.config.char,...re});const ue=_.current;ue&&sr(ue,z.cursorOffset),fe(),setTimeout(()=>{_.current?.focus()},0)},[N,q,t,L,fe,c,f,de,r]),Ce=Me;S.useEffect(()=>{const W=U.current;if(!W||!N?.config.reopenOnChipClick)return;const me=J.findIndex(se=>se.value===W.chip.value);me>0&&P(me)},[J,N]);const we=S.useCallback(W=>{const me=(z,ue)=>{let{segments:ke,cursorOffset:Re}=ue;if(w){const qe=K2(ke);ke=qe.segments,Re=X2(Re,qe.edits)}le.current=ke,t(ke),L(ke),sr(z,Re)},se=z=>{if(!w)return!1;const ue=q(),ke=Hi(z);if(ke===null)return!1;const Re=Hn(ue);if(!fl(Re,ke))return!1;const qe=Z7(ue,ke);return qe&&me(z,qe),!0};if((W.metaKey||W.ctrlKey)&&W.key==="z"&&B.current&&(I.current&&(clearTimeout(I.current),I.current=null),de.pushUndo(B.current),B.current=null),de.handleKeyDownForUndoRedo(W))return;if(w&&(W.metaKey||W.ctrlKey)&&!W.shiftKey&&(W.key==="b"||W.key==="i")){W.preventDefault();const z=_.current;if(!z)return;const ue=Ed(z);if(!ue||ue.start===ue.end)return;const ke=W.key==="b"?"**":"*",Re=q();de.pushUndo(Re);const qe=K7(Re,ue.start,ue.end,ke);if(!qe)return;le.current=qe.segments,t(qe.segments),L(qe.segments),tS(z,qe.selectionStart,qe.selectionEnd);return}if(!W.metaKey&&!W.ctrlKey&&!W.altKey&&!W.nativeEvent.isComposing&&W.key.length===1){const z=n.find(ke=>ke.mode==="launch"&&ke.char===W.key),ue=_.current;if(z?.onActivate&&ue){const ke=Hi(ue);if(ke!==null){const Re=q(),qe=Hn(Re);if(hh(qe,ke,z.position)){W.preventDefault(),z.onActivate({text:qe,cursorPosition:ke,insertChip:ae(or(Re,ke,ke,z.char),{config:z,startOffset:ke,query:""})});return}}}}if(N&&N.config.mode==="dropdown"&&(J.length>0||te||G!==null||!!N.config.emptyMessage)){if(W.key==="ArrowDown"){W.preventDefault(),J.length>0&&P(z=>Math.min(z+1,J.length-1));return}if(W.key==="ArrowUp"){W.preventDefault(),J.length>0&&P(z=>Math.max(z-1,0));return}if(W.key==="Enter"||W.key==="Tab"){W.preventDefault();const z=J[O];z&&Me(z);return}if(W.key==="Escape"){W.preventDefault(),fe();return}}if(W.key===" "&&N&&N.config.resolveOnSpace&&N.query.trim().length>0){W.preventDefault(),Xe(N);return}if(w&&W.key==="Tab"&&!N){const z=_.current;if(z){const ue=q(),ke=Hn(ue),Re=Hi(z);if(Re!==null&&fl(ke,Re)){W.preventDefault();const rt=W.shiftKey?tB(ue,Re):eB(ue,Re);rt&&me(z,rt);return}}}const V=z=>{const ue=Ed(z);if(!ue)return;const ke=q();de.pushUndo(ke);const Re=or(ke,ue.start,ue.end,`
344
344
  `);me(z,{segments:Re,cursorOffset:ue.start+1})};if(W.key==="Enter"&&W.shiftKey&&!W.nativeEvent.isComposing){W.preventDefault();const z=_.current;z&&!se(z)&&V(z);return}if(W.key==="Enter"&&!W.shiftKey&&!W.nativeEvent.isComposing){const z=_.current;if(z&&se(z)){W.preventDefault();return}if(C){W.preventDefault(),i?.(q());return}W.preventDefault(),z&&V(z);return}if(W.key==="Escape"&&o){o();return}if((W.key==="Backspace"||W.key==="Delete")&&!W.nativeEvent.isComposing){const z=_.current;if(z){const ue=Ed(z);if(ue&&ue.start!==ue.end){W.preventDefault();const ke=q();de.pushUndo(ke);const Re=or(ke,ue.start,ue.end,"");me(z,{segments:Re,cursorOffset:ue.start}),ie();return}}}if(W.key==="Backspace"){const z=_.current;if(z){const ue=q(),ke=Hi(z);if(w&&ke!==null){const Re=nB(ue,ke);if(Re){W.preventDefault(),me(z,Re),ie();return}}}if(Be()){W.preventDefault(),ie();return}}if(W.key==="Delete"&&We()){W.preventDefault(),ie();return}},[N,J,te,G,O,i,C,o,q,t,L,w,fe,Be,We,Xe,ie,Me,de,n,ae]),je=S.useMemo(()=>({focus:()=>_.current?.focus(),blur:()=>_.current?.blur(),insertChip:W=>{const me=q(),se={type:"chip",...W},re=[...me,se,{type:"text",text:" "}];t(re),L(re),c?.(se)},getPlainText:()=>Hn(q()),clear:()=>{t([]);const W=_.current;if(W)for(;W.firstChild;)W.removeChild(W.firstChild);de.resetUndoHistory(),I.current&&(clearTimeout(I.current),I.current=null),B.current=null},setText:W=>{de.pushUndo(q());const me=F7(W);t(me),L(me);const se=_.current;se&&sr(se,W.length)},appendText:W=>{const me=q();de.pushUndo(me);const se=me[me.length-1],re=se?.type==="text"?[...me.slice(0,-1),{type:"text",text:se.text+W}]:[...me,{type:"text",text:W}];t(re),L(re);const V=_.current;V&&sr(V,Hn(re).length)},getCursorPosition:()=>{const W=_.current;return W?Hi(W):null},setCursorPosition:W=>{const me=_.current;me&&sr(me,W)},setCursorToEnd:()=>{const W=_.current;W&&sr(W,Hn(q()).length)},getSelection:()=>{const W=_.current;return W?Ed(W):null},setSelection:(W,me)=>{const se=_.current;se&&tS(se,W,me)}}),[q,t,L,c,de]),$e=S.useMemo(()=>({onPaste:de.handlePaste,onCopy:de.handleCopy,onCut:de.handleCut,onDrop:de.handleDrop,onDragOver:de.handleDragOver,onCompositionStart:de.handleCompositionStart,onCompositionEnd:de.handleCompositionEnd,onBlur:de.handleBlur}),[de.handlePaste,de.handleCopy,de.handleCut,de.handleDrop,de.handleDragOver,de.handleCompositionStart,de.handleCompositionEnd,de.handleBlur]);return{editorRef:_,activeTrigger:N,suggestions:J,suggestionsLoading:te,suggestionsError:G,selectedSuggestionIndex:O,handleInput:ve,handleKeyDown:we,handleClick:Ue,handleMouseDown:Pe,selectSuggestion:Ce,dismissTrigger:fe,handle:je,triggerRect:D,eventHandlers:$e}}const nS=240;function zB({suggestions:e,loading:t,error:n,emptyMessage:r,selectedIndex:i,onSelect:o,onDismiss:l,triggerRect:c,triggerChar:f}){const d=S.useRef(null),m=S.useRef(null);if(S.useEffect(()=>{m.current?.scrollIntoView({block:"nearest"})},[i]),S.useEffect(()=>{const k=C=>{const A=C.target;d.current&&A instanceof Node&&!d.current.contains(A)&&l()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[l]),!c||e.length===0&&!t&&!n&&!r)return null;const p=Math.min(320,window.innerWidth-16),b=Math.min(c.left,window.innerWidth-p-8),y=window.innerHeight-c.bottom,E=y<nS&&c.top>y,w={position:"fixed",left:`${Math.max(8,b)}px`,zIndex:50,maxWidth:`${p}px`,maxHeight:`${nS}px`,...E?{bottom:`${window.innerHeight-c.top+4}px`}:{top:`${c.bottom+4}px`}};return g.jsx("div",{ref:d,className:He("min-w-[200px] overflow-y-auto","bg-surface rounded-xl border p-2 shadow-md","animate-in fade-in-0 zoom-in-95"),style:w,role:"listbox","aria-label":`${f} suggestions`,children:t?g.jsx("div",{role:"option","aria-selected":!1,className:"text-muted-foreground px-3 py-2 text-sm",children:"Loading suggestions..."}):n?g.jsx("div",{role:"option","aria-selected":!1,className:"text-destructive px-3 py-2 text-sm",children:n}):e.length===0&&r?g.jsx("div",{role:"option","aria-selected":!1,className:"text-muted-foreground px-3 py-2 text-sm",children:r}):e.map((k,C)=>g.jsxs("button",{ref:C===i?m:void 0,type:"button",role:"option","aria-selected":C===i,className:He("text-foreground flex w-full items-start gap-2 rounded-lg px-3 py-2 text-left text-sm","hover:bg-surface-hover cursor-pointer transition-colors",C===i&&"bg-surface-hover"),onMouseDown:A=>{A.preventDefault(),o(k)},children:[k.icon&&g.jsx("span",{className:"mt-0.5 shrink-0",children:k.icon}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"truncate font-medium",children:k.label}),k.description&&g.jsx("div",{className:"text-muted-foreground truncate text-xs",children:k.description})]})]},k.value))})}function FB({texts:e,interval:t=3e3}){const[n,r]=S.useState(0);return S.useEffect(()=>{if(e.length<=1)return;const i=setInterval(()=>{r(o=>(o+1)%e.length)},t);return()=>clearInterval(i)},[e.length,t]),g.jsx("div",{className:"pointer-events-none absolute top-0 left-0 overflow-hidden select-none",style:{color:"var(--prompt-area-placeholder, var(--muted-foreground))"},"aria-hidden":"true",children:g.jsx("div",{className:"animate-in fade-in-0 slide-in-from-top-4 duration-300 ease-in-out",children:e[n]},n)})}function dA({onClick:e,label:t,className:n}){return g.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),e()},className:He("absolute top-0.5 right-0.5 grid h-3.5 w-3.5 cursor-pointer place-items-center","rounded-full bg-black/60 text-white hover:bg-black/80 dark:bg-white/60 dark:text-black dark:hover:bg-white/80","transition-colors",n),"aria-label":t,children:g.jsxs("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[g.jsx("line",{x1:"2.75",y1:"2.75",x2:"7.25",y2:"7.25"}),g.jsx("line",{x1:"7.25",y1:"2.75",x2:"2.75",y2:"7.25"})]})})}function VB({images:e,onRemove:t,onClick:n,className:r}){return e.length===0?null:g.jsx("div",{className:He("flex flex-wrap gap-2",r),role:"list","aria-label":"Attached images",children:e.map(i=>g.jsxs("div",{role:"listitem",className:He("border-border relative h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border",n&&"cursor-pointer"),onClick:()=>n?.(i),children:[g.jsx("img",{src:i.url,alt:i.alt??"Attached image",className:"h-full w-full object-cover"}),i.loading&&g.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:g.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"})}),t&&g.jsx(dA,{onClick:()=>t(i),label:`Remove ${i.alt??"image"}`})]},i.id))})}function Nc({className:e,children:t}){return g.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e,children:t})}const Jh=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}),g.jsx("path",{d:"M14 2v5a1 1 0 0 0 1 1h5"})]}),$B=({className:e})=>g.jsx(Nc,{className:e,children:Jh}),qB=({className:e})=>g.jsxs(Nc,{className:e,children:[Jh,g.jsx("path",{d:"M10 9H8"}),g.jsx("path",{d:"M16 13H8"}),g.jsx("path",{d:"M16 17H8"})]}),YB=({className:e})=>g.jsxs(Nc,{className:e,children:[Jh,g.jsx("path",{d:"M8 13h2"}),g.jsx("path",{d:"M14 13h2"}),g.jsx("path",{d:"M8 17h2"}),g.jsx("path",{d:"M14 17h2"})]}),GB=({className:e})=>g.jsxs(Nc,{className:e,children:[Jh,g.jsx("path",{d:"M10 12.5 8 15l2 2.5"}),g.jsx("path",{d:"m14 12.5 2 2.5-2 2.5"})]}),XB=({className:e})=>g.jsxs(Nc,{className:e,children:[g.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),g.jsx("circle",{cx:"9",cy:"9",r:"2"}),g.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),Td=3;function KB(e){return e?e==="application/pdf"?"pdf":e.includes("spreadsheet")||e==="text/csv"?"spreadsheet":e.startsWith("text/")||e.includes("javascript")||e.includes("json")||e.includes("xml")?"code":e.startsWith("image/")?"image":"default":"default"}const QB={pdf:qB,spreadsheet:YB,code:GB,image:XB,default:$B};function WB(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function ZB(e){const t=e.lastIndexOf(".");return t===-1||t===e.length-1?null:e.slice(t+1).toUpperCase()}function rS({file:e,compact:t,onRemove:n,onClick:r}){const i=ZB(e.name),o=e.size!=null?WB(e.size):null,l=[i,o].filter(Boolean).join(" · ");return g.jsxs("div",{role:"listitem",className:He("border-border relative flex flex-shrink-0 items-center gap-2 overflow-hidden rounded-lg border transition-colors","hover:bg-surface-hover",t?"h-10 w-36 px-2":"h-14 w-48 px-3",r&&"cursor-pointer"),onClick:()=>r?.(e),children:[(()=>{const c=QB[KB(e.type)];return g.jsx(c,{className:He("text-muted-foreground flex-shrink-0",t?"h-4 w-4":"h-5 w-5")})})(),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:He("truncate font-medium",t?"text-xs":"text-sm"),title:e.name,children:e.name}),!t&&l&&g.jsx("div",{className:"text-muted-foreground truncate text-xs",children:l})]}),e.loading&&g.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:g.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"})}),n&&g.jsx(dA,{onClick:()=>n(e),label:`Remove ${e.name}`})]})}function JB({files:e,onRemove:t,onClick:n,className:r}){const[i,o]=S.useState(!1),l=S.useRef(null),c=S.useRef(null);if(S.useEffect(()=>{if(!i)return;const b=y=>{const E=y.target;E instanceof Node&&l.current&&!l.current.contains(E)&&!c.current?.contains(E)&&o(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[i]),e.length===0)return null;const f=e.length>Td,d=f,m=e.length-Td,p=e.slice(0,Td);return g.jsxs("div",{className:He("relative",r),children:[g.jsxs("div",{className:"flex flex-wrap gap-2",role:"list","aria-label":"Attached files",children:[(f?p:e).map(b=>g.jsx(rS,{file:b,compact:d,onRemove:t,onClick:n},b.id)),f&&g.jsx("div",{role:"listitem",children:g.jsx("button",{ref:c,type:"button",onClick:()=>o(b=>!b),className:He("border-border text-muted-foreground hover:bg-surface-hover flex flex-shrink-0 cursor-pointer items-center justify-center rounded-lg border transition-colors",d?"h-10 px-3 text-xs":"h-14 px-4 text-sm"),children:i?"Show less":`+${m} more`})})]}),i&&g.jsx("div",{ref:l,className:He("bg-surface border-border absolute bottom-full left-0 z-10 mb-2 max-h-48 overflow-y-auto rounded-lg border p-2 shadow-lg"),children:g.jsx("div",{className:"flex flex-wrap gap-2",role:"list","aria-label":"More attached files",children:e.slice(Td).map(b=>g.jsx(rS,{file:b,compact:d,onRemove:t,onClick:n},b.id))})})]})}function ej({value:e,onChange:t,triggers:n,placeholder:r,className:i,disabled:o=!1,markdown:l,normalizeBullets:c,onSubmit:f,onEscape:d,onChipClick:m,onChipAdd:p,onChipDelete:b,onLinkClick:y,onPaste:E,onUndo:w,onRedo:k,minHeight:C=80,maxHeight:A,autoFocus:_=!1,autoGrow:N=!1,"aria-label":M,"data-test-id":O,images:P=[],imagePosition:D="above",onImagePaste:Y,onImageRemove:U,onImageClick:$,files:Q=[],filePosition:J="above",onFileRemove:te,onFileClick:G,onKeyDown:H,onBlur:K,onRawPaste:ee,submitOnEnter:le,spellCheck:I,maxLength:B,"aria-describedby":q,ref:L}){const{editorRef:ae,activeTrigger:ie,suggestions:fe,suggestionsLoading:de,suggestionsError:he,selectedSuggestionIndex:ve,handleInput:Ue,handleKeyDown:Pe,handleClick:Te,handleMouseDown:Ie,selectSuggestion:Be,dismissTrigger:We,handle:Xe,triggerRect:Me,eventHandlers:Ce}=UB({value:e,onChange:t,triggers:n,disabled:o,onSubmit:f,onEscape:d,onChipClick:m,onChipAdd:p,onChipDelete:b,onLinkClick:y,onPaste:E,onRawPaste:ee,onUndo:w,onRedo:k,onImagePaste:Y,markdown:l,normalizeBullets:c,submitOnEnter:le,maxLength:B});S.useImperativeHandle(L,()=>Xe,[Xe]),S.useEffect(()=>{_&&ae.current?.focus()},[_,ae]);const[we,je]=S.useState(!1),[$e,W]=S.useState(void 0),me=S.useCallback(()=>{const Fe=ae.current;if(!Fe)return;Fe.style.height="auto";const Dt=Fe.scrollHeight;Fe.style.height=`${Dt}px`,W(Dt)},[ae]),se=S.useCallback(()=>{N&&(je(!0),me())},[N,me]),re=S.useCallback(()=>{Ce.onBlur(),N&&setTimeout(()=>{const Fe=ae.current;if(!Fe)return;const Dt=document.activeElement;Dt&&Fe.parentElement?.contains(Dt)||(je(!1),W(void 0))},fA)},[Ce,N,ae]),V=S.useCallback(()=>{Ue(),N&&we&&me()},[Ue,N,we,me]);S.useEffect(()=>{N&&we&&requestAnimationFrame(()=>me())},[e,N,we,me]);const[z,ue]=S.useState(!1),ke=S.useRef(null);S.useEffect(()=>{if(!N)return;const Fe=()=>{if(we){ue(!1);return}const Bt=ae.current;Bt&&ue(Bt.scrollHeight>Bt.clientHeight)},Dt=we?0:160;return ke.current=setTimeout(Fe,Dt),()=>{ke.current!==null&&clearTimeout(ke.current)}},[N,we,e,ae]);const Re=S.useMemo(()=>{if(!N){const Fe={minHeight:`${C}px`};return A&&(Fe.maxHeight=`${A}px`,Fe.overflowY="auto"),Fe}return{height:we&&$e?`${$e}px`:`${C}px`,minHeight:`${C}px`,maxHeight:A?`${A}px`:"70dvh",overflowY:we?"auto":"hidden",transition:"height 150ms ease-out, min-height 240ms cubic-bezier(0.33, 1, 0.68, 1)"}},[N,C,A,we,$e]),qe=S.useCallback(Fe=>{H?.(Fe),!Fe.defaultPrevented&&Pe(Fe)},[H,Pe]),rt=S.useCallback(Fe=>{K?.(Fe),re()},[K,re]),et=e.length===0||e.length===1&&e[0].type==="text"&&e[0].text==="",ot=P.length>0?g.jsx(VB,{images:P,onRemove:U,onClick:$,className:D==="above"?"pb-2":"pt-2"}):null,ut=Q.length>0?g.jsx(JB,{files:Q,onRemove:te,onClick:G,className:J==="above"?"pb-2":"pt-2"}):null;return g.jsxs("div",{className:He("prompt-area-container relative text-sm leading-relaxed",i),children:[D==="above"&&ot,J==="above"&&ut,g.jsxs("div",{className:"relative",children:[g.jsx("div",{ref:ae,contentEditable:!o,suppressContentEditableWarning:!0,role:"textbox","aria-label":M??"Text input","aria-multiline":"true","aria-disabled":o||void 0,"aria-describedby":q,"data-test-id":O,spellCheck:I,className:He("prompt-area-editor","w-full min-w-0 break-words whitespace-pre-wrap outline-none",o&&"cursor-not-allowed opacity-50"),style:Re,onFocus:se,onInput:N?V:Ue,onKeyDown:qe,onMouseDown:Ie,onClick:Te,onPaste:Ce.onPaste,onCopy:Ce.onCopy,onCut:Ce.onCut,onDrop:Ce.onDrop,onDragOver:Ce.onDragOver,onCompositionStart:Ce.onCompositionStart,onCompositionEnd:Ce.onCompositionEnd,onBlur:rt}),N&&z&&!we&&g.jsx("div",{"aria-hidden":"true",className:"pointer-events-auto absolute right-0 bottom-0 left-0 cursor-pointer",style:{height:"32px"},onClick:()=>ae.current?.focus(),children:g.jsx("div",{className:"h-full w-full",style:{background:"linear-gradient(to bottom, transparent, color-mix(in srgb, var(--prompt-area-surface, var(--background)) 80%, transparent), var(--prompt-area-surface, var(--background)))"}})}),et&&r&&(Array.isArray(r)?g.jsx(FB,{texts:r}):g.jsx("div",{className:"pointer-events-none absolute top-0 left-0 select-none",style:{color:"var(--prompt-area-placeholder, var(--muted-foreground))"},"aria-hidden":"true",children:r}))]}),J==="below"&&ut,D==="below"&&ot,ie&&ie.config.mode==="dropdown"&&g.jsx(zB,{suggestions:fe,loading:de,error:he,emptyMessage:ie.config.emptyMessage,selectedIndex:ve,onSelect:Be,onDismiss:We,triggerRect:Me,triggerChar:ie.config.char})]})}function tj(e={}){const{initialValue:t=[]}=e,[n,r]=S.useState(t),i=S.useRef(null),o=S.useMemo(()=>Hn(n),[n]),l=S.useMemo(()=>n.length===0?!0:n.every(E=>E.type==="text"&&E.text.trim()===""),[n]),c=S.useMemo(()=>n.some(E=>E.type==="chip"),[n]),f=S.useMemo(()=>n.filter(E=>E.type==="chip"),[n]),d=S.useMemo(()=>({ref:i,value:n,onChange:r}),[n]),m=S.useCallback(()=>{i.current?i.current.clear():r([])},[]),p=S.useCallback(()=>i.current?.focus(),[]),b=S.useCallback(()=>i.current?.blur(),[]),y=S.useCallback(E=>i.current?.insertChip(E),[]);return{bind:d,plainText:o,isEmpty:l,hasChips:c,chips:f,clear:m,focus:p,blur:b,insertChip:y}}function nj(e={}){const{char:t="/",position:n="any",...r}=e;return{char:t,position:n,mode:"dropdown",chipStyle:"inline",accessibilityLabel:"command",...r}}const ep=["default","bypassPermissions","dontAsk"];function rj(e,t){return e==="provider"?ep.includes(t):!0}const sj={status:"starting",items:[],pendingApprovals:[],totalCostUsd:0,lastSeq:0},cg="streaming",vd="streaming-thinking";function ij(e){return e===void 0?"":typeof e=="string"?e:e.map(t=>typeof t.text=="string"?t.text:"").filter(Boolean).join(`
345
- `)}function sS(e){return typeof e=="string"?[{type:"text",text:e}]:e}function aj(e){if(e.type==="text")return e.value;try{return JSON.stringify(e.value)}catch{return String(e.value)}}const oj=/^<local-command-(stdout|stderr)>([\s\S]*?)<\/local-command-\1>$/;function Ia(e,t){const n=e.findIndex(i=>i.id===t.id&&i.kind===t.kind);if(n===-1)return[...e,t];const r=[...e];return r[n]=t,r}function lj(e,t){return{...e,status:e.lastSeq===0?t.status:e.status,model:e.model??t.model,permissionMode:e.permissionMode??t.permissionMode,cwd:e.cwd??t.cwd,sdkSessionId:e.sdkSessionId??t.sdkSessionId,engine:t.engine??e.engine}}function uj(e,t){if(t.seq<=e.lastSeq)return e;const n={...e,lastSeq:t.seq};switch(t.type){case"system_init":return{...n,model:t.model,cwd:t.cwd,sdkSessionId:t.sdkSessionId,permissionMode:t.permissionMode};case"status_changed":return{...n,status:t.status,statusDetail:t.detail};case"capabilities":return{...n,models:t.models,commands:t.commands};case"model_changed":return t.model===void 0?n:{...n,model:t.model};case"permission_mode_changed":return{...n,permissionMode:t.mode};case"context_usage":return{...n,contextUsage:t.usage};case"rate_limit":{const r=t.info.rateLimitType;return r?{...n,rateLimits:{...n.rateLimits,[r]:t.info}}:n}case"user_message":{let r=n.items;for(const i of sS(t.message.content))if(i.type==="tool_result"){const o=i,l=o.is_error===!0;r=r.map(c=>c.kind==="tool_call"&&c.id===o.tool_use_id?{...c,status:l?"failed":"settled",result:{text:ij(o.content),isError:l}}:c)}else if(i.type==="text"&&!t.synthetic){const o=i.text,l=oj.exec(o.trim());l?r=Ia(r,{kind:"notice",id:t.uuid??`user-${t.seq}`,level:l[1]==="stderr"?"error":"info",text:l[2].trim()}):r=Ia(r,{kind:"user",id:t.uuid??`user-${t.seq}`,text:o})}return{...n,items:r}}case"assistant_message":{let r=n.items.find(l=>l.kind==="thinking"&&l.id===vd)?.text??"",i=n.items.filter(l=>!(l.kind==="assistant_text"&&l.id===cg)&&!(l.kind==="thinking"&&l.id===vd));return sS(t.message.content).forEach((l,c)=>{const f=`${t.uuid}-${c}`;if(l.type==="text")i=Ia(i,{kind:"assistant_text",id:f,text:l.text,streaming:!1,parentToolUseId:t.parentToolUseId});else if(l.type==="thinking"){const d=l.thinking||r;if(r="",d.trim()==="")return;i=Ia(i,{kind:"thinking",id:f,text:d,parentToolUseId:t.parentToolUseId})}else if(l.type==="tool_use"){const d=l;i=Ia(i,{kind:"tool_call",id:d.id,name:d.name,input:d.input,parentToolUseId:t.parentToolUseId,status:"running"})}}),{...n,items:i}}case"stream_delta":{const r=t.event;if(r.type!=="content_block_delta")return n;if(r.delta?.type==="text_delta"){const i=n.items.find(l=>l.kind==="assistant_text"&&l.id===cg),o={kind:"assistant_text",id:cg,text:(i?.text??"")+(r.delta.text??""),streaming:!0,parentToolUseId:t.parentToolUseId};return{...n,items:Ia(n.items,o)}}if(r.delta?.type==="thinking_delta"){const i=n.items.find(l=>l.kind==="thinking"&&l.id===vd),o={kind:"thinking",id:vd,text:(i?.text??"")+(r.delta.thinking??""),parentToolUseId:t.parentToolUseId};return{...n,items:Ia(n.items,o)}}return n}case"turn_result":return{...n,totalCostUsd:t.totalCostUsd,items:[...n.items,{kind:"turn_result",id:`turn-${t.seq}`,subtype:t.subtype,isError:t.isError,durationMs:t.durationMs,totalCostUsd:t.totalCostUsd,errors:t.errors}]};case"permission_requested":return{...n,pendingApprovals:[...n.pendingApprovals,t.request]};case"permission_resolved":return{...n,pendingApprovals:n.pendingApprovals.filter(r=>r.id!==t.requestId)};case"execution_dispatched":return{...n,items:n.items.map(r=>r.kind==="tool_call"&&r.id===t.executionId?{...r,status:t.deferred?"deferred":"pending",executionId:t.executionId,backend:t.backend}:r)};case"execution_result":return{...n,items:n.items.map(r=>r.kind==="tool_call"&&r.id===t.executionId?{...r,status:"settled",executionId:t.executionId,result:{text:aj(t.output),isError:!1},logs:t.logs??r.logs}:r)};case"execution_failed":return{...n,items:n.items.map(r=>r.kind==="tool_call"&&r.id===t.executionId?{...r,status:"failed",executionId:t.executionId,result:{text:`${t.reason}: ${t.error}`,isError:!0},logs:t.logs??r.logs}:r)};case"file_delivered":return{...n,items:[...n.items,{kind:"file_delivered",id:`file-${t.seq}`,path:t.path,bytes:t.bytes,description:t.description}]};case"session_error":return{...n,items:[...n.items,{kind:"notice",id:`err-${t.seq}`,level:"error",text:t.message}]};case"session_closed":return{...n,items:[...n.items,{kind:"notice",id:`closed-${t.seq}`,level:"info",text:`Session closed (${t.reason})`}]};case"sdk_event":default:return n}}function cj(e,t){return t.type==="attached"?lj(e,t.session):uj(e,t)}function fj(e,t,n){const[r,i]=S.useReducer(cj,sj),[o,l]=S.useState(!1),[c,f]=S.useState(),d=S.useRef(null),m=S.useRef(n?.onProtocolError);return m.current=n?.onProtocolError,S.useEffect(()=>{if(!t)return;const p=e.attach(t);d.current=p,f(p);const b=p.on("event",k=>i(k)),y=p.on("attached",k=>i(k)),E=p.on("connectionChange",l),w=p.on("protocolError",k=>{m.current?.(k)});return()=>{b(),y(),E(),w(),p.detach(),d.current=null,f(void 0)}},[e,t]),S.useMemo(()=>({state:r,connected:o,handle:c,send:p=>d.current?.send(p),approve:(p,b)=>d.current?.approve(p,b),deny:(p,b)=>d.current?.deny(p,b),interrupt:()=>d.current?.interrupt(),setPermissionMode:p=>d.current?.setPermissionMode(p),setModel:p=>d.current?.setModel(p),closeSession:()=>d.current?.closeSession()}),[r,o,c])}const dj="modulepreload",hj=function(e){return"/"+e},iS={},hc=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),f=c?.nonce||c?.getAttribute("nonce");i=l(n.map(d=>{if(d=hj(d),d in iS)return;iS[d]=!0;const m=d.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const b=document.createElement("link");if(b.rel=m?"stylesheet":dj,m||(b.as="script"),b.crossOrigin="",b.href=d,f&&b.setAttribute("nonce",f),document.head.appendChild(b),m)return new Promise((y,E)=>{b.addEventListener("load",y),b.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return i.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};function pj(e,t={}){const n=new Map;let r,i=!1;const o=m=>t.onExecution?.(m),l=(m,p,b,y)=>{e.sendToolCallError(m.executionId,p,b),o({executionId:m.executionId,toolName:m.toolName,status:"failed",reason:p,startedAt:y,endedAt:Date.now()})},c=async m=>{const p=Date.now();if(!(t.tools??["eval_script"]).includes(m.toolName)){l(m,"unsupported_tool",`this client does not execute '${m.toolName}'`,p);return}const y=m.input?.script;if(typeof y!="string"){l(m,"invalid_input","expected a string `script` input",p);return}const E=new AbortController;n.set(m.executionId,E),o({executionId:m.executionId,toolName:m.toolName,status:"running",startedAt:p});try{const w=await hc(()=>import("./index-CkFmqlop.js"),[]),k=w.createVfs(m.vfsSeed),C=Math.min(m.limits?.timeoutMs??Number.POSITIVE_INFINITY,t.timeoutMs??5e3),A=Math.min(m.limits?.memoryLimitBytes??Number.POSITIVE_INFINITY,t.memoryLimitBytes??64*1024*1024),_=t.execute?await t.execute({script:y,vfs:k,timeoutMs:C,memoryLimitBytes:A,signal:E.signal}):await(async()=>(r??=(t.loadEngine??mj)(),w.runScript(await r,{script:y,vfs:k,timeoutMs:C,memoryLimitBytes:A,signal:E.signal,fetchText:t.fetchText})))();if(i||!n.has(m.executionId))return;const N=_.logs.map(M=>`[${M.level}] ${M.text}`);_.ok?(e.sendToolCallResult(m.executionId,{type:"json",value:_.value},N),o({executionId:m.executionId,toolName:m.toolName,status:"settled",startedAt:p,endedAt:Date.now()})):(e.sendToolCallError(m.executionId,_.reason,_.error,N),o({executionId:m.executionId,toolName:m.toolName,status:"failed",reason:_.reason,startedAt:p,endedAt:Date.now()}))}catch(w){if(i||!n.has(m.executionId))return;l(m,"host_error",w instanceof Error?w.message:String(w),p)}finally{n.delete(m.executionId)}},f=e.on("toolCallRequest",m=>void c(m)),d=e.on("toolCallCanceled",({executionId:m,reason:p})=>{const b=n.get(m);b&&(b.abort(),n.delete(m),o({executionId:m,toolName:"",status:"canceled",reason:p,startedAt:Date.now(),endedAt:Date.now()}))});return{dispose:()=>{i=!0,f(),d();for(const m of n.values())m.abort();n.clear()}}}async function mj(){const[e,t]=await Promise.all([hc(()=>import("./index-CkFmqlop.js"),[]),hc(()=>import("./index-d8zBDtNE.js"),[])]);return e.loadEngine(t)}function gj(e,t={}){const[n,r]=S.useState([]),i=S.useRef(t);return i.current=t,S.useEffect(()=>{if(!e||t.enabled===!1)return;const o=pj(e,{get tools(){return i.current.tools},get timeoutMs(){return i.current.timeoutMs},get memoryLimitBytes(){return i.current.memoryLimitBytes},get loadEngine(){return i.current.loadEngine},get execute(){return i.current.execute},get fetchText(){return i.current.fetchText},onExecution:l=>{i.current.onExecution?.(l);const c=i.current.historyLimit??50;r(f=>[...f.filter(d=>d.executionId!==l.executionId),l].slice(-c))}});return()=>o.dispose()},[e,t.enabled]),{executions:n}}const bj=e=>e.replace(/\s*\(MCP\)$/i,"");function xj({onSend:e,onInterrupt:t,busy:n,disabled:r,placeholder:i="Message Claude…",commands:o,toolbar:l,className:c}){const{bind:f,plainText:d,isEmpty:m,clear:p,focus:b}=tj(),y=S.useMemo(()=>{if(!o||o.length===0)return;const k=new Set,C=o.flatMap(A=>{const _=bj(A.name);return k.has(_)?[]:(k.add(_),[{...A,name:_}])});return[nj({onSearch:A=>{const _=A.toLowerCase(),N=C.flatMap(M=>{const O=[M.name,...M.aliases??[]].map(D=>D.toLowerCase()),P=O.some(D=>D.startsWith(_))?2:O.some(D=>D.includes(_))?1:0;return P===0?[]:[{c:M,score:P}]});return N.sort((M,O)=>O.score-M.score),N.map(({c:M})=>({value:M.name,label:`/${M.name}${M.argumentHint?` ${M.argumentHint}`:""}`,description:M.description}))},onSelect:A=>A.value,chipClassName:"font-mono"})]},[o]),E=()=>{const k=d.trim();!k||r||(e(k),p(),b())},w=!r&&!m;return g.jsxs("div",{"data-slot":"composer",className:He("px-3 pb-3",c),children:[g.jsxs("div",{className:He("mx-auto w-full max-w-3xl overflow-hidden rounded-lg border border-border bg-bg shadow-(--shadow-xs)","transition-colors focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/30",r&&"opacity-60"),children:[g.jsx(ej,{...f,triggers:y,onSubmit:E,disabled:r,placeholder:r?"Session ended":i,minHeight:28,maxHeight:192,"aria-label":"Message Claude",className:"px-3 pt-2.5 pb-1 text-body-sm text-text"}),g.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-2",children:[g.jsx("div",{className:"flex min-w-0 items-center gap-1",children:l}),n?g.jsx($t,{variant:"outline",size:"icon-sm","aria-label":"Interrupt",className:"rounded-full",onClick:t,children:g.jsx(f9,{className:"size-3"})}):g.jsx($t,{size:"icon-sm","aria-label":"Send",className:"rounded-full",disabled:!w,onClick:E,children:g.jsx(EP,{className:"size-4"})})]})]}),g.jsx("div",{className:"mx-auto mt-1 w-full max-w-3xl text-center text-label text-fg-4",children:"Enter to send · Shift+Enter for a new line"})]})}const ub=e=>e==="default";function yj(e,t){if(!t)return;const n=t.replace(/\[.*\]$/,""),r=e.filter(i=>!ub(i.value));return r.find(i=>i.value===n)??r.find(i=>n.includes(i.value)||i.value.includes(n))}function hA({models:e,model:t,onModelChange:n,variant:r="toolbar",disabled:i,className:o}){const l=yj(e,t)??(t?void 0:e.find(c=>ub(c.value)));return g.jsxs(Cc,{items:e.map(c=>({value:c.value,label:c.displayName})),value:l?.value??null,onValueChange:c=>{typeof c!="string"||c===l?.value||n(ub(c)?void 0:c)},disabled:i,children:[g.jsx(kc,{"aria-label":"Model",className:He(r==="toolbar"&&"h-6 max-w-56 border-transparent bg-transparent text-fg-3 hover:bg-surface-hover",o),children:g.jsx("span",{className:He("truncate",r==="toolbar"&&"font-mono text-label"),children:g.jsx(wc,{placeholder:t??"model"})})}),g.jsx(Ac,{className:"min-w-72",children:e.map(c=>g.jsxs(cl,{value:c.value,children:[g.jsx(ul,{children:g.jsx("span",{className:"font-medium",children:c.displayName})}),c.description?g.jsx("span",{className:"text-label text-fg-4",children:c.description}):null]},c.value))})]})}const cb=[{value:"default",label:"default",description:"ask for approval"},{value:"acceptEdits",label:"acceptEdits",description:"auto-approve file edits"},{value:"plan",label:"plan",description:"read-only planning"},{value:"auto",label:"auto",description:"model decides when to ask"},{value:"dontAsk",label:"dontAsk",description:"never ask — deny unapproved"},{value:"bypassPermissions",label:"bypassPermissions",description:"no prompts (danger)",dangerous:!0}];function Rc({mode:e,onModeChange:t,modes:n,variant:r="toolbar",disabled:i,className:o}){const l=e==="bypassPermissions",c=n?cb.filter(f=>n.includes(f.value)):cb;return g.jsxs(Cc,{items:c.map(f=>({value:f.value,label:f.label})),value:e??null,onValueChange:f=>{typeof f=="string"&&f!==e&&t(f)},disabled:i,children:[g.jsx(kc,{"aria-label":"Permission mode",className:He(r==="toolbar"&&"h-6 max-w-44 border-transparent bg-transparent hover:bg-surface-hover",l?"text-danger":r==="toolbar"?"text-fg-3":void 0,o),children:g.jsx("span",{className:He("truncate",r==="toolbar"&&"font-mono text-label"),children:g.jsx(wc,{placeholder:"permissions"})})}),g.jsx(Ac,{className:"min-w-56",children:c.map(f=>g.jsxs(cl,{value:f.value,children:[g.jsx(ul,{children:g.jsx("span",{className:He("font-medium",f.dangerous&&"text-danger"),children:f.label})}),g.jsx("span",{className:He("text-label",f.dangerous?"text-danger/80":"text-fg-4"),children:f.description})]},f.value))})]})}function Ej({request:e,onApprove:t,onDeny:n,className:r}){const[i,o]=S.useState(!1);return g.jsx("div",{"data-slot":"permission-prompt",className:He("rounded-lg border border-warning/40 bg-warning-bg p-3",r),children:g.jsxs("div",{className:"flex items-start gap-2.5",children:[g.jsx(o9,{className:"mt-0.5 size-4 shrink-0 text-warning"}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"text-body-sm font-medium text-fg-1",children:e.title??`Claude wants to use ${e.toolName}`}),e.description?g.jsx("div",{className:"mt-0.5 text-label text-fg-3",children:e.description}):null,g.jsxs("button",{type:"button",className:"mt-1 font-mono text-label text-fg-3 underline-offset-2 hover:underline",onClick:()=>o(l=>!l),children:[i?"Hide":"Show"," ",e.toolName," input"]}),i?g.jsx("pre",{className:"mt-1.5 max-h-48 overflow-auto rounded-md bg-code-bg px-2.5 py-1.5 font-mono text-label whitespace-pre-wrap text-fg-2",children:JSON.stringify(e.input,null,2)}):null]}),g.jsxs("div",{className:"flex shrink-0 gap-1.5",children:[g.jsx($t,{size:"sm",onClick:()=>t(e.id),children:"Allow"}),g.jsx($t,{size:"sm",variant:"outline",onClick:()=>n(e.id,"Denied by user"),children:"Deny"})]})]})})}const aS=[{value:"auto",label:"Auto-answer",description:"pick each question’s recommended option"},{value:"ask",label:"Ask",description:"wait for a watcher or webhook controller to answer"},{value:"deny",label:"Disabled",description:"the agent is told to decide on its own"}];function pA(e){return(Array.isArray(e.questions)?e.questions:[]).flatMap(n=>{const r=n;if(typeof r.question!="string"||!Array.isArray(r.options))return[];const i=r.options.filter(o=>typeof o?.label=="string");return i.length===0?[]:[{question:r.question,header:typeof r.header=="string"?r.header:"",options:i,multiSelect:r.multiSelect===!0}]})}const Cu={labels:[],other:"",otherActive:!1};function oS(e){const t=[...e.labels];return e.otherActive&&e.other.trim()&&t.push(e.other.trim()),t.join(", ")}function Tj({request:e,onAnswer:t,onDismiss:n,className:r}){const i=pA(e.input),[o,l]=S.useState(()=>i.map(()=>Cu)),c=(p,b)=>{l(y=>y.map((E,w)=>w===p?{...E,...b}:E))},f=(p,b,y)=>{const E=o[p]??Cu;y?c(p,{labels:E.labels.includes(b)?E.labels.filter(w=>w!==b):[...E.labels,b]}):c(p,{labels:E.labels[0]===b?[]:[b],otherActive:!1})},d=i.every((p,b)=>oS(o[b]??Cu)!==""),m=()=>{const p={};i.forEach((b,y)=>{p[b.question]=oS(o[y]??Cu)}),t(e.id,{...e.input,answers:p})};return g.jsx("div",{"data-slot":"question-prompt",className:He("rounded-lg border border-info/40 bg-info-bg p-3",r),children:g.jsxs("div",{className:"flex items-start gap-2.5",children:[g.jsx(GP,{className:"mt-0.5 size-4 shrink-0 text-info"}),g.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-3",children:[i.map((p,b)=>{const y=o[b]??Cu;return g.jsxs("div",{className:"flex flex-col gap-1.5",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[p.header?g.jsx(ts,{variant:"info",children:p.header}):null,g.jsx("span",{className:"text-body-sm font-medium text-fg-1",children:p.question})]}),g.jsxs("div",{className:"flex flex-col gap-1",children:[p.options.map(E=>{const w=y.labels.includes(E.label);return g.jsxs("button",{type:"button",onClick:()=>f(b,E.label,p.multiSelect===!0),className:He("rounded-md border px-2.5 py-1.5 text-left transition-colors",w?"border-info bg-bg":"border-border bg-bg/50 hover:border-border-strong hover:bg-bg"),children:[g.jsx("span",{className:"block text-body-sm font-medium text-fg-1",children:E.label}),E.description?g.jsx("span",{className:"block text-label text-fg-4",children:E.description}):null,w&&E.preview?g.jsx("pre",{className:"mt-1.5 max-h-40 overflow-auto rounded-md bg-code-bg px-2.5 py-1.5 font-mono text-label whitespace-pre-wrap text-fg-2",children:E.preview}):null]},E.label)}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("button",{type:"button",onClick:()=>c(b,{otherActive:!y.otherActive}),className:He("shrink-0 rounded-md border px-2.5 py-1.5 text-body-sm font-medium transition-colors",y.otherActive?"border-info bg-bg text-fg-1":"border-border bg-bg/50 text-fg-3 hover:border-border-strong hover:bg-bg"),children:"Other…"}),y.otherActive?g.jsx(bn,{autoFocus:!0,value:y.other,onChange:E=>c(b,{other:E.target.value}),placeholder:"Type your own answer",className:"flex-1"}):null]})]})]},b)}),g.jsx("div",{children:g.jsx($t,{size:"sm",onClick:m,disabled:!d,children:"Answer"})})]}),g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Dismiss question",className:"shrink-0",onClick:()=>n(e.id,"Question dismissed by user"),children:g.jsx(V3,{className:"size-3.5"})})]})})}function tp(e){return e===void 0||Number.isNaN(e)?"—":e===0?"$0.00":e<.01?"<$0.01":`$${e.toFixed(2)}`}function vj(e){if(e<1e3)return`${Math.round(e)}ms`;const t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`}function Qi(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))}function Sj(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function lS(e,t=Date.now()){const n=e-t;if(n<=0)return"now";const r=Math.ceil(n/6e4);if(r<1)return"<1m";if(r<60)return`${r}m`;const i=Math.floor(r/1440);return i>=1?`${i}d ${Math.floor(r%1440/60)}h`:`${Math.floor(r/60)}h ${r%60}m`}function R1(e,t=Date.now()){if(!e)return"—";const n=Math.max(0,t-e),r=Math.floor(n/1e3);if(r<60)return"just now";const i=Math.floor(r/60);if(i<60)return`${i}m ago`;const o=Math.floor(i/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Cj(e,t=80){if(e==null)return"";if(typeof e=="object"){const r=e,i=r.command??r.file_path??r.path??r.url??r.pattern??r.query??r.description;if(typeof i=="string")return i.length>t?i.slice(0,t-1)+"…":i}const n=JSON.stringify(e)??"";return n.length>t?n.slice(0,t-1)+"…":n}const mA={starting:{label:"Starting",variant:"info",busy:!0},running:{label:"Running",variant:"info",busy:!0},awaiting_approval:{label:"Needs approval",variant:"warning",busy:!0},idle:{label:"Idle",variant:"success",busy:!1},parked:{label:"Parked",variant:"accent",busy:!1},failed:{label:"Failed",variant:"danger",busy:!1},closed:{label:"Closed",variant:"neutral",busy:!1}};function wj(e=3e4){const[t,n]=S.useState(()=>Date.now());return S.useEffect(()=>{const r=setInterval(()=>n(Date.now()),e);return()=>clearInterval(r)},[e]),t}const gA=e=>e>=95?"text-danger":e>=80?"text-warning":"text-fg-3",kj=e=>typeof CSS<"u"&&CSS.supports("color",e)?e:void 0;function Aj({usage:e}){return g.jsx(Q3,{content:g.jsxs("div",{className:"flex min-w-44 flex-col gap-1 py-0.5",children:[e.categories.map(t=>g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"size-2 shrink-0 rounded-full bg-fg-4",style:kj(t.color)?{backgroundColor:t.color}:void 0}),g.jsx("span",{className:"flex-1",children:t.name}),g.jsx("span",{className:"font-mono text-fg-3",children:Qi(t.tokens)})]},t.name)),g.jsxs("div",{className:"mt-0.5 flex items-center justify-between gap-2 border-t border-border pt-1",children:[g.jsx("span",{children:"Total"}),g.jsxs("span",{className:"font-mono text-fg-3",children:[Qi(e.totalTokens)," / ",Qi(e.maxTokens)," (",e.percentage.toFixed(0),"%)"]})]})]}),children:g.jsxs("span",{className:He("inline-flex cursor-default items-center gap-1 font-mono text-label",gA(e.percentage)),children:["Ctx ",Qi(e.totalTokens)]})})}function uS({label:e,info:t,now:n}){const r=t.utilization,i=t.resetsAt!==void 0?t.resetsAt*1e3:void 0;return g.jsx(Q3,{content:g.jsxs("div",{className:"flex min-w-36 flex-col gap-1 py-0.5",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("span",{children:[e," usage"]}),g.jsx("span",{className:"font-mono text-fg-3",children:r!==void 0?`${r.toFixed(1)}%`:"—"})]}),i!==void 0?g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("span",{children:"Resets in"}),g.jsx("span",{className:"font-mono text-fg-3",children:lS(i,n)})]}):null,t.isUsingOverage?g.jsx("div",{className:"text-warning",children:"Using overage"}):null,t.status==="rejected"?g.jsx("div",{className:"text-danger",children:"Limit reached"}):null]}),children:g.jsxs("span",{className:He("inline-flex cursor-default items-center gap-1 font-mono text-label",t.status==="rejected"?"text-danger":gA(r??0)),children:[g.jsx(Z3,{value:r??0}),e,r!==void 0?` ${r.toFixed(0)}%`:"",i!==void 0?g.jsxs("span",{className:"text-fg-4",children:["· ",lS(i,n)]}):null]})})}function _j({state:e,connected:t,className:n}){const r=mA[e.status],i=wj(),o=e.rateLimits?.five_hour,l=e.rateLimits?.seven_day;return g.jsxs("div",{"data-slot":"status-bar",className:He("flex items-center gap-3 border-b border-border bg-surface px-3 py-2",n),children:[g.jsxs(ts,{variant:r.variant,dot:!r.busy,children:[r.busy?g.jsx(ci,{className:"size-3 text-current"}):null,r.label]}),e.contextUsage?g.jsx(Aj,{usage:e.contextUsage}):null,o?g.jsx(uS,{label:"Session",info:o,now:i}):null,l?g.jsx(uS,{label:"Weekly",info:l,now:i}):null,g.jsx("span",{className:"flex-1"}),t?null:g.jsxs("span",{className:"inline-flex items-center gap-1 text-label text-warning",children:[g.jsx(E9,{className:"size-3"})," reconnecting…"]}),g.jsx("span",{className:"font-mono text-label text-fg-3",children:tp(e.totalCostUsd)})]})}/*!---------------------------------------------------------------------------------------------
345
+ `)}function sS(e){return typeof e=="string"?[{type:"text",text:e}]:e}function aj(e){if(e.type==="text")return e.value;try{return JSON.stringify(e.value)}catch{return String(e.value)}}const oj=/^<local-command-(stdout|stderr)>([\s\S]*?)<\/local-command-\1>$/;function Ia(e,t){const n=e.findIndex(i=>i.id===t.id&&i.kind===t.kind);if(n===-1)return[...e,t];const r=[...e];return r[n]=t,r}function lj(e,t){return{...e,status:e.lastSeq===0?t.status:e.status,model:e.model??t.model,permissionMode:e.permissionMode??t.permissionMode,cwd:e.cwd??t.cwd,sdkSessionId:e.sdkSessionId??t.sdkSessionId,engine:t.engine??e.engine}}function uj(e,t){if(t.seq<=e.lastSeq)return e;const n={...e,lastSeq:t.seq};switch(t.type){case"system_init":return{...n,model:t.model,cwd:t.cwd,sdkSessionId:t.sdkSessionId,permissionMode:t.permissionMode};case"status_changed":return{...n,status:t.status,statusDetail:t.detail};case"capabilities":return{...n,models:t.models,commands:t.commands};case"model_changed":return t.model===void 0?n:{...n,model:t.model};case"permission_mode_changed":return{...n,permissionMode:t.mode};case"context_usage":return{...n,contextUsage:t.usage};case"rate_limit":{const r=t.info.rateLimitType;return r?{...n,rateLimits:{...n.rateLimits,[r]:t.info}}:n}case"user_message":{let r=n.items;for(const i of sS(t.message.content))if(i.type==="tool_result"){const o=i,l=o.is_error===!0;r=r.map(c=>c.kind==="tool_call"&&c.id===o.tool_use_id?{...c,status:l?"failed":"settled",result:{text:ij(o.content),isError:l}}:c)}else if(i.type==="text"&&!t.synthetic){const o=i.text,l=oj.exec(o.trim());l?r=Ia(r,{kind:"notice",id:t.uuid??`user-${t.seq}`,level:l[1]==="stderr"?"error":"info",text:l[2].trim()}):r=Ia(r,{kind:"user",id:t.uuid??`user-${t.seq}`,text:o})}return{...n,items:r}}case"assistant_message":{let r=n.items.find(l=>l.kind==="thinking"&&l.id===vd)?.text??"",i=n.items.filter(l=>!(l.kind==="assistant_text"&&l.id===cg)&&!(l.kind==="thinking"&&l.id===vd));return sS(t.message.content).forEach((l,c)=>{const f=`${t.uuid}-${c}`;if(l.type==="text")i=Ia(i,{kind:"assistant_text",id:f,text:l.text,streaming:!1,parentToolUseId:t.parentToolUseId});else if(l.type==="thinking"){const d=l.thinking||r;if(r="",d.trim()==="")return;i=Ia(i,{kind:"thinking",id:f,text:d,parentToolUseId:t.parentToolUseId})}else if(l.type==="tool_use"){const d=l;i=Ia(i,{kind:"tool_call",id:d.id,name:d.name,input:d.input,parentToolUseId:t.parentToolUseId,status:"running"})}}),{...n,items:i}}case"stream_delta":{const r=t.event;if(r.type!=="content_block_delta")return n;if(r.delta?.type==="text_delta"){const i=n.items.find(l=>l.kind==="assistant_text"&&l.id===cg),o={kind:"assistant_text",id:cg,text:(i?.text??"")+(r.delta.text??""),streaming:!0,parentToolUseId:t.parentToolUseId};return{...n,items:Ia(n.items,o)}}if(r.delta?.type==="thinking_delta"){const i=n.items.find(l=>l.kind==="thinking"&&l.id===vd),o={kind:"thinking",id:vd,text:(i?.text??"")+(r.delta.thinking??""),parentToolUseId:t.parentToolUseId};return{...n,items:Ia(n.items,o)}}return n}case"turn_result":return{...n,totalCostUsd:t.totalCostUsd,items:[...n.items,{kind:"turn_result",id:`turn-${t.seq}`,subtype:t.subtype,isError:t.isError,durationMs:t.durationMs,totalCostUsd:t.totalCostUsd,errors:t.errors}]};case"permission_requested":return{...n,pendingApprovals:[...n.pendingApprovals,t.request]};case"permission_resolved":return{...n,pendingApprovals:n.pendingApprovals.filter(r=>r.id!==t.requestId)};case"execution_dispatched":return{...n,items:n.items.map(r=>r.kind==="tool_call"&&r.id===t.executionId?{...r,status:t.deferred?"deferred":"pending",executionId:t.executionId,backend:t.backend}:r)};case"execution_result":return{...n,items:n.items.map(r=>r.kind==="tool_call"&&r.id===t.executionId?{...r,status:"settled",executionId:t.executionId,result:{text:aj(t.output),isError:!1},logs:t.logs??r.logs}:r)};case"execution_failed":return{...n,items:n.items.map(r=>r.kind==="tool_call"&&r.id===t.executionId?{...r,status:"failed",executionId:t.executionId,result:{text:`${t.reason}: ${t.error}`,isError:!0},logs:t.logs??r.logs}:r)};case"file_delivered":return{...n,items:[...n.items,{kind:"file_delivered",id:`file-${t.seq}`,path:t.path,bytes:t.bytes,description:t.description}]};case"session_error":return{...n,items:[...n.items,{kind:"notice",id:`err-${t.seq}`,level:"error",text:t.message}]};case"session_closed":return{...n,items:[...n.items,{kind:"notice",id:`closed-${t.seq}`,level:"info",text:`Session closed (${t.reason})`}]};case"sdk_event":default:return n}}function cj(e,t){return t.type==="attached"?lj(e,t.session):uj(e,t)}function fj(e,t,n){const[r,i]=S.useReducer(cj,sj),[o,l]=S.useState(!1),[c,f]=S.useState(),d=S.useRef(null),m=S.useRef(n?.onProtocolError);return m.current=n?.onProtocolError,S.useEffect(()=>{if(!t)return;const p=e.attach(t);d.current=p,f(p);const b=p.on("event",k=>i(k)),y=p.on("attached",k=>i(k)),E=p.on("connectionChange",l),w=p.on("protocolError",k=>{m.current?.(k)});return()=>{b(),y(),E(),w(),p.detach(),d.current=null,f(void 0)}},[e,t]),S.useMemo(()=>({state:r,connected:o,handle:c,send:p=>d.current?.send(p),approve:(p,b)=>d.current?.approve(p,b),deny:(p,b)=>d.current?.deny(p,b),interrupt:()=>d.current?.interrupt(),setPermissionMode:p=>d.current?.setPermissionMode(p),setModel:p=>d.current?.setModel(p),closeSession:()=>d.current?.closeSession()}),[r,o,c])}const dj="modulepreload",hj=function(e){return"/"+e},iS={},hc=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),f=c?.nonce||c?.getAttribute("nonce");i=l(n.map(d=>{if(d=hj(d),d in iS)return;iS[d]=!0;const m=d.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const b=document.createElement("link");if(b.rel=m?"stylesheet":dj,m||(b.as="script"),b.crossOrigin="",b.href=d,f&&b.setAttribute("nonce",f),document.head.appendChild(b),m)return new Promise((y,E)=>{b.addEventListener("load",y),b.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return i.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};function pj(e,t={}){const n=new Map;let r,i=!1;const o=m=>t.onExecution?.(m),l=(m,p,b,y)=>{e.sendToolCallError(m.executionId,p,b),o({executionId:m.executionId,toolName:m.toolName,status:"failed",reason:p,startedAt:y,endedAt:Date.now()})},c=async m=>{const p=Date.now();if(!(t.tools??["eval_script"]).includes(m.toolName)){l(m,"unsupported_tool",`this client does not execute '${m.toolName}'`,p);return}const y=m.input?.script;if(typeof y!="string"){l(m,"invalid_input","expected a string `script` input",p);return}const E=new AbortController;n.set(m.executionId,E),o({executionId:m.executionId,toolName:m.toolName,status:"running",startedAt:p});try{const w=await hc(()=>import("./index-DHI1YKpy.js"),[]),k=w.createVfs(m.vfsSeed),C=Math.min(m.limits?.timeoutMs??Number.POSITIVE_INFINITY,t.timeoutMs??5e3),A=Math.min(m.limits?.memoryLimitBytes??Number.POSITIVE_INFINITY,t.memoryLimitBytes??64*1024*1024),_=t.execute?await t.execute({script:y,vfs:k,timeoutMs:C,memoryLimitBytes:A,signal:E.signal}):await(async()=>(r??=(t.loadEngine??mj)(),w.runScript(await r,{script:y,vfs:k,timeoutMs:C,memoryLimitBytes:A,signal:E.signal,fetchText:t.fetchText})))();if(i||!n.has(m.executionId))return;const N=_.logs.map(M=>`[${M.level}] ${M.text}`);_.ok?(e.sendToolCallResult(m.executionId,{type:"json",value:_.value},N),o({executionId:m.executionId,toolName:m.toolName,status:"settled",startedAt:p,endedAt:Date.now()})):(e.sendToolCallError(m.executionId,_.reason,_.error,N),o({executionId:m.executionId,toolName:m.toolName,status:"failed",reason:_.reason,startedAt:p,endedAt:Date.now()}))}catch(w){if(i||!n.has(m.executionId))return;l(m,"host_error",w instanceof Error?w.message:String(w),p)}finally{n.delete(m.executionId)}},f=e.on("toolCallRequest",m=>void c(m)),d=e.on("toolCallCanceled",({executionId:m,reason:p})=>{const b=n.get(m);b&&(b.abort(),n.delete(m),o({executionId:m,toolName:"",status:"canceled",reason:p,startedAt:Date.now(),endedAt:Date.now()}))});return{dispose:()=>{i=!0,f(),d();for(const m of n.values())m.abort();n.clear()}}}async function mj(){const[e,t]=await Promise.all([hc(()=>import("./index-DHI1YKpy.js"),[]),hc(()=>import("./index-Bgb6oVBf.js"),[])]);return e.loadEngine(t)}function gj(e,t={}){const[n,r]=S.useState([]),i=S.useRef(t);return i.current=t,S.useEffect(()=>{if(!e||t.enabled===!1)return;const o=pj(e,{get tools(){return i.current.tools},get timeoutMs(){return i.current.timeoutMs},get memoryLimitBytes(){return i.current.memoryLimitBytes},get loadEngine(){return i.current.loadEngine},get execute(){return i.current.execute},get fetchText(){return i.current.fetchText},onExecution:l=>{i.current.onExecution?.(l);const c=i.current.historyLimit??50;r(f=>[...f.filter(d=>d.executionId!==l.executionId),l].slice(-c))}});return()=>o.dispose()},[e,t.enabled]),{executions:n}}const bj=e=>e.replace(/\s*\(MCP\)$/i,"");function xj({onSend:e,onInterrupt:t,busy:n,disabled:r,placeholder:i="Message Claude…",commands:o,toolbar:l,className:c}){const{bind:f,plainText:d,isEmpty:m,clear:p,focus:b}=tj(),y=S.useMemo(()=>{if(!o||o.length===0)return;const k=new Set,C=o.flatMap(A=>{const _=bj(A.name);return k.has(_)?[]:(k.add(_),[{...A,name:_}])});return[nj({onSearch:A=>{const _=A.toLowerCase(),N=C.flatMap(M=>{const O=[M.name,...M.aliases??[]].map(D=>D.toLowerCase()),P=O.some(D=>D.startsWith(_))?2:O.some(D=>D.includes(_))?1:0;return P===0?[]:[{c:M,score:P}]});return N.sort((M,O)=>O.score-M.score),N.map(({c:M})=>({value:M.name,label:`/${M.name}${M.argumentHint?` ${M.argumentHint}`:""}`,description:M.description}))},onSelect:A=>A.value,chipClassName:"font-mono"})]},[o]),E=()=>{const k=d.trim();!k||r||(e(k),p(),b())},w=!r&&!m;return g.jsxs("div",{"data-slot":"composer",className:He("px-3 pb-3",c),children:[g.jsxs("div",{className:He("mx-auto w-full max-w-3xl overflow-hidden rounded-lg border border-border bg-bg shadow-(--shadow-xs)","transition-colors focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/30",r&&"opacity-60"),children:[g.jsx(ej,{...f,triggers:y,onSubmit:E,disabled:r,placeholder:r?"Session ended":i,minHeight:28,maxHeight:192,"aria-label":"Message Claude",className:"px-3 pt-2.5 pb-1 text-body-sm text-text"}),g.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-2",children:[g.jsx("div",{className:"flex min-w-0 items-center gap-1",children:l}),n?g.jsx($t,{variant:"outline",size:"icon-sm","aria-label":"Interrupt",className:"rounded-full",onClick:t,children:g.jsx(f9,{className:"size-3"})}):g.jsx($t,{size:"icon-sm","aria-label":"Send",className:"rounded-full",disabled:!w,onClick:E,children:g.jsx(EP,{className:"size-4"})})]})]}),g.jsx("div",{className:"mx-auto mt-1 w-full max-w-3xl text-center text-label text-fg-4",children:"Enter to send · Shift+Enter for a new line"})]})}const ub=e=>e==="default";function yj(e,t){if(!t)return;const n=t.replace(/\[.*\]$/,""),r=e.filter(i=>!ub(i.value));return r.find(i=>i.value===n)??r.find(i=>n.includes(i.value)||i.value.includes(n))}function hA({models:e,model:t,onModelChange:n,variant:r="toolbar",disabled:i,className:o}){const l=yj(e,t)??(t?void 0:e.find(c=>ub(c.value)));return g.jsxs(Cc,{items:e.map(c=>({value:c.value,label:c.displayName})),value:l?.value??null,onValueChange:c=>{typeof c!="string"||c===l?.value||n(ub(c)?void 0:c)},disabled:i,children:[g.jsx(kc,{"aria-label":"Model",className:He(r==="toolbar"&&"h-6 max-w-56 border-transparent bg-transparent text-fg-3 hover:bg-surface-hover",o),children:g.jsx("span",{className:He("truncate",r==="toolbar"&&"font-mono text-label"),children:g.jsx(wc,{placeholder:t??"model"})})}),g.jsx(Ac,{className:"min-w-72",children:e.map(c=>g.jsxs(cl,{value:c.value,children:[g.jsx(ul,{children:g.jsx("span",{className:"font-medium",children:c.displayName})}),c.description?g.jsx("span",{className:"text-label text-fg-4",children:c.description}):null]},c.value))})]})}const cb=[{value:"default",label:"default",description:"ask for approval"},{value:"acceptEdits",label:"acceptEdits",description:"auto-approve file edits"},{value:"plan",label:"plan",description:"read-only planning"},{value:"auto",label:"auto",description:"model decides when to ask"},{value:"dontAsk",label:"dontAsk",description:"never ask — deny unapproved"},{value:"bypassPermissions",label:"bypassPermissions",description:"no prompts (danger)",dangerous:!0}];function Rc({mode:e,onModeChange:t,modes:n,variant:r="toolbar",disabled:i,className:o}){const l=e==="bypassPermissions",c=n?cb.filter(f=>n.includes(f.value)):cb;return g.jsxs(Cc,{items:c.map(f=>({value:f.value,label:f.label})),value:e??null,onValueChange:f=>{typeof f=="string"&&f!==e&&t(f)},disabled:i,children:[g.jsx(kc,{"aria-label":"Permission mode",className:He(r==="toolbar"&&"h-6 max-w-44 border-transparent bg-transparent hover:bg-surface-hover",l?"text-danger":r==="toolbar"?"text-fg-3":void 0,o),children:g.jsx("span",{className:He("truncate",r==="toolbar"&&"font-mono text-label"),children:g.jsx(wc,{placeholder:"permissions"})})}),g.jsx(Ac,{className:"min-w-56",children:c.map(f=>g.jsxs(cl,{value:f.value,children:[g.jsx(ul,{children:g.jsx("span",{className:He("font-medium",f.dangerous&&"text-danger"),children:f.label})}),g.jsx("span",{className:He("text-label",f.dangerous?"text-danger/80":"text-fg-4"),children:f.description})]},f.value))})]})}function Ej({request:e,onApprove:t,onDeny:n,className:r}){const[i,o]=S.useState(!1);return g.jsx("div",{"data-slot":"permission-prompt",className:He("rounded-lg border border-warning/40 bg-warning-bg p-3",r),children:g.jsxs("div",{className:"flex items-start gap-2.5",children:[g.jsx(o9,{className:"mt-0.5 size-4 shrink-0 text-warning"}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"text-body-sm font-medium text-fg-1",children:e.title??`Claude wants to use ${e.toolName}`}),e.description?g.jsx("div",{className:"mt-0.5 text-label text-fg-3",children:e.description}):null,g.jsxs("button",{type:"button",className:"mt-1 font-mono text-label text-fg-3 underline-offset-2 hover:underline",onClick:()=>o(l=>!l),children:[i?"Hide":"Show"," ",e.toolName," input"]}),i?g.jsx("pre",{className:"mt-1.5 max-h-48 overflow-auto rounded-md bg-code-bg px-2.5 py-1.5 font-mono text-label whitespace-pre-wrap text-fg-2",children:JSON.stringify(e.input,null,2)}):null]}),g.jsxs("div",{className:"flex shrink-0 gap-1.5",children:[g.jsx($t,{size:"sm",onClick:()=>t(e.id),children:"Allow"}),g.jsx($t,{size:"sm",variant:"outline",onClick:()=>n(e.id,"Denied by user"),children:"Deny"})]})]})})}const aS=[{value:"auto",label:"Auto-answer",description:"pick each question’s recommended option"},{value:"ask",label:"Ask",description:"wait for a watcher or webhook controller to answer"},{value:"deny",label:"Disabled",description:"the agent is told to decide on its own"}];function pA(e){return(Array.isArray(e.questions)?e.questions:[]).flatMap(n=>{const r=n;if(typeof r.question!="string"||!Array.isArray(r.options))return[];const i=r.options.filter(o=>typeof o?.label=="string");return i.length===0?[]:[{question:r.question,header:typeof r.header=="string"?r.header:"",options:i,multiSelect:r.multiSelect===!0}]})}const Cu={labels:[],other:"",otherActive:!1};function oS(e){const t=[...e.labels];return e.otherActive&&e.other.trim()&&t.push(e.other.trim()),t.join(", ")}function Tj({request:e,onAnswer:t,onDismiss:n,className:r}){const i=pA(e.input),[o,l]=S.useState(()=>i.map(()=>Cu)),c=(p,b)=>{l(y=>y.map((E,w)=>w===p?{...E,...b}:E))},f=(p,b,y)=>{const E=o[p]??Cu;y?c(p,{labels:E.labels.includes(b)?E.labels.filter(w=>w!==b):[...E.labels,b]}):c(p,{labels:E.labels[0]===b?[]:[b],otherActive:!1})},d=i.every((p,b)=>oS(o[b]??Cu)!==""),m=()=>{const p={};i.forEach((b,y)=>{p[b.question]=oS(o[y]??Cu)}),t(e.id,{...e.input,answers:p})};return g.jsx("div",{"data-slot":"question-prompt",className:He("rounded-lg border border-info/40 bg-info-bg p-3",r),children:g.jsxs("div",{className:"flex items-start gap-2.5",children:[g.jsx(GP,{className:"mt-0.5 size-4 shrink-0 text-info"}),g.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-3",children:[i.map((p,b)=>{const y=o[b]??Cu;return g.jsxs("div",{className:"flex flex-col gap-1.5",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[p.header?g.jsx(ts,{variant:"info",children:p.header}):null,g.jsx("span",{className:"text-body-sm font-medium text-fg-1",children:p.question})]}),g.jsxs("div",{className:"flex flex-col gap-1",children:[p.options.map(E=>{const w=y.labels.includes(E.label);return g.jsxs("button",{type:"button",onClick:()=>f(b,E.label,p.multiSelect===!0),className:He("rounded-md border px-2.5 py-1.5 text-left transition-colors",w?"border-info bg-bg":"border-border bg-bg/50 hover:border-border-strong hover:bg-bg"),children:[g.jsx("span",{className:"block text-body-sm font-medium text-fg-1",children:E.label}),E.description?g.jsx("span",{className:"block text-label text-fg-4",children:E.description}):null,w&&E.preview?g.jsx("pre",{className:"mt-1.5 max-h-40 overflow-auto rounded-md bg-code-bg px-2.5 py-1.5 font-mono text-label whitespace-pre-wrap text-fg-2",children:E.preview}):null]},E.label)}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("button",{type:"button",onClick:()=>c(b,{otherActive:!y.otherActive}),className:He("shrink-0 rounded-md border px-2.5 py-1.5 text-body-sm font-medium transition-colors",y.otherActive?"border-info bg-bg text-fg-1":"border-border bg-bg/50 text-fg-3 hover:border-border-strong hover:bg-bg"),children:"Other…"}),y.otherActive?g.jsx(bn,{autoFocus:!0,value:y.other,onChange:E=>c(b,{other:E.target.value}),placeholder:"Type your own answer",className:"flex-1"}):null]})]})]},b)}),g.jsx("div",{children:g.jsx($t,{size:"sm",onClick:m,disabled:!d,children:"Answer"})})]}),g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Dismiss question",className:"shrink-0",onClick:()=>n(e.id,"Question dismissed by user"),children:g.jsx(V3,{className:"size-3.5"})})]})})}function tp(e){return e===void 0||Number.isNaN(e)?"—":e===0?"$0.00":e<.01?"<$0.01":`$${e.toFixed(2)}`}function vj(e){if(e<1e3)return`${Math.round(e)}ms`;const t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`}function Qi(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))}function Sj(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}function lS(e,t=Date.now()){const n=e-t;if(n<=0)return"now";const r=Math.ceil(n/6e4);if(r<1)return"<1m";if(r<60)return`${r}m`;const i=Math.floor(r/1440);return i>=1?`${i}d ${Math.floor(r%1440/60)}h`:`${Math.floor(r/60)}h ${r%60}m`}function R1(e,t=Date.now()){if(!e)return"—";const n=Math.max(0,t-e),r=Math.floor(n/1e3);if(r<60)return"just now";const i=Math.floor(r/60);if(i<60)return`${i}m ago`;const o=Math.floor(i/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Cj(e,t=80){if(e==null)return"";if(typeof e=="object"){const r=e,i=r.command??r.file_path??r.path??r.url??r.pattern??r.query??r.description;if(typeof i=="string")return i.length>t?i.slice(0,t-1)+"…":i}const n=JSON.stringify(e)??"";return n.length>t?n.slice(0,t-1)+"…":n}const mA={starting:{label:"Starting",variant:"info",busy:!0},running:{label:"Running",variant:"info",busy:!0},awaiting_approval:{label:"Needs approval",variant:"warning",busy:!0},idle:{label:"Idle",variant:"success",busy:!1},parked:{label:"Parked",variant:"accent",busy:!1},failed:{label:"Failed",variant:"danger",busy:!1},closed:{label:"Closed",variant:"neutral",busy:!1}};function wj(e=3e4){const[t,n]=S.useState(()=>Date.now());return S.useEffect(()=>{const r=setInterval(()=>n(Date.now()),e);return()=>clearInterval(r)},[e]),t}const gA=e=>e>=95?"text-danger":e>=80?"text-warning":"text-fg-3",kj=e=>typeof CSS<"u"&&CSS.supports("color",e)?e:void 0;function Aj({usage:e}){return g.jsx(Q3,{content:g.jsxs("div",{className:"flex min-w-44 flex-col gap-1 py-0.5",children:[e.categories.map(t=>g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"size-2 shrink-0 rounded-full bg-fg-4",style:kj(t.color)?{backgroundColor:t.color}:void 0}),g.jsx("span",{className:"flex-1",children:t.name}),g.jsx("span",{className:"font-mono text-fg-3",children:Qi(t.tokens)})]},t.name)),g.jsxs("div",{className:"mt-0.5 flex items-center justify-between gap-2 border-t border-border pt-1",children:[g.jsx("span",{children:"Total"}),g.jsxs("span",{className:"font-mono text-fg-3",children:[Qi(e.totalTokens)," / ",Qi(e.maxTokens)," (",e.percentage.toFixed(0),"%)"]})]})]}),children:g.jsxs("span",{className:He("inline-flex cursor-default items-center gap-1 font-mono text-label",gA(e.percentage)),children:["Ctx ",Qi(e.totalTokens)]})})}function uS({label:e,info:t,now:n}){const r=t.utilization,i=t.resetsAt!==void 0?t.resetsAt*1e3:void 0;return g.jsx(Q3,{content:g.jsxs("div",{className:"flex min-w-36 flex-col gap-1 py-0.5",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("span",{children:[e," usage"]}),g.jsx("span",{className:"font-mono text-fg-3",children:r!==void 0?`${r.toFixed(1)}%`:"—"})]}),i!==void 0?g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("span",{children:"Resets in"}),g.jsx("span",{className:"font-mono text-fg-3",children:lS(i,n)})]}):null,t.isUsingOverage?g.jsx("div",{className:"text-warning",children:"Using overage"}):null,t.status==="rejected"?g.jsx("div",{className:"text-danger",children:"Limit reached"}):null]}),children:g.jsxs("span",{className:He("inline-flex cursor-default items-center gap-1 font-mono text-label",t.status==="rejected"?"text-danger":gA(r??0)),children:[g.jsx(Z3,{value:r??0}),e,r!==void 0?` ${r.toFixed(0)}%`:"",i!==void 0?g.jsxs("span",{className:"text-fg-4",children:["· ",lS(i,n)]}):null]})})}function _j({state:e,connected:t,className:n}){const r=mA[e.status],i=wj(),o=e.rateLimits?.five_hour,l=e.rateLimits?.seven_day;return g.jsxs("div",{"data-slot":"status-bar",className:He("flex items-center gap-3 border-b border-border bg-surface px-3 py-2",n),children:[g.jsxs(ts,{variant:r.variant,dot:!r.busy,children:[r.busy?g.jsx(ci,{className:"size-3 text-current"}):null,r.label]}),e.contextUsage?g.jsx(Aj,{usage:e.contextUsage}):null,o?g.jsx(uS,{label:"Session",info:o,now:i}):null,l?g.jsx(uS,{label:"Weekly",info:l,now:i}):null,g.jsx("span",{className:"flex-1"}),t?null:g.jsxs("span",{className:"inline-flex items-center gap-1 text-label text-warning",children:[g.jsx(E9,{className:"size-3"})," reconnecting…"]}),g.jsx("span",{className:"font-mono text-label text-fg-3",children:tp(e.totalCostUsd)})]})}/*!---------------------------------------------------------------------------------------------
346
346
  * Copyright (c) StackBlitz. All rights reserved.
347
347
  * Licensed under the MIT License. See License.txt in the project root for license information.
348
348
  *--------------------------------------------------------------------------------------------*/const Nj={damping:.7,stiffness:.05,mass:1.25},Rj=70,Oj=1e3/60,Ij=350;let np=!1;globalThis.document?.addEventListener("mousedown",()=>{np=!0});globalThis.document?.addEventListener("mouseup",()=>{np=!1});globalThis.document?.addEventListener("click",()=>{np=!1});const Lj=(e={})=>{const[t,n]=S.useState(!1),[r,i]=S.useState(e.initial!==!1),[o,l]=S.useState(!1),c=S.useRef(null);c.current=e;const f=S.useCallback(()=>{if(!np)return!1;const A=window.getSelection();if(!A||!A.rangeCount)return!1;const _=A.getRangeAt(0);return _.commonAncestorContainer.contains(k.current)||k.current?.contains(_.commonAncestorContainer)},[]),d=S.useCallback(A=>{p.isAtBottom=A,i(A)},[]),m=S.useCallback(A=>{p.escapedFromLock=A,n(A)},[]),p=S.useMemo(()=>{let A;return{escapedFromLock:t,isAtBottom:r,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return k.current?.scrollTop??0},set scrollTop(_){if(k.current){const{scrollBehavior:N}=getComputedStyle(k.current);N!=="auto"&&(k.current.style.scrollBehavior="auto"),k.current.scrollTop=_,p.ignoreScrollToTop=k.current.scrollTop,N!=="auto"&&(k.current.style.scrollBehavior=N)}},get targetScrollTop(){return!k.current||!C.current?0:k.current.scrollHeight-1-k.current.clientHeight},get calculatedTargetScrollTop(){if(!k.current||!C.current)return 0;const{targetScrollTop:_}=this;if(!e.targetScrollTop)return _;if(A?.targetScrollTop===_)return A.calculatedScrollTop;const N=Math.max(Math.min(e.targetScrollTop(_,{scrollElement:k.current,contentElement:C.current}),_),0);return A={targetScrollTop:_,calculatedScrollTop:N},requestAnimationFrame(()=>{A=void 0}),N},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=Rj}}},[]),b=S.useCallback((A={})=>{typeof A=="string"&&(A={animation:A}),A.preserveScrollPosition||d(!0);const _=Date.now()+(Number(A.wait)||0),N=dg(c.current,A.animation),{ignoreEscapes:M=!1}=A;let O,P=p.calculatedTargetScrollTop;A.duration instanceof Promise?A.duration.finally(()=>{O=Date.now()}):O=_+(A.duration??0);const D=async()=>{const Y=new Promise(requestAnimationFrame).then(()=>{if(!p.isAtBottom)return p.animation=void 0,!1;const{scrollTop:U}=p,$=performance.now(),Q=($-(p.lastTick??$))/Oj;if(p.animation||(p.animation={behavior:N,promise:Y,ignoreEscapes:M}),p.animation.behavior===N&&(p.lastTick=$),f()||_>Date.now())return D();if(U<Math.min(P,p.calculatedTargetScrollTop)){if(p.animation?.behavior===N){if(N==="instant")return p.scrollTop=p.calculatedTargetScrollTop,D();p.velocity=(N.damping*p.velocity+N.stiffness*p.scrollDifference)/N.mass,p.accumulated+=p.velocity*Q,p.scrollTop+=p.accumulated,p.scrollTop!==U&&(p.accumulated=0)}return D()}return O>Date.now()?(P=p.calculatedTargetScrollTop,D()):(p.animation=void 0,p.scrollTop<p.calculatedTargetScrollTop?b({animation:dg(c.current,c.current.resize),ignoreEscapes:M,duration:Math.max(0,O-Date.now())||void 0}):p.isAtBottom)});return Y.then(U=>(requestAnimationFrame(()=>{p.animation||(p.lastTick=void 0,p.velocity=0)}),U))};return A.wait!==!0&&(p.animation=void 0),p.animation?.behavior===N?p.animation.promise:D()},[d,f,p]),y=S.useCallback(()=>{m(!0),d(!1)},[m,d]),E=S.useCallback(({target:A})=>{if(A!==k.current)return;const{scrollTop:_,ignoreScrollToTop:N}=p;let{lastScrollTop:M=_}=p;p.lastScrollTop=_,p.ignoreScrollToTop=void 0,N&&N>_&&(M=N),l(p.isNearBottom),setTimeout(()=>{if(p.resizeDifference||_===N)return;if(f()){m(!0),d(!1);return}const O=_>M,P=_<M;if(p.animation?.ignoreEscapes){p.scrollTop=M;return}P&&(m(!0),d(!1)),O&&m(!1),!p.escapedFromLock&&p.isNearBottom&&d(!0)},1)},[m,d,f,p]),w=S.useCallback(({target:A,deltaY:_})=>{let N=A;for(;!["scroll","auto"].includes(getComputedStyle(N).overflow);){if(!N.parentElement)return;N=N.parentElement}N===k.current&&_<0&&k.current.scrollHeight>k.current.clientHeight&&!p.animation?.ignoreEscapes&&(m(!0),d(!1))},[m,d,p]),k=cS(A=>{k.current?.removeEventListener("scroll",E),k.current?.removeEventListener("wheel",w),A?.addEventListener("scroll",E,{passive:!0}),A?.addEventListener("wheel",w,{passive:!0})},[]),C=cS(A=>{if(p.resizeObserver?.disconnect(),p.resizeObserver=void 0,!A)return;let _;p.resizeObserver=new ResizeObserver(([N])=>{const{height:M}=N.contentRect,O=M-(_??M);if(p.resizeDifference=O,p.scrollTop>p.targetScrollTop&&(p.scrollTop=p.targetScrollTop),l(p.isNearBottom),O>=0){const P=dg(c.current,_?c.current.resize:c.current.initial);b({animation:P,wait:!0,preserveScrollPosition:!0,duration:P==="instant"?void 0:Ij})}else p.isNearBottom&&(m(!1),d(!0));_=M,requestAnimationFrame(()=>{setTimeout(()=>{p.resizeDifference===O&&(p.resizeDifference=0)},1)})}),p.resizeObserver?.observe(A)},[]);return{contentRef:C,scrollRef:k,scrollToBottom:b,stopScroll:y,isAtBottom:r||o,isNearBottom:o,escapedFromLock:t,state:p}};function cS(e,t){const n=S.useCallback(r=>(n.current=r,e(r)),t);return n}const fg=new Map;function dg(...e){const t={...Nj};let n=!1;for(const i of e){if(i==="instant"){n=!0;continue}typeof i=="object"&&(n=!1,t.damping=i.damping??t.damping,t.stiffness=i.stiffness??t.stiffness,t.mass=i.mass??t.mass)}const r=JSON.stringify(t);return fg.has(r)||fg.set(r,Object.freeze(t)),n?"instant":fg.get(r)}/*!---------------------------------------------------------------------------------------------
@@ -458,7 +458,7 @@ ${t}</tr>
458
458
  `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${Es(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:n,tokens:r}){let i=this.parser.parseInline(r),o=IC(t);if(o===null)return i;t=o;let l='<a href="'+t+'"';return n&&(l+=' title="'+Es(n)+'"'),l+=">"+i+"</a>",l}image({href:t,title:n,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let o=IC(t);if(o===null)return Es(r);t=o;let l=`<img src="${t}" alt="${Es(r)}"`;return n&&(l+=` title="${Es(n)}"`),l+=">",l}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Es(t.text)}},ux=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},os=class Nb{options;renderer;textRenderer;constructor(t){this.options=t||lo,this.options.renderer=this.options.renderer||new kh,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ux}static parse(t,n){return new Nb(n).parse(t)}static parseInline(t,n){return new Nb(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let i=t[r];if(this.options.extensions?.renderers?.[i.type]){let l=i,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){n+=c||"";continue}}let o=i;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let c=this.options.extensions.renderers[o.type].call({parser:this},o);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=c||"";continue}}let l=o;switch(l.type){case"escape":{r+=n.text(l);break}case"html":{r+=n.html(l);break}case"link":{r+=n.link(l);break}case"image":{r+=n.image(l);break}case"checkbox":{r+=n.checkbox(l);break}case"strong":{r+=n.strong(l);break}case"em":{r+=n.em(l);break}case"codespan":{r+=n.codespan(l);break}case"br":{r+=n.br(l);break}case"del":{r+=n.del(l);break}case"text":{r+=n.text(l);break}default:{let c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}},Uu=class{options;block;constructor(e){this.options=e||lo}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Jr.lex:Jr.lexInline}provideParser(e=this.block){return e?os.parse:os.parseInline}},EQ=class{defaults=tx();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=os;Renderer=kh;TextRenderer=ux;Lexer=Jr;Tokenizer=wh;Hooks=Uu;constructor(...t){this.use(...t)}walkTokens(t,n){let r=[];for(let i of t)switch(r=r.concat(n.call(this,i)),i.type){case"table":{let o=i;for(let l of o.header)r=r.concat(this.walkTokens(l.tokens,n));for(let l of o.rows)for(let c of l)r=r.concat(this.walkTokens(c.tokens,n));break}case"list":{let o=i;r=r.concat(this.walkTokens(o.items,n));break}default:{let o=i;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(l=>{let c=o[l].flat(1/0);r=r.concat(this.walkTokens(c,n))}):o.tokens&&(r=r.concat(this.walkTokens(o.tokens,n)))}}return r}use(...t){let n=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let l=n.renderers[o.name];l?n.renderers[o.name]=function(...c){let f=o.renderer.apply(this,c);return f===!1&&(f=l.apply(this,c)),f}:n.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let l=n[o.level];l?l.unshift(o.tokenizer):n[o.level]=[o.tokenizer],o.start&&(o.level==="block"?n.startBlock?n.startBlock.push(o.start):n.startBlock=[o.start]:o.level==="inline"&&(n.startInline?n.startInline.push(o.start):n.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(n.childTokens[o.name]=o.childTokens)}),i.extensions=n),r.renderer){let o=this.defaults.renderer||new kh(this.defaults);for(let l in r.renderer){if(!(l in o))throw new Error(`renderer '${l}' does not exist`);if(["options","parser"].includes(l))continue;let c=l,f=r.renderer[c],d=o[c];o[c]=(...m)=>{let p=f.apply(o,m);return p===!1&&(p=d.apply(o,m)),p||""}}i.renderer=o}if(r.tokenizer){let o=this.defaults.tokenizer||new wh(this.defaults);for(let l in r.tokenizer){if(!(l in o))throw new Error(`tokenizer '${l}' does not exist`);if(["options","rules","lexer"].includes(l))continue;let c=l,f=r.tokenizer[c],d=o[c];o[c]=(...m)=>{let p=f.apply(o,m);return p===!1&&(p=d.apply(o,m)),p}}i.tokenizer=o}if(r.hooks){let o=this.defaults.hooks||new Uu;for(let l in r.hooks){if(!(l in o))throw new Error(`hook '${l}' does not exist`);if(["options","block"].includes(l))continue;let c=l,f=r.hooks[c],d=o[c];Uu.passThroughHooks.has(l)?o[c]=m=>{if(this.defaults.async&&Uu.passThroughHooksRespectAsync.has(l))return(async()=>{let b=await f.call(o,m);return d.call(o,b)})();let p=f.call(o,m);return d.call(o,p)}:o[c]=(...m)=>{if(this.defaults.async)return(async()=>{let b=await f.apply(o,m);return b===!1&&(b=await d.apply(o,m)),b})();let p=f.apply(o,m);return p===!1&&(p=d.apply(o,m)),p}}i.hooks=o}if(r.walkTokens){let o=this.defaults.walkTokens,l=r.walkTokens;i.walkTokens=function(c){let f=[];return f.push(l.call(this,c)),o&&(f=f.concat(o.call(this,c))),f}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,n){return Jr.lex(t,n??this.defaults)}parser(t,n){return os.parse(t,n??this.defaults)}parseMarkdown(t){return(n,r)=>{let i={...r},o={...this.defaults,...i},l=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&i.async===!1)return l(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return l(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let c=o.hooks?await o.hooks.preprocess(n):n,f=await(o.hooks?await o.hooks.provideLexer(t):t?Jr.lex:Jr.lexInline)(c,o),d=o.hooks?await o.hooks.processAllTokens(f):f;o.walkTokens&&await Promise.all(this.walkTokens(d,o.walkTokens));let m=await(o.hooks?await o.hooks.provideParser(t):t?os.parse:os.parseInline)(d,o);return o.hooks?await o.hooks.postprocess(m):m})().catch(l);try{o.hooks&&(n=o.hooks.preprocess(n));let c=(o.hooks?o.hooks.provideLexer(t):t?Jr.lex:Jr.lexInline)(n,o);o.hooks&&(c=o.hooks.processAllTokens(c)),o.walkTokens&&this.walkTokens(c,o.walkTokens);let f=(o.hooks?o.hooks.provideParser(t):t?os.parse:os.parseInline)(c,o);return o.hooks&&(f=o.hooks.postprocess(f)),f}catch(c){return l(c)}}}onError(t,n){return r=>{if(r.message+=`
459
459
  Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+Es(r.message+"",!0)+"</pre>";return n?Promise.resolve(i):i}if(n)return Promise.reject(r);throw r}}},eo=new EQ;function Kt(e,t){return eo.parse(e,t)}Kt.options=Kt.setOptions=function(e){return eo.setOptions(e),Kt.defaults=eo.defaults,EN(Kt.defaults),Kt};Kt.getDefaults=tx;Kt.defaults=lo;Kt.use=function(...e){return eo.use(...e),Kt.defaults=eo.defaults,EN(Kt.defaults),Kt};Kt.walkTokens=function(e,t){return eo.walkTokens(e,t)};Kt.parseInline=eo.parseInline;Kt.Parser=os;Kt.parser=os.parse;Kt.Renderer=kh;Kt.TextRenderer=ux;Kt.Lexer=Jr;Kt.lexer=Jr.lex;Kt.Tokenizer=wh;Kt.Hooks=Uu;Kt.parse=Kt;Kt.options;Kt.setOptions;Kt.use;Kt.walkTokens;Kt.parseInline;os.parse;Jr.lex;var TQ=300,vQ="300px",SQ=500;function CQ(e={}){let{immediate:t=!1,debounceDelay:n=TQ,rootMargin:r=vQ,idleTimeout:i=SQ}=e,[o,l]=S.useState(!1),c=S.useRef(null),f=S.useRef(null),d=S.useRef(null),m=S.useMemo(()=>y=>{let E=Date.now();return window.setTimeout(()=>{y({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-E))})},1)},[]),p=S.useMemo(()=>typeof window<"u"&&window.requestIdleCallback?(y,E)=>window.requestIdleCallback(y,E):m,[m]),b=S.useMemo(()=>typeof window<"u"&&window.cancelIdleCallback?y=>window.cancelIdleCallback(y):y=>{clearTimeout(y)},[]);return S.useEffect(()=>{if(t){l(!0);return}let y=c.current;if(!y)return;f.current&&(clearTimeout(f.current),f.current=null),d.current&&(b(d.current),d.current=null);let E=()=>{f.current&&(clearTimeout(f.current),f.current=null),d.current&&(b(d.current),d.current=null)},w=_=>{d.current=p(N=>{N.timeRemaining()>0||N.didTimeout?(l(!0),_.disconnect()):d.current=p(()=>{l(!0),_.disconnect()},{timeout:i/2})},{timeout:i})},k=_=>{E(),f.current=window.setTimeout(()=>{var N,M;let O=_.takeRecords();(O.length===0||(M=(N=O.at(-1))==null?void 0:N.isIntersecting)!=null&&M)&&w(_)},n)},C=(_,N)=>{_.isIntersecting?k(N):E()},A=new IntersectionObserver(_=>{for(let N of _)C(N,A)},{rootMargin:r,threshold:0});return A.observe(y),()=>{f.current&&clearTimeout(f.current),d.current&&b(d.current),A.disconnect()}},[t,n,r,i,b,p]),{shouldRender:o,containerRef:c}}var RN=/\s/,wQ=/^\s+$/,kQ=new Set(["code","pre","svg","math","annotation"]),AQ=e=>typeof e=="object"&&e!==null&&"type"in e&&e.type==="element",_Q=e=>e.some(t=>AQ(t)&&kQ.has(t.tagName)),NQ=e=>{let t=[],n="",r=!1;for(let i of e){let o=RN.test(i);o!==r&&n&&(t.push(n),n=""),n+=i,r=o}return n&&t.push(n),t},RQ=e=>{let t=[],n="";for(let r of e)RN.test(r)?n+=r:(n&&(t.push(n),n=""),t.push(r));return n&&t.push(n),t},OQ=(e,t,n,r,i,o)=>{let l=`--sd-animation:sd-${t};--sd-duration:${i?0:n}ms;--sd-easing:${r}`;return o&&(l+=`;--sd-delay:${o}ms`),{type:"element",tagName:"span",properties:{"data-sd-animate":!0,style:l},children:[{type:"text",value:e}]}},IQ=(e,t,n,r,i)=>{let o=t.at(-1);if(!(o&&"children"in o))return;if(_Q(t))return el;let l=o,c=l.children.indexOf(e);if(c===-1)return;let f=e.value;if(!f.trim()){i.count+=f.length;return}let d=n.sep==="char"?RQ(f):NQ(f),m=r.prevContentLength,p=d.map(b=>{let y=i.count;if(i.count+=b.length,wQ.test(b))return{type:"text",value:b};let E=m>0&&y<m,w=E?0:i.newIndex++*n.stagger;return OQ(b,n.animation,n.duration,n.easing,E,w)});return l.children.splice(c,1,...p),c+p.length},LQ=0;function Rb(e){var t,n,r,i,o;let l={animation:(t=e?.animation)!=null?t:"fadeIn",duration:(n=e?.duration)!=null?n:150,easing:(r=e?.easing)!=null?r:"ease",sep:(i=e?.sep)!=null?i:"word",stagger:(o=e?.stagger)!=null?o:40},c={prevContentLength:0,lastRenderCharCount:0},f=LQ++,d=()=>m=>{let p={count:0,newIndex:0};O1(m,"text",(b,y)=>IQ(b,y,l,c,p)),c.lastRenderCharCount=p.count,c.prevContentLength=0};return Object.defineProperty(d,"name",{value:`rehypeAnimate$${f}`}),{name:"animate",type:"animate",rehypePlugin:d,setPrevContentLength(m){c.prevContentLength=m},getLastRenderCharCount(){let m=c.lastRenderCharCount;return c.lastRenderCharCount=0,m}}}Rb();var ON=S.createContext(!1),MQ=()=>S.useContext(ON),cx=(...e)=>ik(Ih(e)),DQ=(e,t)=>{if(!e||!t)return t;let n=`${e}:`;return t.split(/\s+/).filter(Boolean).map(r=>r.startsWith(n)?r:`${e}:${r}`).join(" ")},PQ=e=>e?(...t)=>DQ(e,ik(Ih(t))):cx,sl=(e,t,n)=>{let r=typeof t=="string"&&n.startsWith("text/csv")?"\uFEFF":"",i=typeof t=="string"?new Blob([r+t],{type:n}):t,o=URL.createObjectURL(i),l=document.createElement("a");l.href=o,l.download=e,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)},Ob=S.createContext(cx),St=()=>S.useContext(Ob),BQ=cx("block","before:content-[counter(line)]","before:inline-block","before:[counter-increment:line]","before:w-6","before:mr-4","before:text-[13px]","before:text-right","before:text-muted-foreground/50","before:font-mono","before:select-none"),jQ=e=>{let t={};for(let n of e.split(";")){let r=n.indexOf(":");if(r>0){let i=n.slice(0,r).trim(),o=n.slice(r+1).trim();i&&o&&(t[i]=o)}}return t},HQ=S.memo(({children:e,result:t,language:n,className:r,startLine:i,lineNumbers:o=!0,...l})=>{let c=St(),f=S.useMemo(()=>c(BQ),[c]),d=S.useMemo(()=>{let m={};return t.bg&&(m["--sdm-bg"]=t.bg),t.fg&&(m["--sdm-fg"]=t.fg),t.rootStyle&&Object.assign(m,jQ(t.rootStyle)),m},[t.bg,t.fg,t.rootStyle]);return g.jsx("div",{className:c(r,"overflow-x-auto rounded-md border border-border bg-background p-4 text-sm"),"data-language":n,"data-streamdown":"code-block-body",...l,children:g.jsx("pre",{className:c(r,"bg-[var(--sdm-bg,inherit]","dark:bg-[var(--shiki-dark-bg,var(--sdm-bg,inherit)]"),style:d,children:g.jsx("code",{className:o?c("[counter-increment:line_0] [counter-reset:line]"):void 0,style:o&&i&&i>1?{counterReset:`line ${i-1}`}:void 0,children:t.tokens.map((m,p)=>g.jsx("span",{className:o?f:void 0,children:m.length===0||m.length===1&&m[0].content===""?`
460
460
  `:m.map((b,y)=>{let E={},w=!!b.bgColor;if(b.color&&(E["--sdm-c"]=b.color),b.bgColor&&(E["--sdm-tbg"]=b.bgColor),b.htmlStyle)for(let[k,C]of Object.entries(b.htmlStyle))k==="color"?E["--sdm-c"]=C:k==="background-color"?(E["--sdm-tbg"]=C,w=!0):E[k]=C;return g.jsx("span",{className:c("text-[var(--sdm-c,inherit)]","dark:text-[var(--shiki-dark,var(--sdm-c,inherit))]",w&&"bg-[var(--sdm-tbg)]",w&&"dark:bg-[var(--shiki-dark-bg,var(--sdm-tbg))]"),style:E,...b.htmlAttrs,children:b.content},y)})},p))})})})},(e,t)=>e.result===t.result&&e.language===t.language&&e.className===t.className&&e.startLine===t.startLine&&e.lineNumbers===t.lineNumbers),UQ=({className:e,language:t,style:n,isIncomplete:r,...i})=>{let o=St();return g.jsx("div",{className:o("my-4 flex w-full flex-col gap-2 rounded-xl border border-border bg-sidebar p-2",e),"data-incomplete":r||void 0,"data-language":t,"data-streamdown":"code-block",style:{contentVisibility:"auto",containIntrinsicSize:"auto 200px",...n},...i})},IN=S.createContext({code:""}),LN=()=>S.useContext(IN),zQ=({language:e})=>{let t=St();return g.jsx("div",{className:t("flex h-8 items-center text-muted-foreground text-xs"),"data-language":e,"data-streamdown":"code-block-header",children:g.jsx("span",{className:t("ml-1 font-mono lowercase"),children:e})})},FQ=e=>{let t=e.length;for(;t>0&&e[t-1]===`
461
- `;)t--;return e.slice(0,t)},VQ=S.lazy(()=>hc(()=>import("./highlighted-body-OFNGDK62-3ziW0qKZ.js"),[]).then(e=>({default:e.HighlightedCodeBlockBody}))),$Q=({code:e,language:t,className:n,children:r,isIncomplete:i=!1,startLine:o,lineNumbers:l,...c})=>{let f=St(),d=S.useMemo(()=>FQ(e),[e]),m=S.useMemo(()=>({bg:"transparent",fg:"inherit",tokens:d.split(`
461
+ `;)t--;return e.slice(0,t)},VQ=S.lazy(()=>hc(()=>import("./highlighted-body-OFNGDK62-BP5tMAtR.js"),[]).then(e=>({default:e.HighlightedCodeBlockBody}))),$Q=({code:e,language:t,className:n,children:r,isIncomplete:i=!1,startLine:o,lineNumbers:l,...c})=>{let f=St(),d=S.useMemo(()=>FQ(e),[e]),m=S.useMemo(()=>({bg:"transparent",fg:"inherit",tokens:d.split(`
462
462
  `).map(p=>[{content:p,color:"inherit",bgColor:"transparent",htmlStyle:{},offset:0}])}),[d]);return g.jsx(IN.Provider,{value:{code:e},children:g.jsxs(UQ,{isIncomplete:i,language:t,children:[g.jsx(zQ,{language:t}),r?g.jsx("div",{className:f("pointer-events-none sticky top-2 z-10 -mt-10 flex h-8 items-center justify-end"),children:g.jsx("div",{className:f("pointer-events-auto flex shrink-0 items-center gap-2 rounded-md border border-sidebar bg-sidebar/80 px-1.5 py-1 supports-[backdrop-filter]:bg-sidebar/70 supports-[backdrop-filter]:backdrop-blur"),"data-streamdown":"code-block-actions",children:r})}):null,g.jsx(S.Suspense,{fallback:g.jsx(HQ,{className:n,language:t,lineNumbers:l,result:m,startLine:o,...c}),children:g.jsx(VQ,{className:n,code:d,language:t,lineNumbers:l,raw:m,startLine:o,...c})})]})})},qQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M15.5607 3.99999L15.0303 4.53032L6.23744 13.3232C5.55403 14.0066 4.44599 14.0066 3.76257 13.3232L4.2929 12.7929L3.76257 13.3232L0.969676 10.5303L0.439346 9.99999L1.50001 8.93933L2.03034 9.46966L4.82323 12.2626C4.92086 12.3602 5.07915 12.3602 5.17678 12.2626L13.9697 3.46966L14.5 2.93933L15.5607 3.99999Z",fill:"currentColor",fillRule:"evenodd"})}),YQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M2.75 0.5C1.7835 0.5 1 1.2835 1 2.25V9.75C1 10.7165 1.7835 11.5 2.75 11.5H3.75H4.5V10H3.75H2.75C2.61193 10 2.5 9.88807 2.5 9.75V2.25C2.5 2.11193 2.61193 2 2.75 2H8.25C8.38807 2 8.5 2.11193 8.5 2.25V3H10V2.25C10 1.2835 9.2165 0.5 8.25 0.5H2.75ZM7.75 4.5C6.7835 4.5 6 5.2835 6 6.25V13.75C6 14.7165 6.7835 15.5 7.75 15.5H13.25C14.2165 15.5 15 14.7165 15 13.75V6.25C15 5.2835 14.2165 4.5 13.25 4.5H7.75ZM7.5 6.25C7.5 6.11193 7.61193 6 7.75 6H13.25C13.3881 6 13.5 6.11193 13.5 6.25V13.75C13.5 13.8881 13.3881 14 13.25 14H7.75C7.61193 14 7.5 13.8881 7.5 13.75V6.25Z",fill:"currentColor",fillRule:"evenodd"})}),GQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M8.75 1V1.75V8.68934L10.7197 6.71967L11.25 6.18934L12.3107 7.25L11.7803 7.78033L8.70711 10.8536C8.31658 11.2441 7.68342 11.2441 7.29289 10.8536L4.21967 7.78033L3.68934 7.25L4.75 6.18934L5.28033 6.71967L7.25 8.68934V1.75V1H8.75ZM13.5 9.25V13.5H2.5V9.25V8.5H1V9.25V14C1 14.5523 1.44771 15 2 15H14C14.5523 15 15 14.5523 15 14V9.25V8.5H13.5V9.25Z",fill:"currentColor",fillRule:"evenodd"})}),XQ=e=>g.jsxs("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:[g.jsx("path",{d:"M8 0V4",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M8 16V12",opacity:"0.5",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M3.29773 1.52783L5.64887 4.7639",opacity:"0.9",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M12.7023 1.52783L10.3511 4.7639",opacity:"0.1",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M12.7023 14.472L10.3511 11.236",opacity:"0.4",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M3.29773 14.472L5.64887 11.236",opacity:"0.6",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M15.6085 5.52783L11.8043 6.7639",opacity:"0.2",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M0.391602 10.472L4.19583 9.23598",opacity:"0.7",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M15.6085 10.4722L11.8043 9.2361",opacity:"0.3",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M0.391602 5.52783L4.19583 6.7639",opacity:"0.8",stroke:"currentColor",strokeWidth:"1.5"})]}),KQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M1 5.25V6H2.5V5.25V2.5H5.25H6V1H5.25H2C1.44772 1 1 1.44772 1 2V5.25ZM5.25 14.9994H6V13.4994H5.25H2.5V10.7494V9.99939H1V10.7494V13.9994C1 14.5517 1.44772 14.9994 2 14.9994H5.25ZM15 10V10.75V14C15 14.5523 14.5523 15 14 15H10.75H10V13.5H10.75H13.5V10.75V10H15ZM10.75 1H10V2.5H10.75H13.5V5.25V6H15V5.25V2C15 1.44772 14.5523 1 14 1H10.75Z",fill:"currentColor",fillRule:"evenodd"})}),QQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M13.5 8C13.5 4.96643 11.0257 2.5 7.96452 2.5C5.42843 2.5 3.29365 4.19393 2.63724 6.5H5.25H6V8H5.25H0.75C0.335787 8 0 7.66421 0 7.25V2.75V2H1.5V2.75V5.23347C2.57851 2.74164 5.06835 1 7.96452 1C11.8461 1 15 4.13001 15 8C15 11.87 11.8461 15 7.96452 15C5.62368 15 3.54872 13.8617 2.27046 12.1122L1.828 11.5066L3.03915 10.6217L3.48161 11.2273C4.48831 12.6051 6.12055 13.5 7.96452 13.5C11.0257 13.5 13.5 11.0336 13.5 8Z",fill:"currentColor",fillRule:"evenodd"})}),WQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M12.4697 13.5303L13 14.0607L14.0607 13L13.5303 12.4697L9.06065 7.99999L13.5303 3.53032L14.0607 2.99999L13 1.93933L12.4697 2.46966L7.99999 6.93933L3.53032 2.46966L2.99999 1.93933L1.93933 2.99999L2.46966 3.53032L6.93933 7.99999L2.46966 12.4697L1.93933 13L2.99999 14.0607L3.53032 13.5303L7.99999 9.06065L12.4697 13.5303Z",fill:"currentColor",fillRule:"evenodd"})}),ZQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M13.5 10.25V13.25C13.5 13.3881 13.3881 13.5 13.25 13.5H2.75C2.61193 13.5 2.5 13.3881 2.5 13.25L2.5 2.75C2.5 2.61193 2.61193 2.5 2.75 2.5H5.75H6.5V1H5.75H2.75C1.7835 1 1 1.7835 1 2.75V13.25C1 14.2165 1.7835 15 2.75 15H13.25C14.2165 15 15 14.2165 15 13.25V10.25V9.5H13.5V10.25ZM9 1H9.75H14.2495C14.6637 1 14.9995 1.33579 14.9995 1.75V6.25V7H13.4995V6.25V3.56066L8.53033 8.52978L8 9.06011L6.93934 7.99945L7.46967 7.46912L12.4388 2.5H9.75H9V1Z",fill:"currentColor",fillRule:"evenodd"})}),JQ=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M1.5 6.5C1.5 3.73858 3.73858 1.5 6.5 1.5C9.26142 1.5 11.5 3.73858 11.5 6.5C11.5 9.26142 9.26142 11.5 6.5 11.5C3.73858 11.5 1.5 9.26142 1.5 6.5ZM6.5 0C2.91015 0 0 2.91015 0 6.5C0 10.0899 2.91015 13 6.5 13C8.02469 13 9.42677 12.475 10.5353 11.596L13.9697 15.0303L14.5 15.5607L15.5607 14.5L15.0303 13.9697L11.596 10.5353C12.475 9.42677 13 8.02469 13 6.5C13 2.91015 10.0899 0 6.5 0ZM4.125 5.875H4.75H5.875V4.75V4.125H7.125V4.75V5.875H8.25H8.875V7.125H8.25H7.125V8.25V8.875H5.875V8.25V7.125H4.75H4.125V5.875Z",fill:"currentColor",fillRule:"evenodd"})}),eW=e=>g.jsx("svg",{color:"currentColor",height:16,strokeLinejoin:"round",viewBox:"0 0 16 16",width:16,...e,children:g.jsx("path",{clipRule:"evenodd",d:"M1.5 6.5C1.5 3.73858 3.73858 1.5 6.5 1.5C9.26142 1.5 11.5 3.73858 11.5 6.5C11.5 9.26142 9.26142 11.5 6.5 11.5C3.73858 11.5 1.5 9.26142 1.5 6.5ZM6.5 0C2.91015 0 0 2.91015 0 6.5C0 10.0899 2.91015 13 6.5 13C8.02469 13 9.42677 12.475 10.5353 11.596L13.9697 15.0303L14.5 15.5607L15.5607 14.5L15.0303 13.9697L11.596 10.5353C12.475 9.42677 13 8.02469 13 6.5C13 2.91015 10.0899 0 6.5 0ZM4.125 5.875H4.75H8.25H8.875V7.125H8.25H4.75H4.125V5.875Z",fill:"currentColor",fillRule:"evenodd"})}),zu={CheckIcon:qQ,CopyIcon:YQ,DownloadIcon:GQ,ExternalLinkIcon:ZQ,Loader2Icon:XQ,Maximize2Icon:KQ,RotateCcwIcon:QQ,XIcon:WQ,ZoomInIcon:JQ,ZoomOutIcon:eW},MN=S.createContext(zu),tW=(e,t)=>{if(e===t)return!0;if(!(e&&t))return e===t;let n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>e[i]===t[i])},DC=({icons:e,children:t})=>{let n=S.useRef(e),r=S.useRef(e?{...zu,...e}:zu);tW(n.current,e)||(n.current=e,r.current=e?{...zu,...e}:zu);let i=r.current;return g.jsx(MN.Provider,{value:i,children:t})},ds=()=>S.useContext(MN),DN={copyCode:"Copy Code",downloadFile:"Download file",downloadDiagram:"Download diagram",downloadDiagramAsSvg:"Download diagram as SVG",downloadDiagramAsPng:"Download diagram as PNG",downloadDiagramAsMmd:"Download diagram as MMD",viewFullscreen:"View fullscreen",exitFullscreen:"Exit fullscreen",mermaidFormatSvg:"SVG",mermaidFormatPng:"PNG",mermaidFormatMmd:"MMD",copyTable:"Copy table",copyTableAsMarkdown:"Copy table as Markdown",copyTableAsCsv:"Copy table as CSV",copyTableAsTsv:"Copy table as TSV",downloadTable:"Download table",downloadTableAsCsv:"Download table as CSV",downloadTableAsMarkdown:"Download table as Markdown",tableFormatMarkdown:"Markdown",tableFormatCsv:"CSV",tableFormatTsv:"TSV",imageNotAvailable:"Image not available",downloadImage:"Download image",openExternalLink:"Open external link?",externalLinkWarning:"You're about to visit an external website.",close:"Close",copyLink:"Copy link",copied:"Copied",openLink:"Open link"},Ib=S.createContext(DN),pi=()=>S.useContext(Ib),PC=({onCopy:e,onError:t,timeout:n=2e3,children:r,className:i,code:o,...l})=>{let c=St(),[f,d]=S.useState(!1),m=S.useRef(0),{code:p}=LN(),{isAnimating:b}=S.useContext(Hr),y=pi(),E=o??p,w=async()=>{var A;if(typeof window>"u"||!((A=navigator?.clipboard)!=null&&A.writeText)){t?.(new Error("Clipboard API not available"));return}try{f||(await navigator.clipboard.writeText(E),d(!0),e?.(),m.current=window.setTimeout(()=>d(!1),n))}catch(_){t?.(_)}};S.useEffect(()=>()=>{window.clearTimeout(m.current)},[]);let k=ds(),C=f?k.CheckIcon:k.CopyIcon;return g.jsx("button",{className:c("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",i),"data-streamdown":"code-block-copy-button",disabled:b,onClick:w,title:y.copyCode,type:"button",...l,children:r??g.jsx(C,{size:14})})},BC={"1c":"1c","1c-query":"1cq",abap:"abap","actionscript-3":"as",ada:"ada",adoc:"adoc","angular-html":"html","angular-ts":"ts",apache:"conf",apex:"cls",apl:"apl",applescript:"applescript",ara:"ara",asciidoc:"adoc",asm:"asm",astro:"astro",awk:"awk",ballerina:"bal",bash:"sh",bat:"bat",batch:"bat",be:"be",beancount:"beancount",berry:"berry",bibtex:"bib",bicep:"bicep",blade:"blade.php",bsl:"bsl",c:"c","c#":"cs","c++":"cpp",cadence:"cdc",cairo:"cairo",cdc:"cdc",clarity:"clar",clj:"clj",clojure:"clj","closure-templates":"soy",cmake:"cmake",cmd:"cmd",cobol:"cob",codeowners:"CODEOWNERS",codeql:"ql",coffee:"coffee",coffeescript:"coffee","common-lisp":"lisp",console:"sh",coq:"v",cpp:"cpp",cql:"cql",crystal:"cr",cs:"cs",csharp:"cs",css:"css",csv:"csv",cue:"cue",cypher:"cql",d:"d",dart:"dart",dax:"dax",desktop:"desktop",diff:"diff",docker:"dockerfile",dockerfile:"dockerfile",dotenv:"env","dream-maker":"dm",edge:"edge",elisp:"el",elixir:"ex",elm:"elm","emacs-lisp":"el",erb:"erb",erl:"erl",erlang:"erl",f:"f","f#":"fs",f03:"f03",f08:"f08",f18:"f18",f77:"f77",f90:"f90",f95:"f95",fennel:"fnl",fish:"fish",fluent:"ftl",for:"for","fortran-fixed-form":"f","fortran-free-form":"f90",fs:"fs",fsharp:"fs",fsl:"fsl",ftl:"ftl",gdresource:"tres",gdscript:"gd",gdshader:"gdshader",genie:"gs",gherkin:"feature","git-commit":"gitcommit","git-rebase":"gitrebase",gjs:"js",gleam:"gleam","glimmer-js":"js","glimmer-ts":"ts",glsl:"glsl",gnuplot:"plt",go:"go",gql:"gql",graphql:"graphql",groovy:"groovy",gts:"gts",hack:"hack",haml:"haml",handlebars:"hbs",haskell:"hs",haxe:"hx",hbs:"hbs",hcl:"hcl",hjson:"hjson",hlsl:"hlsl",hs:"hs",html:"html","html-derivative":"html",http:"http",hxml:"hxml",hy:"hy",imba:"imba",ini:"ini",jade:"jade",java:"java",javascript:"js",jinja:"jinja",jison:"jison",jl:"jl",js:"js",json:"json",json5:"json5",jsonc:"jsonc",jsonl:"jsonl",jsonnet:"jsonnet",jssm:"jssm",jsx:"jsx",julia:"jl",kotlin:"kt",kql:"kql",kt:"kt",kts:"kts",kusto:"kql",latex:"tex",lean:"lean",lean4:"lean",less:"less",liquid:"liquid",lisp:"lisp",lit:"lit",llvm:"ll",log:"log",logo:"logo",lua:"lua",luau:"luau",make:"mak",makefile:"mak",markdown:"md",marko:"marko",matlab:"m",md:"md",mdc:"mdc",mdx:"mdx",mediawiki:"wiki",mermaid:"mmd",mips:"s",mipsasm:"s",mmd:"mmd",mojo:"mojo",move:"move",nar:"nar",narrat:"narrat",nextflow:"nf",nf:"nf",nginx:"conf",nim:"nim",nix:"nix",nu:"nu",nushell:"nu",objc:"m","objective-c":"m","objective-cpp":"mm",ocaml:"ml",pascal:"pas",perl:"pl",perl6:"p6",php:"php",plsql:"pls",po:"po",polar:"polar",postcss:"pcss",pot:"pot",potx:"potx",powerquery:"pq",powershell:"ps1",prisma:"prisma",prolog:"pl",properties:"properties",proto:"proto",protobuf:"proto",ps:"ps",ps1:"ps1",pug:"pug",puppet:"pp",purescript:"purs",py:"py",python:"py",ql:"ql",qml:"qml",qmldir:"qmldir",qss:"qss",r:"r",racket:"rkt",raku:"raku",razor:"cshtml",rb:"rb",reg:"reg",regex:"regex",regexp:"regexp",rel:"rel",riscv:"s",rs:"rs",rst:"rst",ruby:"rb",rust:"rs",sas:"sas",sass:"sass",scala:"scala",scheme:"scm",scss:"scss",sdbl:"sdbl",sh:"sh",shader:"shader",shaderlab:"shader",shell:"sh",shellscript:"sh",shellsession:"sh",smalltalk:"st",solidity:"sol",soy:"soy",sparql:"rq",spl:"spl",splunk:"spl",sql:"sql","ssh-config":"config",stata:"do",styl:"styl",stylus:"styl",svelte:"svelte",swift:"swift","system-verilog":"sv",systemd:"service",talon:"talon",talonscript:"talon",tasl:"tasl",tcl:"tcl",templ:"templ",terraform:"tf",tex:"tex",tf:"tf",tfvars:"tfvars",toml:"toml",ts:"ts","ts-tags":"ts",tsp:"tsp",tsv:"tsv",tsx:"tsx",turtle:"ttl",twig:"twig",typ:"typ",typescript:"ts",typespec:"tsp",typst:"typ",v:"v",vala:"vala",vb:"vb",verilog:"v",vhdl:"vhdl",vim:"vim",viml:"vim",vimscript:"vim",vue:"vue","vue-html":"html","vue-vine":"vine",vy:"vy",vyper:"vy",wasm:"wasm",wenyan:"wy",wgsl:"wgsl",wiki:"wiki",wikitext:"wiki",wit:"wit",wl:"wl",wolfram:"wl",xml:"xml",xsl:"xsl",yaml:"yaml",yml:"yml",zenscript:"zs",zig:"zig",zsh:"zsh",文言:"wy"},nW=({onDownload:e,onError:t,language:n,children:r,className:i,code:o,...l})=>{let c=St(),{code:f}=LN(),{isAnimating:d}=S.useContext(Hr),m=pi(),p=ds(),b=o??f,y=`file.${n&&n in BC?BC[n]:"txt"}`,E="text/plain",w=()=>{try{sl(y,b,E),e?.()}catch(k){t?.(k)}};return g.jsx("button",{className:c("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",i),"data-streamdown":"code-block-download-button",disabled:d,onClick:w,title:m.downloadFile,type:"button",...l,children:r??g.jsx(p.DownloadIcon,{size:14})})},jC=()=>{let{Loader2Icon:e}=ds(),t=St();return g.jsxs("div",{className:t("w-full divide-y divide-border overflow-hidden rounded-xl border border-border"),children:[g.jsx("div",{className:t("h-[46px] w-full bg-muted/80")}),g.jsx("div",{className:t("flex w-full items-center justify-center p-4"),children:g.jsx(e,{className:t("size-4 animate-spin")})})]})},rW=/\.[^/.]+$/,sW=({node:e,className:t,src:n,alt:r,onLoad:i,onError:o,...l})=>{let{DownloadIcon:c}=ds(),f=St(),d=S.useRef(null),[m,p]=S.useState(!1),[b,y]=S.useState(!1),E=pi(),w=l.width!=null||l.height!=null,k=(m||w)&&!b,C=b&&!w;S.useEffect(()=>{let M=d.current;if(M!=null&&M.complete){let O=M.naturalWidth>0;p(O),y(!O)}},[]);let A=S.useCallback(M=>{p(!0),y(!1),i?.(M)},[i]),_=S.useCallback(M=>{p(!1),y(!0),o?.(M)},[o]),N=async()=>{if(n)try{let M=await(await fetch(n)).blob(),O=new URL(n,window.location.origin).pathname.split("/").pop()||"",P=O.split(".").pop(),D=O.includes(".")&&P!==void 0&&P.length<=4,Y="";if(D)Y=O;else{let U=M.type,$="png";U.includes("jpeg")||U.includes("jpg")?$="jpg":U.includes("png")?$="png":U.includes("svg")?$="svg":U.includes("gif")?$="gif":U.includes("webp")&&($="webp"),Y=`${(r||O||"image").replace(rW,"")}.${$}`}sl(Y,M,M.type)}catch{window.open(n,"_blank")}};return n?g.jsxs("div",{className:f("group relative my-4 inline-block"),"data-streamdown":"image-wrapper",children:[g.jsx("img",{alt:r,className:f("max-w-full rounded-lg",C&&"hidden",t),"data-streamdown":"image",onError:_,onLoad:A,ref:d,src:n,...l}),C&&g.jsx("span",{className:f("text-muted-foreground text-xs italic"),"data-streamdown":"image-fallback",children:E.imageNotAvailable}),g.jsx("div",{className:f("pointer-events-none absolute inset-0 hidden rounded-lg bg-black/10 group-hover:block")}),k&&g.jsx("button",{className:f("absolute right-2 bottom-2 flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border border-border bg-background/90 shadow-sm backdrop-blur-sm transition-all duration-200 hover:bg-background","opacity-0 group-hover:opacity-100"),onClick:N,title:E.downloadImage,type:"button",children:g.jsx(c,{size:14})})]}):null},ec=0,fx=()=>{ec+=1,ec===1&&(document.body.style.overflow="hidden")},dx=()=>{ec=Math.max(0,ec-1),ec===0&&(document.body.style.overflow="")},iW=({url:e,isOpen:t,onClose:n,onConfirm:r})=>{let{CheckIcon:i,CopyIcon:o,ExternalLinkIcon:l,XIcon:c}=ds(),f=St(),[d,m]=S.useState(!1),p=pi(),b=S.useCallback(async()=>{try{await navigator.clipboard.writeText(e),m(!0),setTimeout(()=>m(!1),2e3)}catch{}},[e]),y=S.useCallback(()=>{r(),n()},[r,n]);return S.useEffect(()=>{if(t){fx();let E=w=>{w.key==="Escape"&&n()};return document.addEventListener("keydown",E),()=>{document.removeEventListener("keydown",E),dx()}}},[t,n]),t?g.jsx("div",{className:f("fixed inset-0 z-50 flex items-center justify-center bg-background/50 backdrop-blur-sm"),"data-streamdown":"link-safety-modal",onClick:n,onKeyDown:E=>{E.key==="Escape"&&n()},role:"button",tabIndex:0,children:g.jsxs("div",{className:f("relative mx-4 flex w-full max-w-md flex-col gap-4 rounded-xl border bg-background p-6 shadow-lg"),onClick:E=>E.stopPropagation(),onKeyDown:E=>E.stopPropagation(),role:"presentation",children:[g.jsx("button",{className:f("absolute top-4 right-4 rounded-md p-1 text-muted-foreground transition-all hover:bg-muted hover:text-foreground"),onClick:n,title:p.close,type:"button",children:g.jsx(c,{size:16})}),g.jsxs("div",{className:f("flex flex-col gap-2"),children:[g.jsxs("div",{className:f("flex items-center gap-2 font-semibold text-lg"),children:[g.jsx(l,{size:20}),g.jsx("span",{children:p.openExternalLink})]}),g.jsx("p",{className:f("text-muted-foreground text-sm"),children:p.externalLinkWarning})]}),g.jsx("div",{className:f("break-all rounded-md bg-muted p-3 font-mono text-sm",e.length>100&&"max-h-32 overflow-y-auto"),children:e}),g.jsxs("div",{className:f("flex gap-2"),children:[g.jsx("button",{className:f("flex flex-1 items-center justify-center gap-2 rounded-md border bg-background px-4 py-2 font-medium text-sm transition-all hover:bg-muted"),onClick:b,type:"button",children:d?g.jsxs(g.Fragment,{children:[g.jsx(i,{size:14}),g.jsx("span",{children:p.copied})]}):g.jsxs(g.Fragment,{children:[g.jsx(o,{size:14}),g.jsx("span",{children:p.copyLink})]})}),g.jsxs("button",{className:f("flex flex-1 items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 font-medium text-primary-foreground text-sm transition-all hover:bg-primary/90"),onClick:y,type:"button",children:[g.jsx(l,{size:14}),g.jsx("span",{children:p.openLink})]})]})]})}):null},Lb=S.createContext(null),hx=()=>S.useContext(Lb),ZZ=()=>{var e;let t=hx();return(e=t?.code)!=null?e:null},px=()=>{var e;let t=hx();return(e=t?.mermaid)!=null?e:null},aW=e=>{var t;let n=hx();return n!=null&&n.renderers&&e&&(t=n.renderers.find(r=>Array.isArray(r.language)?r.language.includes(e):r.language===e))!=null?t:null},oW=(e,t)=>{var n;let r=(n=void 0)!=null?n:5;return new Promise((i,o)=>{let l="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(e))),c=new Image;c.crossOrigin="anonymous",c.onload=()=>{let f=document.createElement("canvas"),d=c.width*r,m=c.height*r;f.width=d,f.height=m;let p=f.getContext("2d");if(!p){o(new Error("Failed to create 2D canvas context for PNG export"));return}p.drawImage(c,0,0,d,m),f.toBlob(b=>{if(!b){o(new Error("Failed to create PNG blob"));return}i(b)},"image/png")},c.onerror=()=>o(new Error("Failed to load SVG image")),c.src=l})},lW=({chart:e,children:t,className:n,onDownload:r,config:i,onError:o})=>{let l=St(),[c,f]=S.useState(!1),d=S.useRef(null),{isAnimating:m}=S.useContext(Hr),p=ds(),b=px(),y=pi(),E=async w=>{try{if(w==="mmd"){sl("diagram.mmd",e,"text/plain"),f(!1),r?.(w);return}if(!b){o?.(new Error("Mermaid plugin not available"));return}let k=b.getMermaid(i),C=e.split("").reduce((N,M)=>(N<<5)-N+M.charCodeAt(0)|0,0),A=`mermaid-${Math.abs(C)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:_}=await k.render(A,e);if(!_){o?.(new Error("SVG not found. Please wait for the diagram to render."));return}if(w==="svg"){sl("diagram.svg",_,"image/svg+xml"),f(!1),r?.(w);return}if(w==="png"){let N=await oW(_);sl("diagram.png",N,"image/png"),r?.(w),f(!1);return}}catch(k){o?.(k)}};return S.useEffect(()=>{let w=k=>{let C=k.composedPath();d.current&&!C.includes(d.current)&&f(!1)};return document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w)}},[]),g.jsxs("div",{className:l("relative"),ref:d,children:[g.jsx("button",{className:l("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",n),disabled:m,onClick:()=>f(!c),title:y.downloadDiagram,type:"button",children:t??g.jsx(p.DownloadIcon,{size:14})}),c?g.jsxs("div",{className:l("absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg"),children:[g.jsx("button",{className:l("w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40"),onClick:()=>E("svg"),title:y.downloadDiagramAsSvg,type:"button",children:y.mermaidFormatSvg}),g.jsx("button",{className:l("w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40"),onClick:()=>E("png"),title:y.downloadDiagramAsPng,type:"button",children:y.mermaidFormatPng}),g.jsx("button",{className:l("w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40"),onClick:()=>E("mmd"),title:y.downloadDiagramAsMmd,type:"button",children:y.mermaidFormatMmd})]}):null]})},uW=({chart:e,config:t,onFullscreen:n,onExit:r,className:i,...o})=>{let{Maximize2Icon:l,XIcon:c}=ds(),f=St(),[d,m]=S.useState(!1),{isAnimating:p,controls:b}=S.useContext(Hr),y=pi(),E=(()=>{if(typeof b=="boolean")return b;let k=b.mermaid;return k===!1?!1:k===!0||k===void 0?!0:k.panZoom!==!1})(),w=()=>{m(!d)};return S.useEffect(()=>{if(d){fx();let k=C=>{C.key==="Escape"&&m(!1)};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k),dx()}}},[d]),S.useEffect(()=>{d?n?.():r&&r()},[d,n,r]),g.jsxs(g.Fragment,{children:[g.jsx("button",{className:f("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",i),disabled:p,onClick:w,title:y.viewFullscreen,type:"button",...o,children:g.jsx(l,{size:14})}),d?cs.createPortal(g.jsxs("div",{className:f("fixed inset-0 z-50 flex items-center justify-center bg-background/95 backdrop-blur-sm"),onClick:w,onKeyDown:k=>{k.key==="Escape"&&w()},role:"button",tabIndex:0,children:[g.jsx("button",{className:f("absolute top-4 right-4 z-10 rounded-md p-2 text-muted-foreground transition-all hover:bg-muted hover:text-foreground"),onClick:w,title:y.exitFullscreen,type:"button",children:g.jsx(c,{size:20})}),g.jsx("div",{className:f("flex size-full items-center justify-center p-4"),onClick:k=>k.stopPropagation(),onKeyDown:k=>k.stopPropagation(),role:"presentation",children:g.jsx(gR,{chart:e,className:f("size-full [&_svg]:h-auto [&_svg]:w-auto"),config:t,fullscreen:!0,showControls:E})})]}),document.body):null]})},PN=e=>{var t,n;let r=[],i=[],o=e.querySelectorAll("thead th");for(let c of o)r.push(((t=c.textContent)==null?void 0:t.trim())||"");let l=e.querySelectorAll("tbody tr");for(let c of l){let f=[],d=c.querySelectorAll("td");for(let m of d)f.push(((n=m.textContent)==null?void 0:n.trim())||"");i.push(f)}return{headers:r,rows:i}},BN=e=>{let{headers:t,rows:n}=e,r=c=>{let f=!1,d=!1;for(let m of c){if(m==='"'){f=!0,d=!0;break}(m===","||m===`
463
463
  `)&&(f=!0)}return f?d?`"${c.replace(/"/g,'""')}"`:`"${c}"`:c},i=t.length>0?n.length+1:n.length,o=new Array(i),l=0;t.length>0&&(o[l]=t.map(r).join(","),l+=1);for(let c of n)o[l]=c.map(r).join(","),l+=1;return o.join(`
464
464
  `)},cW=e=>{let{headers:t,rows:n}=e,r=c=>{let f=!1;for(let m of c)if(m===" "||m===`
@@ -478,4 +478,4 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
478
478
  `);return`${l}${m}${f}
479
479
 
480
480
  `})}return n},$W=/([\\`*_~[\]|])/g,qW=e=>e.replace($W,"\\$1"),YW=(e,t)=>{if(!t.length)return e;let n=e;for(let r of t){let i=new RegExp(`(<${r}(?=[\\s>/])[^>]*>)([\\s\\S]*?)(</${r}\\s*>)`,"gi");n=n.replace(i,(o,l,c,f)=>{let d=qW(c).replace(/\n\n/g,"&#10;&#10;");return l+d+f})}return n},fR=e=>e.type==="text"?e.value:"children"in e&&Array.isArray(e.children)?e.children.map(fR).join(""):"",GW=e=>t=>{if(!e||e.length===0)return;let n=new Set(e.map(r=>r.toLowerCase()));Is(t,"element",r=>{if(n.has(r.tagName.toLowerCase())){let i=fR(r);r.children=i?[{type:"text",value:i}]:[]}})},XW=()=>e=>{Is(e,"code",t=>{var n,r;t.meta&&(t.data=(n=t.data)!=null?n:{},t.data.hProperties={...(r=t.data.hProperties)!=null?r:{},metastring:t.meta})})},KW=/^[ \t]*<[\w!/?-]/,QW=/(^|\n)[ \t]{4,}(?=<[\w!/?-])/g,WW=e=>typeof e!="string"||e.length===0||!KW.test(e)?e:e.replace(QW,"$1"),KC,QC,WC,ZC,Gd={...Ba,protocols:{...Ba.protocols,href:[...(QC=(KC=Ba.protocols)==null?void 0:KC.href)!=null?QC:[],"tel"]},attributes:{...Ba.attributes,code:[...(ZC=(WC=Ba.attributes)==null?void 0:WC.code)!=null?ZC:[],"metastring"]}},Pb={raw:yb,sanitize:[T_,Gd],harden:[Yj,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},ZW={gfm:[cY,{}],codeMeta:XW},JC=Object.values(Pb),JW=Object.values(ZW),eZ={block:" ▋",circle:" ●"},dR=["github-light","github-dark"],hR={enabled:!0},tZ={shikiTheme:dR,controls:!0,isAnimating:!1,lineNumbers:!0,mode:"streaming",mermaid:void 0,linkSafety:hR},Hr=S.createContext(tZ),pR=S.memo(({content:e,shouldParseIncompleteMarkdown:t,shouldNormalizeHtmlIndentation:n,index:r,isIncomplete:i,dir:o,animatePlugin:l,...c})=>{if(l){let m=l.getLastRenderCharCount();l.setPrevContentLength(m)}let f=typeof e=="string"&&n?WW(e):e,d=g.jsx(cR,{...c,children:f});return g.jsx(ON.Provider,{value:i,children:o?g.jsx("div",{dir:o,style:{display:"contents"},children:d}):d})},(e,t)=>{if(e.content!==t.content||e.shouldNormalizeHtmlIndentation!==t.shouldNormalizeHtmlIndentation||e.index!==t.index||e.isIncomplete!==t.isIncomplete||e.dir!==t.dir)return!1;if(e.components!==t.components){let n=Object.keys(e.components||{}),r=Object.keys(t.components||{});if(n.length!==r.length||n.some(i=>{var o,l;return((o=e.components)==null?void 0:o[i])!==((l=t.components)==null?void 0:l[i])}))return!1}return!(e.rehypePlugins!==t.rehypePlugins||e.remarkPlugins!==t.remarkPlugins)});pR.displayName="Block";var mR=S.memo(({children:e,mode:t="streaming",dir:n,parseIncompleteMarkdown:r=!0,normalizeHtmlIndentation:i=!1,components:o,rehypePlugins:l=JC,remarkPlugins:c=JW,className:f,shikiTheme:d=dR,mermaid:m,controls:p=!0,isAnimating:b=!1,animated:y,BlockComponent:E=pR,parseMarkdownIntoBlocksFn:w=FW,caret:k,plugins:C,remend:A,linkSafety:_=hR,lineNumbers:N=!0,allowedTags:M,literalTagContent:O,translations:P,icons:D,prefix:Y,onAnimationStart:U,onAnimationEnd:$,...Q})=>{let J=S.useId(),[te,G]=S.useTransition(),H=S.useMemo(()=>PQ(Y),[Y]),K=S.useRef(null),ee=S.useRef(U),le=S.useRef($);ee.current=U,le.current=$,S.useEffect(()=>{var Ce,we,je;if(t==="static")return;let $e=K.current;if(K.current=b,$e===null){b&&((Ce=ee.current)==null||Ce.call(ee));return}b&&!$e?(we=ee.current)==null||we.call(ee):!b&&$e&&((je=le.current)==null||je.call(le))},[b,t]);let I=S.useMemo(()=>M?Object.keys(M):[],[M]),B=S.useMemo(()=>{if(typeof e!="string")return"";let Ce=t==="streaming"&&r?TG(e,A):e;return O&&O.length>0&&(Ce=YW(Ce,O)),I.length>0&&(Ce=VW(Ce,I)),Ce},[e,t,r,A,I,O]),q=S.useMemo(()=>w(B),[B,w]),[L,ae]=S.useState(q);S.useEffect(()=>{t==="streaming"&&!ve?G(()=>{ae(q)}):ae(q)},[q,t]);let ie=t==="streaming"?L:q,fe=S.useMemo(()=>n==="auto"?ie.map(UC):void 0,[ie,n]),de=S.useMemo(()=>ie.map((Ce,we)=>`${J}-${we}`),[ie.length,J]),he=S.useMemo(()=>y===!0?"true":y?JSON.stringify(y):"",[y]),ve=S.useMemo(()=>he?he==="true"?Rb():Rb(y):null,[he]),Ue=S.useMemo(()=>{var Ce,we;return{shikiTheme:(we=(Ce=C?.code)==null?void 0:Ce.getThemes())!=null?we:d,controls:p,isAnimating:b,lineNumbers:N,mode:t,mermaid:m,linkSafety:_}},[d,p,b,N,t,m,_,C?.code]),Pe=S.useMemo(()=>P?JSON.stringify(P):"",[P]),Te=S.useMemo(()=>({...DN,...P}),[Pe]),Ie=S.useMemo(()=>{let{inlineCode:Ce,...we}=o??{},je={...yW,...we};if(Ce){let $e=je.code;je.code=W=>"data-block"in W?$e?S.createElement($e,W):null:S.createElement(Ce,W)}return je},[o]),Be=S.useMemo(()=>{let Ce=[];return C!=null&&C.cjk&&(Ce=[...Ce,...C.cjk.remarkPluginsBefore]),Ce=[...Ce,...c],C!=null&&C.cjk&&(Ce=[...Ce,...C.cjk.remarkPluginsAfter]),C!=null&&C.math&&(Ce=[...Ce,C.math.remarkPlugin]),Ce},[c,C?.math,C?.cjk]),We=S.useMemo(()=>{var Ce;let we=l;if(M&&Object.keys(M).length>0&&l===JC){let je={...Gd,tagNames:[...(Ce=Gd.tagNames)!=null?Ce:[],...Object.keys(M)],attributes:{...Gd.attributes,...M}};we=[Pb.raw,[T_,je],Pb.harden]}return O&&O.length>0&&(we=[...we,[GW,O]]),C!=null&&C.math&&(we=[...we,C.math.rehypePlugin]),ve&&b&&(we=[...we,ve.rehypePlugin]),we},[l,C?.math,ve,b,M,O]),Xe=S.useMemo(()=>{if(!b||ie.length===0)return!1;let Ce=ie.at(-1);return zC(Ce)||CW(Ce)},[b,ie]),Me=S.useMemo(()=>k&&b&&!Xe?{"--streamdown-caret":`"${eZ[k]}"`}:void 0,[k,b,Xe]);return t==="static"?g.jsx(Ib.Provider,{value:Te,children:g.jsx(Lb.Provider,{value:C??null,children:g.jsx(Hr.Provider,{value:Ue,children:g.jsx(DC,{icons:D,children:g.jsx(Ob.Provider,{value:H,children:g.jsx("div",{className:H("space-y-4 whitespace-normal [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",f),dir:n==="auto"?UC(B):n,children:g.jsx(cR,{components:Ie,rehypePlugins:We,remarkPlugins:Be,...Q,children:B})})})})})})}):g.jsx(Ib.Provider,{value:Te,children:g.jsx(Lb.Provider,{value:C??null,children:g.jsx(Hr.Provider,{value:Ue,children:g.jsx(DC,{icons:D,children:g.jsx(Ob.Provider,{value:H,children:g.jsxs("div",{className:H("space-y-4 whitespace-normal [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",k&&!Xe?"[&>*:last-child]:after:inline [&>*:last-child]:after:align-baseline [&>*:last-child]:after:content-[var(--streamdown-caret)]":null,f),style:Me,children:[ie.length===0&&k&&b&&g.jsx("span",{}),ie.map((Ce,we)=>{var je;let $e=we===ie.length-1,W=b&&$e&&zC(Ce);return g.jsx(E,{animatePlugin:ve,components:Ie,content:Ce,dir:(je=fe?.[we])!=null?je:n!=="auto"?n:void 0,index:we,isIncomplete:W,rehypePlugins:We,remarkPlugins:Be,shouldNormalizeHtmlIndentation:i,shouldParseIncompleteMarkdown:r,...Q},de[we])})]})})})})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&e.animated===t.animated&&e.mode===t.mode&&e.plugins===t.plugins&&e.className===t.className&&e.linkSafety===t.linkSafety&&e.lineNumbers===t.lineNumbers&&e.normalizeHtmlIndentation===t.normalizeHtmlIndentation&&e.literalTagContent===t.literalTagContent&&JSON.stringify(e.translations)===JSON.stringify(t.translations)&&e.prefix===t.prefix&&e.dir===t.dir);mR.displayName="Streamdown";var nZ=({children:e,className:t,minZoom:n=.5,maxZoom:r=3,zoomStep:i=.1,showControls:o=!0,initialZoom:l=1,fullscreen:c=!1})=>{let{RotateCcwIcon:f,ZoomInIcon:d,ZoomOutIcon:m}=ds(),p=St(),b=S.useRef(null),y=S.useRef(null),[E,w]=S.useState(l),[k,C]=S.useState({x:0,y:0}),[A,_]=S.useState(!1),[N,M]=S.useState({x:0,y:0}),[O,P]=S.useState({x:0,y:0}),D=S.useCallback(H=>{w(K=>Math.max(n,Math.min(r,K+H)))},[n,r]),Y=S.useCallback(()=>{D(i)},[D,i]),U=S.useCallback(()=>{D(-i)},[D,i]),$=S.useCallback(()=>{w(l),C({x:0,y:0})},[l]),Q=S.useCallback(H=>{H.preventDefault();let K=H.deltaY>0?-i:i;D(K)},[D,i]),J=S.useCallback(H=>{if(H.button!==0||H.isPrimary===!1)return;_(!0),M({x:H.clientX,y:H.clientY}),P(k);let K=H.currentTarget;K instanceof HTMLElement&&K.setPointerCapture(H.pointerId)},[k]),te=S.useCallback(H=>{if(!A)return;H.preventDefault();let K=H.clientX-N.x,ee=H.clientY-N.y;C({x:O.x+K,y:O.y+ee})},[A,N,O]),G=S.useCallback(H=>{_(!1);let K=H.currentTarget;K instanceof HTMLElement&&K.releasePointerCapture(H.pointerId)},[]);return S.useEffect(()=>{let H=b.current;if(H)return H.addEventListener("wheel",Q,{passive:!1}),()=>{H.removeEventListener("wheel",Q)}},[Q]),S.useEffect(()=>{let H=y.current;if(H&&A)return document.body.style.userSelect="none",H.addEventListener("pointermove",te,{passive:!1}),H.addEventListener("pointerup",G),H.addEventListener("pointercancel",G),()=>{document.body.style.userSelect="",H.removeEventListener("pointermove",te),H.removeEventListener("pointerup",G),H.removeEventListener("pointercancel",G)}},[A,te,G]),g.jsxs("div",{className:p("relative flex flex-col",c?"h-full w-full":"min-h-28 w-full",t),ref:b,style:{cursor:A?"grabbing":"grab"},children:[o?g.jsxs("div",{className:p("absolute z-10 flex flex-col gap-1 rounded-md border border-border bg-background/80 p-1 supports-[backdrop-filter]:bg-background/70 supports-[backdrop-filter]:backdrop-blur-sm",c?"bottom-4 left-4":"bottom-2 left-2"),children:[g.jsx("button",{className:p("flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"),disabled:E>=r,onClick:Y,title:"Zoom in",type:"button",children:g.jsx(d,{size:16})}),g.jsx("button",{className:p("flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"),disabled:E<=n,onClick:U,title:"Zoom out",type:"button",children:g.jsx(m,{size:16})}),g.jsx("button",{className:p("flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"),onClick:$,title:"Reset zoom and pan",type:"button",children:g.jsx(f,{size:16})})]}):null,g.jsx("div",{className:p("flex-1 origin-center transition-transform duration-150 ease-out",c?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:J,ref:y,role:"application",style:{transform:`translate(${k.x}px, ${k.y}px) scale(${E})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},gR=({chart:e,className:t,config:n,fullscreen:r=!1,showControls:i=!0})=>{let o=St(),[l,c]=S.useState(null),[f,d]=S.useState(!1),[m,p]=S.useState(""),[b,y]=S.useState(""),[E,w]=S.useState(0),{mermaid:k}=S.useContext(Hr),C=px(),A=k?.errorComponent,{shouldRender:_,containerRef:N}=CQ({immediate:r});if(S.useEffect(()=>{if(_){if(!C){c("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{c(null),d(!0);let O=C.getMermaid(n),P=e.split("").reduce((U,$)=>(U<<5)-U+$.charCodeAt(0)|0,0),D=`mermaid-${Math.abs(P)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:Y}=await O.render(D,e);p(Y),y(Y)}catch(O){if(!(b||m)){let P=O instanceof Error?O.message:"Failed to render Mermaid chart";c(P)}}finally{d(!1)}})()}},[e,n,E,_,C]),!(_||m||b))return g.jsx("div",{className:o("my-4 min-h-[200px]",t),ref:N});if(f&&!m&&!b)return g.jsx("div",{className:o("my-4 flex justify-center p-4",t),ref:N,children:g.jsxs("div",{className:o("flex items-center space-x-2 text-muted-foreground"),children:[g.jsx("div",{className:o("h-4 w-4 animate-spin rounded-full border-current border-b-2")}),g.jsx("span",{className:o("text-sm"),children:"Loading diagram..."})]})});if(l&&!m&&!b){let O=()=>w(P=>P+1);return A?g.jsx("div",{ref:N,children:g.jsx(A,{chart:e,error:l,retry:O})}):g.jsxs("div",{className:o("rounded-md bg-red-50 p-4",t),ref:N,children:[g.jsxs("p",{className:o("font-mono text-red-700 text-sm"),children:["Mermaid Error: ",l]}),g.jsxs("details",{className:o("mt-2"),children:[g.jsx("summary",{className:o("cursor-pointer text-red-600 text-xs"),children:"Show Code"}),g.jsx("pre",{className:o("mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs"),children:e})]})]})}let M=m||b;return g.jsx("div",{className:o("size-full",t),"data-streamdown":"mermaid",ref:N,children:g.jsx(nZ,{className:o(r?"size-full overflow-hidden":"overflow-hidden",t),fullscreen:r,maxZoom:3,minZoom:.5,showControls:i,zoomStep:.1,children:g.jsx("div",{"aria-label":"Mermaid chart",className:o("flex justify-center",r?"size-full items-center":null),dangerouslySetInnerHTML:{__html:M},role:"img"})})})};const bR=S.memo(function({children:t,streaming:n,className:r}){return g.jsx(mR,{mode:n?"streaming":"static",parseIncompleteMarkdown:n,shikiTheme:["github-light","github-dark"],className:He("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",r),children:t})},(e,t)=>e.children===t.children&&e.streaming===t.streaming&&e.className===t.className);function rZ({children:e,isStreaming:t=!1,defaultOpen:n,className:r}){const[i,o]=S.useState(n??t),l=S.useRef(!1);S.useEffect(()=>{if(!l.current)if(t)o(!0);else{const f=setTimeout(()=>o(!1),600);return()=>clearTimeout(f)}},[t]);const c=e.trim()!=="";return!c&&!t?null:g.jsxs("div",{"data-slot":"reasoning","data-streaming":t||void 0,className:He("w-full",r),children:[g.jsxs("button",{type:"button",disabled:!c,onClick:()=>{l.current=!0,o(f=>!f)},className:"flex items-center gap-1.5 text-label text-fg-3 transition-colors outline-none disabled:cursor-default hover:text-fg-1 disabled:hover:text-fg-3",children:[g.jsx(vP,{className:"size-3.5"}),g.jsx("span",{children:t?"Thinking…":"Thought process"}),c?g.jsx(j3,{className:He("size-3.5 transition-transform",i&&"rotate-180")}):null]}),i&&c?g.jsx("div",{className:"mt-2 border-l-2 border-border pl-3 text-body-sm text-fg-3 [&_*]:text-fg-3",children:g.jsx(bR,{streaming:t,children:e})}):null]})}const ew=2e3,sZ={running:{label:"Running",variant:"info",busy:!0},pending:{label:"Executing",variant:"info",busy:!0},deferred:{label:"Deferred",variant:"accent",busy:!1},settled:{label:"Done",variant:"success",busy:!1},failed:{label:"Error",variant:"danger",busy:!1}};function iZ({item:e,className:t}){const[n,r]=S.useState(!1),[i,o]=S.useState(!1),l=e.status??(e.result===void 0?"running":"settled"),c=sZ[l],f=l==="failed"||e.result?.isError===!0,d=e.result?.text??"",m=!i&&d.length>ew,p=m?d.slice(0,ew):d;return g.jsxs("div",{"data-slot":"tool-call","data-state":l,className:He("w-full overflow-hidden rounded-lg border border-border bg-surface",t),children:[g.jsxs("button",{type:"button",onClick:()=>r(b=>!b),className:He("flex w-full items-center gap-2 px-3 py-2 text-left transition-colors outline-none","hover:bg-surface-hover focus-visible:bg-surface-hover"),children:[g.jsx(v9,{className:"size-3.5 shrink-0 text-fg-3"}),g.jsx("span",{className:"shrink-0 font-mono text-body-sm font-medium text-fg-1",children:e.name}),g.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-label text-fg-4",children:Cj(e.input)}),g.jsxs(ts,{variant:c.variant,dot:!c.busy,className:"shrink-0 gap-1",children:[c.busy?g.jsx(ci,{className:"size-3 text-current"}):null,l==="deferred"?g.jsx(RP,{className:"size-3 text-current"}):null,c.label]}),g.jsx(j3,{className:He("size-3.5 shrink-0 text-fg-4 transition-transform",n&&"rotate-180")})]}),n?g.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-2.5",children:[g.jsx(ag,{code:JSON.stringify(e.input,null,2),label:"Parameters"}),e.logs?.length?g.jsx(ag,{code:e.logs.join(`
481
- `),label:"Logs"}):null,e.result!==void 0?g.jsxs("div",{children:[g.jsx(ag,{code:p||"(empty result)",label:f?"Error":"Result",className:He(f&&"border-danger/40 [&_pre]:text-danger")}),m?g.jsxs("button",{type:"button",className:"mt-1 text-label text-fg-3 underline-offset-2 hover:underline",onClick:()=>o(!0),children:["Show all ",d.length.toLocaleString()," chars"]}):null]}):null]}):null]})}function aZ({item:e}){return g.jsxs("div",{"data-slot":"turn-result",className:"flex items-center gap-2 py-1",children:[g.jsx("div",{className:"h-px flex-1 bg-border"}),g.jsxs("span",{className:He("font-mono text-label",e.isError?"text-danger":"text-fg-4"),children:[e.isError?e.subtype:"turn done"," · ",vj(e.durationMs)," ·"," ",tp(e.totalCostUsd)]}),g.jsx("div",{className:"h-px flex-1 bg-border"})]})}function oZ({item:e}){return g.jsx("div",{"data-slot":"notice",className:He("rounded-md border px-3 py-2 text-body-sm",e.level==="error"?"border-transparent bg-danger-bg text-danger":"border-border bg-surface text-fg-3"),children:e.text})}function lZ({item:e,fileUrl:t}){switch(e.kind){case"user":return g.jsx(fS,{from:"user",children:g.jsx(dS,{children:e.text})});case"assistant_text":return g.jsx(fS,{from:"assistant",children:g.jsx(dS,{children:g.jsx(bR,{streaming:e.streaming,children:e.text})})});case"thinking":return g.jsx(rZ,{isStreaming:e.id==="streaming-thinking",children:e.text});case"tool_call":return g.jsx(iZ,{item:e});case"turn_result":return g.jsx(aZ,{item:e});case"notice":return g.jsx(oZ,{item:e});case"file_delivered":return g.jsx(jj,{item:e,href:t?.(e.path)});default:return null}}function uZ(e){if(e.status!=="running"&&e.status!=="starting")return!1;const t=e.items.at(-1);return t?t.kind==="assistant_text"&&t.streaming||t.kind==="thinking"&&t.id==="streaming-thinking"?!1:t.kind!=="turn_result"||e.status==="running":!0}function cZ({state:e,fileUrl:t,className:n}){return g.jsxs(Dj,{className:n,children:[g.jsxs(Pj,{children:[e.items.length===0&&e.status!=="starting"?g.jsx("div",{className:"py-12 text-center text-body-sm text-fg-4",children:"No messages yet."}):e.items.map(r=>g.jsx(lZ,{item:r,fileUrl:t},`${r.kind}:${r.id}`)),uZ(e)?g.jsx(Hj,{label:e.status==="starting"?"Starting session…":void 0}):null]}),g.jsx(Bj,{})]})}function fZ({client:e,sessionId:t,header:n,className:r}){const[i,o]=S.useState(void 0),{state:l,connected:c,handle:f,send:d,approve:m,deny:p,interrupt:b,setModel:y,setPermissionMode:E}=fj(e,t,{onProtocolError:o});S.useEffect(()=>o(void 0),[t]),gj(f);const w=l.status==="running"||l.status==="awaiting_approval",k=l.status==="failed"||l.status==="closed",C=S.useMemo(()=>{if(l.commands)return l.commands.some(_=>_.name==="model")?l.commands:[{name:"model",description:"Switch the model for this session",argumentHint:"<model>"},...l.commands]},[l.commands]),A=_=>{const N=/^\/model\s+(\S+)$/.exec(_);if(N){y(N[1]);return}d(_)};return g.jsxs("div",{"data-slot":"session-panel",className:He("flex h-full min-h-0 flex-col overflow-hidden bg-bg",r),children:[n,g.jsx(_j,{state:l,connected:c}),i?g.jsx("div",{className:"px-3 pt-2",children:g.jsxs("div",{role:"alert",className:"mx-auto flex w-full max-w-3xl items-start gap-2 rounded-md border border-danger/40 bg-danger-bg px-3 py-2 text-body-sm text-danger",children:[g.jsx("span",{className:"min-w-0 flex-1 break-words",children:i}),g.jsx("button",{type:"button",onClick:()=>o(void 0),"aria-label":"Dismiss error",className:"shrink-0 opacity-70 transition-opacity hover:opacity-100",children:"✕"})]})}):null,g.jsx(cZ,{state:l,fileUrl:t?_=>e.sessionFileUrl(t,_):void 0}),l.pendingApprovals.length>0?g.jsx("div",{className:"px-3 pb-2",children:g.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-2",children:l.pendingApprovals.map(_=>_.toolName==="AskUserQuestion"&&pA(_.input).length>0?g.jsx(Tj,{request:_,onAnswer:m,onDismiss:p},_.id):g.jsx(Ej,{request:_,onApprove:m,onDeny:p},_.id))})}):null,g.jsx(xj,{onSend:A,onInterrupt:b,busy:w,disabled:k||!t,commands:C,toolbar:g.jsxs(g.Fragment,{children:[l.models?.length?g.jsx(hA,{models:l.models,model:l.model,onModelChange:y,disabled:k}):null,l.permissionMode?g.jsx(Rc,{mode:l.permissionMode,onModeChange:E,modes:l.engine==="provider"?ep:void 0,disabled:k}):null]})})]})}function dZ({session:e,active:t,onSelect:n,onDelete:r}){const i=mA[e.status];return g.jsxs("div",{"data-slot":"session-list-item","data-active":t||void 0,className:He("group flex w-full items-center gap-2 rounded-md border border-transparent px-2.5 py-2 text-left transition-colors",t?"border-border bg-surface":"hover:bg-surface-hover"),children:[g.jsxs("button",{type:"button",onClick:()=>n?.(e.id),className:"min-w-0 flex-1 text-left outline-none",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"truncate text-body-sm font-medium text-fg-1",children:e.title??e.id.slice(0,8)}),g.jsx(ts,{variant:i.variant,dot:!0,className:"shrink-0",children:i.label})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 font-mono text-label text-fg-4",children:[g.jsx("span",{className:"truncate",children:e.cwd}),e.profile?g.jsxs("span",{className:"shrink-0",children:["@",e.profile]}):null,g.jsx("span",{className:"shrink-0",children:tp(e.totalCostUsd)}),g.jsx("span",{className:"shrink-0",children:R1(e.lastActivityAt??e.createdAt)})]})]}),r?g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Close session",className:"opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e.id),children:g.jsx(A1,{className:"size-3.5 text-fg-3"})}):null]})}function hZ({sessions:e,activeId:t,onSelect:n,onDelete:r,emptyText:i="No sessions yet.",className:o}){return g.jsx("div",{"data-slot":"session-list",className:He("flex flex-col gap-1",o),children:e.length===0?g.jsx("div",{className:"px-2.5 py-6 text-center text-body-sm text-fg-4",children:i}):e.map(l=>g.jsx(dZ,{session:l,active:l.id===t,onSelect:n,onDelete:r},l.id))})}function pZ({className:e}){return g.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e,children:[g.jsx("path",{d:"M8 3.5h9A3.5 3.5 0 0 1 20.5 7v9"}),g.jsx("rect",{width:"13.5",height:"13.5",x:"3.5",y:"7",rx:"3.5"}),g.jsx("path",{d:"m7 16.5 2.5-2.5L7 11.5"}),g.jsx("circle",{cx:"13.2",cy:"14",r:"1.7",fill:"#2fbf71",stroke:"none"})]})}function xR(){const[e,t]=S.useState(Ub());return g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Toggle theme",onClick:()=>t(WO()),children:e==="dark"?g.jsx(h9,{className:"size-4"}):g.jsx(KP,{className:"size-4"})})}const mZ=[{id:"sessions",label:"Sessions",icon:u9,path:"/sessions"},{id:"jobs",label:"Jobs",icon:z3,path:"/jobs"},{id:"profiles",label:"Profiles",icon:x9,path:"/profiles"},{id:"settings",label:"Settings",icon:i9,path:"/settings"}],tw="workerdeck.sidebar-collapsed";function gZ({children:e}){const t=FI({select:o=>o.location.pathname}),[n,r]=S.useState(()=>{try{return localStorage.getItem(tw)==="1"}catch{return!1}}),i=()=>{r(o=>{try{localStorage.setItem(tw,o?"0":"1")}catch{}return!o})};return g.jsxs("div",{className:"flex h-dvh bg-sidebar",children:[g.jsxs("aside",{className:He("flex shrink-0 flex-col gap-1 p-3 transition-[width] duration-150",n?"w-14 items-center":"w-52"),children:[g.jsxs("div",{className:He("flex items-center py-2",n?"justify-center":"gap-2 px-2"),children:[g.jsx(pZ,{className:"size-4 shrink-0 text-fg-1"}),!n&&g.jsx("span",{className:"text-body-sm font-semibold tracking-tight text-fg-1",children:"workerdeck"})]}),g.jsx("nav",{className:He("mt-1 flex flex-1 flex-col gap-0.5",n&&"items-center"),children:mZ.map(o=>{const l=t.startsWith(o.path);return g.jsxs(yc,{to:o.path,title:n?o.label:void 0,"aria-label":o.label,className:He("flex items-center rounded-md text-body-sm transition-colors outline-none",n?"justify-center p-2":"gap-2 px-2 py-1.5",l?"bg-surface font-medium text-fg-1 shadow-(--shadow-xs)":"text-fg-3 hover:bg-surface-hover hover:text-fg-1"),children:[g.jsx(o.icon,{className:"size-4 shrink-0"}),!n&&o.label]},o.id)})}),g.jsxs("div",{className:He("flex items-center",n?"flex-col gap-1":"justify-between px-1"),children:[!n&&g.jsx("span",{className:"font-mono text-label text-fg-4",children:"v0.1"}),g.jsx(xR,{}),g.jsx("button",{type:"button",onClick:i,title:n?"Expand sidebar":"Collapse sidebar","aria-label":n?"Expand sidebar":"Collapse sidebar",className:"flex size-7 items-center justify-center rounded-md text-fg-3 transition-colors outline-none hover:bg-surface-hover hover:text-fg-1",children:n?g.jsx(JP,{className:"size-4"}):g.jsx(WP,{className:"size-4"})})]})]}),g.jsx("main",{className:"frame-shine m-2 ml-0 flex min-w-0 flex-1 flex-col overflow-hidden rounded-xl",children:e??g.jsx(Fw,{})})]})}const yR=[{value:"default",displayName:"Default (recommended)",description:"The CLI's configured default model"},{value:"fable",displayName:"Fable",description:"Fable 5 · Most capable for your hardest and longest-running tasks"},{value:"opus",displayName:"Opus",description:"Opus 4.8 with 1M context · Best for everyday, complex tasks"},{value:"sonnet",displayName:"Sonnet",description:"Sonnet 5 · Efficient for routine tasks"},{value:"haiku",displayName:"Haiku",description:"Haiku 4.5 · Fastest for quick answers"}],Bb={session:"workerdeck.default-session-model",job:"workerdeck.default-job-model"};function gx(e){return localStorage.getItem(Bb[e])??""}function bZ(e,t){const n=t.trim();n?localStorage.setItem(Bb[e],n):localStorage.removeItem(Bb[e])}const ER={session:"workerdeck.default-session-permission-mode",job:"workerdeck.default-job-permission-mode"},xZ={session:"default",job:"acceptEdits"};function bx(e){const t=localStorage.getItem(ER[e]);return cb.some(r=>r.value===t)?t:xZ[e]}function yZ(e,t){localStorage.setItem(ER[e],t)}function xx({value:e,onChange:t,models:n=yR,className:r}){return g.jsx(hA,{variant:"form",models:n,model:e||void 0,onModelChange:i=>t(i??""),className:r})}function TR({profiles:e,value:t,onChange:n,className:r}){return e.length===0?null:g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Profile"}),g.jsxs(Cc,{items:e.map(i=>({value:i.name,label:i.name})),value:t,onValueChange:i=>n(i),children:[g.jsx(kc,{className:r,children:g.jsx(wc,{})}),g.jsx(Ac,{children:e.map(i=>g.jsx(cl,{value:i.name,children:g.jsx(ul,{children:i.description?`${i.name} — ${i.description}`:i.name})},i.name))})]})]})}class EZ{sessionId;#t;#r;#n;#e=new Map;#s;#l=!1;#u=0;#i=[];#c;constructor(t,n,r={}){this.#t=t,this.sessionId=n,this.#r={reconnect:!0,...r},this.#s=r.afterSeq??0,this.#c=setTimeout(()=>this.#f(),0)}get lastSeq(){return this.#s}on(t,n){let r=this.#e.get(t);return r||(r=new Set,this.#e.set(t,r)),r.add(n),()=>r.delete(n)}send(t){this.#a({type:"user_message",text:t})}approve(t,n){this.#a({type:"permission_decision",requestId:t,behavior:"allow",updatedInput:n})}deny(t,n,r){this.#a({type:"permission_decision",requestId:t,behavior:"deny",message:n,interrupt:r})}interrupt(){this.#a({type:"interrupt"})}setPermissionMode(t){this.#a({type:"set_permission_mode",mode:t})}setModel(t){this.#a({type:"set_model",model:t})}sendToolCallResult(t,n,r){this.#a({type:"tool_call_result",executionId:t,output:n,logs:r})}sendToolCallError(t,n,r,i){this.#a({type:"tool_call_error",executionId:t,reason:n,error:r,logs:i})}closeSession(){this.#a({type:"close"}),this.detach()}detach(){this.#l=!0,clearTimeout(this.#c),this.#n?.close(),this.#n=void 0}#o(t,n){const r=this.#e.get(t);if(r)for(const i of r)try{i(n)}catch{}}#a(t){const n=JSON.stringify(t);this.#n&&this.#n.readyState===1?this.#n.send(n):this.#i.push(n)}#f(){if(this.#l)return;const t=this.#t.openSocket(this.sessionId,this.#s);this.#n=t,t.onopen=()=>{this.#u=0,this.#o("connectionChange",!0);for(const n of this.#i.splice(0))t.send(n)},t.onmessage=n=>{const r=JSON.parse(String(n.data));if(r.type==="attached")this.#o("attached",r);else if(r.type==="event"){if(r.event.seq<=this.#s)return;this.#s=r.event.seq,this.#o("event",r.event)}else r.type==="tool_call_request"?this.#o("toolCallRequest",r):r.type==="tool_call_canceled"?this.#o("toolCallCanceled",{executionId:r.executionId,reason:r.reason}):r.type==="protocol_error"&&this.#o("protocolError",r.message)},t.onclose=()=>{if(this.#o("connectionChange",!1),this.#l||!this.#r.reconnect)return;const n=Math.min(500*2**this.#u++,1e4);this.#c=setTimeout(()=>this.#f(),n)},t.onerror=()=>{}}}class TZ{#t;#r;#n;#e=new Map;#s=!1;#l=0;#u;constructor(t,n={}){this.#t=t,this.#r=n.reconnect??!0,this.#u=setTimeout(()=>this.#c(),0)}on(t,n){let r=this.#e.get(t);return r||(r=new Set,this.#e.set(t,r)),r.add(n),()=>r.delete(n)}detach(){this.#s=!0,clearTimeout(this.#u),this.#n?.close(),this.#n=void 0}#i(t,n){const r=this.#e.get(t);if(r)for(const i of r)try{i(n)}catch{}}#c(){if(this.#s)return;const t=this.#t.openQueueSocket();this.#n=t,t.onopen=()=>{this.#l=0,this.#i("connectionChange",!0)},t.onmessage=n=>{const r=JSON.parse(String(n.data));r.type==="queue_attached"?(this.#i("attached",r.stats),this.#i("stats",r.stats)):r.type==="job_event"?this.#i("event",r.event):r.type==="queue_stats"&&this.#i("stats",r.stats)},t.onclose=()=>{if(this.#i("connectionChange",!1),this.#s||!this.#r)return;const n=Math.min(500*2**this.#l++,1e4);this.#u=setTimeout(()=>this.#c(),n)},t.onerror=()=>{}}}class vZ{#t;#r;#n;constructor(t){this.#t=t,this.#r=t.fetchImpl??fetch.bind(globalThis),this.#n=t.WebSocketImpl??WebSocket}async createSession(t){return(await this.#e("POST","/sessions",t)).session}async listSessions(){return(await this.#e("GET","/sessions")).sessions}async getSession(t){return(await this.#e("GET",`/sessions/${encodeURIComponent(t)}`)).session}async deleteSession(t){return(await this.#e("DELETE",`/sessions/${encodeURIComponent(t)}`)).session}async listSessionFiles(t){return(await this.#e("GET",`/sessions/${encodeURIComponent(t)}/files`)).files}async fetchSessionFile(t,n){const r=await this.#r(this.sessionFileUrl(t,n),{headers:this.#t.headers});if(!r.ok){const i=await r.json().catch(()=>({}));throw new Error(i.error??`GET file failed with ${r.status}`)}return await r.text()}sessionFileUrl(t,n){const r=n.split("/").filter(Boolean).map(encodeURIComponent).join("/");return`${this.#t.baseUrl}/sessions/${encodeURIComponent(t)}/files/${r}`}async resolvePermission(t,n,r){await this.#e("POST",`/sessions/${encodeURIComponent(t)}/permissions/${encodeURIComponent(n)}`,r)}async submitExecutionResult(t,n){return await this.#e("POST",`/executions/${encodeURIComponent(t)}/result`,n)}async listProfiles(){return await this.#e("GET","/profiles")}async getProfile(t){return await this.#e("GET",`/profiles/${encodeURIComponent(t)}`)}async createProfile(t){return(await this.#e("POST","/profiles",t)).profile}async updateProfile(t,n){return(await this.#e("PATCH",`/profiles/${encodeURIComponent(t)}`,n)).profile}async deleteProfile(t){await this.#e("DELETE",`/profiles/${encodeURIComponent(t)}`)}async listSdkSessions(t){const n=new URLSearchParams;t?.dir&&n.set("dir",t.dir),t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset));const r=n.size>0?`?${n.toString()}`:"";return(await this.#e("GET",`/sdk-sessions${r}`)).sdkSessions}async createJob(t){return(await this.#e("POST","/jobs",t)).job}async listJobs(){return(await this.#e("GET","/jobs")).jobs}async getJob(t){return(await this.#e("GET",`/jobs/${encodeURIComponent(t)}`)).job}async cancelJob(t){return(await this.#e("DELETE",`/jobs/${encodeURIComponent(t)}`)).job}async queueStats(){return(await this.#e("GET","/queue")).stats}attach(t,n){return new EZ(this,t,n)}attachQueue(t){return new TZ(this,t)}openSocket(t,n){const r=this.#t.buildWsUrl?.(t,n)??`${this.#t.baseUrl.replace(/^http/,"ws")}/sessions/${encodeURIComponent(t)}/ws?afterSeq=${n}`;return new this.#n(r)}openQueueSocket(){const t=this.#t.buildQueueWsUrl?.()??`${this.#t.baseUrl.replace(/^http/,"ws")}/queue/ws`;return new this.#n(t)}async#e(t,n,r){const i=await this.#r(`${this.#t.baseUrl}${n}`,{method:t,headers:{...r!==void 0?{"content-type":"application/json"}:{},...this.#t.headers},body:r!==void 0?JSON.stringify(r):void 0}),o=await i.json().catch(()=>({}));if(!i.ok)throw new Error(o.error??`${t} ${n} failed with ${i.status}`);return o}}const Kn=new vZ({baseUrl:`${location.origin}/v1`});function vR(e,t,n){const r=e?.engine==="provider",i=rj(e?.engine,t)?t:"default";if(!r)return{isProvider:r,modes:void 0,models:yR,mode:i,model:n};const o=e.provider,l=o?.models?.length?o.models:o?.model?[o.model]:[];return{isProvider:r,modes:ep,models:[{value:"default",displayName:"Profile default",description:o?.model??"the profile's configured model"},...l.map(c=>({value:c,displayName:c}))],mode:i,model:l.includes(n)?n:""}}function SZ(e=15e3){const[t,n]=S.useState([]),[r,i]=S.useState(),[o,l]=S.useState(!0),[c,f]=S.useState(!1),[d,m]=S.useState(),p=S.useRef(void 0),b=S.useCallback(async()=>{try{const[E,w]=await Promise.all([Kn.listJobs(),Kn.queueStats()]);n(E),i(w),l(!0),m(void 0)}catch(E){const w=E instanceof Error?E.message:String(E);/not configured/i.test(w)?(l(!1),m(void 0)):m(w)}},[]);S.useEffect(()=>(b(),p.current=setInterval(()=>void b(),e),()=>clearInterval(p.current)),[b,e]);const y=o&&r!==void 0;return S.useEffect(()=>{if(!y)return;const E=Kn.attachQueue(),w=[E.on("attached",()=>void b()),E.on("stats",i),E.on("connectionChange",f),E.on("event",k=>{n(C=>C.some(_=>_.id===k.job.id)?C.map(_=>_.id===k.job.id?k.job:_):[...C,k.job])})];return()=>{for(const k of w)k();E.detach()}},[y,b]),{jobs:t,stats:r,enabled:o,live:c,error:d,refresh:b}}const SR={profiles:[]};let jb,Pg;const Hb=new Set;async function nw(){const e=await Kn.listProfiles().catch(()=>SR);jb=e;for(const t of Hb)t(e);return e}function CR(){const[e,t]=S.useState(jb??SR);S.useEffect(()=>(Hb.add(t),jb||(Pg??=nw()),()=>{Hb.delete(t)}),[]);const n=S.useCallback(async()=>{Pg=nw(),await Pg},[]);return{...e,refresh:n}}function CZ(){return CR().profiles}const rw="workerdeck.last-profile";function wR(){const e=CZ(),[t,n]=S.useState(()=>localStorage.getItem(rw)??""),r=e.some(l=>l.name===t)?t:e[0]?.name??"",i=e.find(l=>l.name===r);return{profiles:e,profile:r,selected:i,select:l=>{n(l),localStorage.setItem(rw,l)}}}function kR(e=5e3){const[t,n]=S.useState([]),[r,i]=S.useState(),o=S.useRef(void 0),l=S.useCallback(async()=>{try{n(await Kn.listSessions()),i(void 0)}catch(c){i(c instanceof Error?c.message:String(c))}},[]);return S.useEffect(()=>(l(),o.current=setInterval(()=>void l(),e),()=>clearInterval(o.current)),[l,e]),{sessions:t,error:r,refresh:l}}const sw="workerdeck.last-cwd",wZ={queued:{label:"Queued",variant:"neutral"},running:{label:"Running",variant:"info",busy:!0},parked:{label:"Parked",variant:"accent"},succeeded:{label:"Succeeded",variant:"success"},failed:{label:"Failed",variant:"danger"},canceled:{label:"Canceled",variant:"warning"}};function kZ({stats:e}){const t=e.dailyTokenLimit!==void 0&&e.dailyTokenLimit>0?e.dailyTokensUsed/e.dailyTokenLimit*100:void 0;return g.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2 rounded-md border border-border bg-surface px-3 py-2 text-body-sm text-fg-2",children:[g.jsxs("span",{children:["Running ",g.jsxs("span",{className:"font-mono text-fg-1",children:[e.running,"/",e.maxConcurrency]})]}),g.jsxs("span",{children:["Queued ",g.jsx("span",{className:"font-mono text-fg-1",children:e.queued})]}),e.parked>0?g.jsxs("span",{children:["Parked ",g.jsx("span",{className:"font-mono text-fg-1",children:e.parked})]}):null,g.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t!==void 0?g.jsx(Z3,{value:t,className:t>=95?"text-danger":t>=80?"text-warning":"text-fg-3"}):null,"Daily tokens"," ",g.jsxs("span",{className:"font-mono text-fg-1",children:[Qi(e.dailyTokensUsed),e.dailyTokenLimit!==void 0?` / ${Qi(e.dailyTokenLimit)}`:""]})]}),e.sessionTokenLimit!==void 0?g.jsxs("span",{children:["Per-job cap ",g.jsx("span",{className:"font-mono text-fg-1",children:Qi(e.sessionTokenLimit)})]}):null,e.paused?g.jsx(ts,{variant:"warning",dot:!0,children:"Paused — daily budget exhausted"}):null]})}function AZ({onScheduled:e}){const[t,n]=S.useState(()=>localStorage.getItem(sw)??""),[r,i]=S.useState(""),[o,l]=S.useState(()=>bx("job")),[c,f]=S.useState("auto"),[d,m]=S.useState(()=>gx("job")),{profiles:p,profile:b,selected:y,select:E}=wR(),w=vR(y,o,d),[k,C]=S.useState(!1),[A,_]=S.useState(""),[N,M]=S.useState(""),[O,P]=S.useState(""),[D,Y]=S.useState(!1),U=async()=>{if(!t.trim()||!r.trim()){Mn.error("Working directory and prompt are required");return}const $=A.trim()?Number(A.trim()):void 0;if($!==void 0&&(!Number.isFinite($)||$<=0)){Mn.error("Max tokens must be a positive number");return}const Q=N.trim()?Number(N.trim()):void 0;if(Q!==void 0&&(!Number.isInteger(Q)||Q<1)){Mn.error("Attempts must be a whole number of at least 1");return}Y(!0);try{localStorage.setItem(sw,t.trim()),await Kn.createJob({session:{cwd:t.trim(),profile:b||void 0,prompt:r.trim(),permissionMode:w.mode,questionBehavior:c,model:w.model.trim()||void 0,...w.isProvider?{}:{settingSources:["user","project"],allowDangerouslySkipPermissions:k||void 0}},maxTokens:$,attempts:Q,webhook:O.trim()?{url:O.trim()}:void 0}),i(""),Mn.success("Job scheduled"),e()}catch(J){Mn.error(J instanceof Error?J.message:"Failed to schedule job")}finally{Y(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Schedule a job"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Working directory"}),g.jsx(bn,{value:t,onChange:$=>n($.target.value),placeholder:"/path/to/project",spellCheck:!1,className:"font-mono"})]}),g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Prompt (the task — runs unattended)"}),g.jsx(Xb,{value:r,onChange:$=>i($.target.value),rows:2,placeholder:"e.g. /verify-content 42, or a task description"})]}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(TR,{profiles:p,value:b,onChange:E,className:"min-w-32"}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Permission mode"}),g.jsx(Rc,{variant:"form",mode:w.mode,onModeChange:l,modes:w.modes,className:"min-w-44"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Questions"}),g.jsxs(Cc,{items:aS.map($=>({value:$.value,label:$.label})),value:c,onValueChange:$=>f($),children:[g.jsx(kc,{className:"min-w-36",children:g.jsx(wc,{})}),g.jsx(Ac,{children:aS.map($=>g.jsx(cl,{value:$.value,children:g.jsx(ul,{children:`${$.label} — ${$.description}`})},$.value))})]})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Model"}),g.jsx(xx,{value:w.model,onChange:m,models:w.models,className:"min-w-40"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Max tokens (optional)"}),g.jsx(bn,{value:A,onChange:$=>_($.target.value),placeholder:"per-job cap",inputMode:"numeric",className:"min-w-28 font-mono"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Attempts (optional)"}),g.jsx(bn,{value:N,onChange:$=>M($.target.value),placeholder:"1",inputMode:"numeric",className:"min-w-20 font-mono"})]}),g.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Webhook URL (optional)"}),g.jsx(bn,{value:O,onChange:$=>P($.target.value),placeholder:"https://…/hook",spellCheck:!1,className:"min-w-44 font-mono"})]}),g.jsxs($t,{onClick:()=>void U(),disabled:D,children:[D?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(k1,{className:"size-4"}),"Schedule"]})]}),w.isProvider?null:g.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 text-body-sm text-fg-2",title:"Spawns the CLI with --dangerously-skip-permissions available, so the mode can be switched on while watching the run. The job still starts in the mode selected above.",children:[g.jsx("input",{type:"checkbox",checked:k,onChange:$=>C($.target.checked),className:"size-3.5 accent-(--color-fg-1)"}),"Allow switching to ",g.jsx("code",{className:"font-mono",children:"bypassPermissions"})," mid-run",g.jsx("span",{className:"text-label text-fg-4",children:"(dangerous)"})]}),g.jsxs("p",{className:"text-label text-fg-4",children:["Unattended runs still surface permission prompts — watch the job's session to approve, or pick a mode that doesn't ask. Unanswered prompts deny after the server's timeout. With Questions set to Ask, webhook deliveries carry the full question so a controller can answer via"," ",g.jsx("code",{className:"font-mono",children:"POST /sessions/:id/permissions/:requestId"}),"."]})]})]})}function _Z({job:e,watchable:t,onChanged:n}){const r=ml(),i=wZ[e.status],o=e.status==="queued"||e.status==="running"||e.status==="parked",l=async()=>{try{await Kn.cancelJob(e.id),n()}catch(c){Mn.error(c instanceof Error?c.message:"Cancel failed")}};return g.jsxs("li",{className:"flex items-center gap-3 rounded-md px-2 py-2 hover:bg-surface-hover",children:[g.jsxs(ts,{variant:i.variant,dot:!i.busy,children:[i.busy?g.jsx(ci,{className:"size-3 text-current"}):null,i.label]}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-body-sm text-fg-1",children:e.prompt}),g.jsxs("div",{className:"flex flex-wrap gap-x-3 font-mono text-label text-fg-4",children:[g.jsx("span",{className:"truncate",children:e.cwd}),e.profile?g.jsxs("span",{className:"shrink-0",children:["@",e.profile]}):null,g.jsx("span",{className:"shrink-0",children:R1(e.finishedAt??e.startedAt??e.createdAt)}),e.maxAttempts!==void 0&&e.maxAttempts>1?g.jsxs("span",{className:"shrink-0",children:["attempt ",e.attempt??1,"/",e.maxAttempts,e.status==="queued"&&e.nextRunAt!==void 0&&e.nextRunAt>Date.now()?" — retry pending":""]}):null,e.usage.tokens>0?g.jsxs("span",{className:"shrink-0",children:[Qi(e.usage.tokens)," tok"]}):null,e.usage.totalCostUsd>0?g.jsx("span",{className:"shrink-0",children:tp(e.usage.totalCostUsd)}):null,e.error?g.jsx("span",{className:"truncate text-danger",children:e.error}):null]})]}),e.sessionId&&t?g.jsxs($t,{variant:"ghost",size:"xs",onClick:()=>void r({to:"/sessions/$sessionId",params:{sessionId:e.sessionId}}),children:[g.jsx(U3,{className:"size-3"}),"Watch"]}):null,o?g.jsxs($t,{variant:"outline",size:"xs",onClick:()=>void l(),children:[g.jsx(V3,{className:"size-3"}),"Cancel"]}):null]})}function NZ(){const{jobs:e,stats:t,enabled:n,live:r,error:i,refresh:o}=SZ(),{sessions:l}=kR(),c=new Set(l.map(d=>d.id)),f=[...e].sort((d,m)=>m.createdAt-d.createdAt);return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{className:"flex items-end justify-between",children:[g.jsxs("div",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Jobs"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"Scheduled one-shot runs with concurrency and token budgets."})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[n?g.jsx(ts,{variant:r?"success":"neutral",dot:!0,children:r?"Live":"Polling"}):null,g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Refresh",onClick:()=>void o(),children:g.jsx(F3,{className:"size-4"})})]})]}),i?g.jsxs("div",{className:"rounded-md bg-danger-bg px-3 py-2 text-body-sm text-danger",children:["Can't reach the worker server: ",i,". Start it with"," ",g.jsx("code",{className:"font-mono",children:"pnpm server"}),"."]}):null,n?g.jsxs(g.Fragment,{children:[t?g.jsx(kZ,{stats:t}):null,f.length===0?g.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-border bg-surface px-4 py-8 text-center",children:[g.jsx(z3,{className:"size-6 text-fg-4"}),g.jsx("p",{className:"text-body-sm text-fg-2",children:"No jobs yet. Schedule one below."})]}):g.jsx("ul",{className:"flex flex-col gap-1 rounded-md border border-border bg-surface p-1",children:f.map(d=>g.jsx(_Z,{job:d,watchable:d.sessionId!==void 0&&c.has(d.sessionId),onChanged:()=>void o()},d.id))}),g.jsx(AZ,{onScheduled:()=>void o()})]}):g.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-border bg-surface px-4 py-8 text-center",children:[g.jsx(CP,{className:"size-6 text-fg-4"}),g.jsx("p",{className:"text-body-sm text-fg-2",children:"The server has no job queue configured."}),g.jsxs("p",{className:"text-label text-fg-4",children:["Pass ",g.jsxs("code",{className:"font-mono",children:["queue: ","{ maxConcurrency, … }"]})," to"," ",g.jsx("code",{className:"font-mono",children:"createWorkerServer"})," — the dev server enables it by default."]})]})]})})}const RZ=["web_search","download","web_fetch","deliver_file"],Od=e=>e.split(",").map(t=>t.trim()).filter(Boolean);function zi({label:e,children:t}){return g.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:e}),t]})}function OZ({profile:e,onSaved:t}){const n=e.engine==="provider",[r,i]=S.useState(e.description??""),[o,l]=S.useState(e.defaults?.model??""),[c,f]=S.useState(e.defaults?.permissionMode),[d,m]=S.useState(e.provider?.model??""),[p,b]=S.useState((e.provider?.models??[]).join(", ")),[y,E]=S.useState(e.session?.capabilities),[w,k]=S.useState((e.session?.mcpServers??[]).join(", ")),[C,A]=S.useState(e.session?.instructions??""),[_,N]=S.useState(!1),M=async()=>{const O={description:r.trim()||void 0,defaults:{model:o.trim()||void 0,permissionMode:c}};n&&(O.provider={...e.provider,id:e.provider?.id??"",model:d.trim()||void 0,models:Od(p).length>0?Od(p):void 0},O.session={capabilities:y,mcpServers:Od(w).length>0?Od(w):void 0,instructions:C.trim()||void 0}),N(!0);try{t(await Kn.updateProfile(e.name,O)),Mn.success("Profile saved")}catch(P){Mn.error(P instanceof Error?P.message:"Failed to save profile")}finally{N(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Edit profile"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsx(zi,{label:"Description",children:g.jsx(bn,{value:r,onChange:O=>i(O.target.value)})}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(zi,{label:"Default model",children:g.jsx(bn,{value:o,onChange:O=>l(O.target.value),placeholder:"unset — request / engine default",className:"font-mono"})}),g.jsx(zi,{label:"Default permission mode",children:g.jsx(Rc,{variant:"form",mode:c,onModeChange:f,modes:n?ep:void 0})})]}),n?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(zi,{label:"Default model id",children:g.jsx(bn,{value:d,onChange:O=>m(O.target.value),className:"font-mono"})}),g.jsx(zi,{label:"Models offered (comma-separated)",children:g.jsx(bn,{value:p,onChange:O=>b(O.target.value),className:"font-mono"})})]}),g.jsx(zi,{label:"Capabilities granted",children:g.jsxs("div",{className:"flex flex-wrap items-center gap-3 py-1.5",children:[g.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-body-sm text-fg-2",children:[g.jsx("input",{type:"checkbox",checked:y===void 0,onChange:O=>E(O.target.checked?void 0:[]),className:"size-3.5 accent-(--color-fg-1)"}),"not declared"]}),RZ.map(O=>g.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-body-sm text-fg-2",children:[g.jsx("input",{type:"checkbox",disabled:y===void 0,checked:y?.includes(O)??!1,onChange:P=>E(D=>P.target.checked?[...D??[],O]:(D??[]).filter(Y=>Y!==O)),className:"size-3.5 accent-(--color-fg-1) disabled:opacity-40"}),g.jsx("code",{className:"font-mono text-label",children:O})]},O))]})}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(zi,{label:"MCP servers (names, comma-separated)",children:g.jsx(bn,{value:w,onChange:O=>k(O.target.value),className:"font-mono"})}),g.jsx(zi,{label:"Instructions",children:g.jsx(bn,{value:C,onChange:O=>A(O.target.value)})})]})]}):null,g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("p",{className:"text-label text-fg-4",children:"Name and engine are fixed — sessions and jobs are pinned to the name, and the engine decides what the rest of these fields mean."}),g.jsxs($t,{onClick:()=>void M(),disabled:_,children:[_?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(r9,{className:"size-4"}),"Save"]})]})]})]})}const IZ=["web_search","download","web_fetch","deliver_file"],Id=e=>e.split(",").map(t=>t.trim()).filter(Boolean);function as({label:e,children:t}){return g.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:e}),t]})}function LZ({onCreated:e}){const[t,n]=S.useState("provider"),[r,i]=S.useState(""),[o,l]=S.useState(""),[c,f]=S.useState(""),[d,m]=S.useState(""),[p,b]=S.useState(""),[y,E]=S.useState(""),[w,k]=S.useState(""),[C,A]=S.useState([]),[_,N]=S.useState(""),[M,O]=S.useState(""),[P,D]=S.useState(!1),Y=t==="provider",U=async()=>{if(!r.trim()){Mn.error("Name is required");return}const $={name:r.trim(),engine:t};if(o.trim()&&($.description=o.trim()),Y){$.provider={id:c.trim(),model:d.trim()||void 0,models:Id(p).length>0?Id(p):void 0,apiKeyEnv:y.trim()||void 0};const Q={};C.length>0&&(Q.capabilities=C),Id(_).length>0&&(Q.mcpServers=Id(_)),M.trim()&&(Q.instructions=M.trim()),Object.keys(Q).length>0&&($.session=Q)}else $.configDir=w.trim();D(!0);try{await Kn.createProfile($),await e(),i(""),l(""),O(""),Mn.success(`Profile '${$.name}' created`)}catch(Q){Mn.error(Q instanceof Error?Q.message:"Failed to create profile")}finally{D(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"New profile"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(as,{label:"Engine",children:g.jsxs(Cc,{items:[{value:"provider",label:"provider"},{value:"claude",label:"claude"}],value:t,onValueChange:$=>n($),children:[g.jsx(kc,{className:"min-w-32",children:g.jsx(wc,{})}),g.jsxs(Ac,{children:[g.jsx(cl,{value:"provider",children:g.jsx(ul,{children:"provider — model-agnostic engine"})}),g.jsx(cl,{value:"claude",children:g.jsx(ul,{children:"claude — Agent SDK + config dir"})})]})]})}),g.jsx(as,{label:"Name",children:g.jsx(bn,{value:r,onChange:$=>i($.target.value),placeholder:"kimi"})}),g.jsx(as,{label:"Description (optional)",children:g.jsx(bn,{value:o,onChange:$=>l($.target.value),placeholder:"what this profile is for"})})]}),Y?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(as,{label:"Provider id",children:g.jsx(bn,{value:c,onChange:$=>f($.target.value),placeholder:"anthropic / openai / moonshotai",className:"font-mono"})}),g.jsx(as,{label:"Default model",children:g.jsx(bn,{value:d,onChange:$=>m($.target.value),placeholder:"kimi-k3",className:"font-mono"})}),g.jsx(as,{label:"Models offered (comma-separated)",children:g.jsx(bn,{value:p,onChange:$=>b($.target.value),placeholder:"kimi-k3, kimi-k2",className:"font-mono"})}),g.jsx(as,{label:"API key variable",children:g.jsx(bn,{value:y,onChange:$=>E($.target.value),placeholder:"MOONSHOT_API_KEY",className:"font-mono"})})]}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(as,{label:"Capabilities granted",children:g.jsx("div",{className:"flex flex-wrap gap-3 py-1.5",children:IZ.map($=>g.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-body-sm text-fg-2",children:[g.jsx("input",{type:"checkbox",checked:C.includes($),onChange:Q=>A(J=>Q.target.checked?[...J,$]:J.filter(te=>te!==$)),className:"size-3.5 accent-(--color-fg-1)"}),g.jsx("code",{className:"font-mono text-label",children:$})]},$))})}),g.jsx(as,{label:"MCP servers (names, comma-separated)",children:g.jsx(bn,{value:_,onChange:$=>N($.target.value),placeholder:"deepwiki",className:"font-mono"})})]}),g.jsx(as,{label:"Instructions (optional)",children:g.jsx(bn,{value:M,onChange:$=>O($.target.value),placeholder:"prepended to the session's system prompt"})}),g.jsx("p",{className:"text-label text-fg-4",children:"Leave capabilities and MCP servers empty to inherit whatever the server's engine factory wired — that factory is the ceiling either way, so a grant here can never exceed it. MCP servers are named, never configured: their transport config (and any credentials in it) stays on the server."})]}):g.jsxs(g.Fragment,{children:[g.jsx(as,{label:"Config directory",children:g.jsx(bn,{value:w,onChange:$=>k($.target.value),placeholder:"/Users/you/.claude",spellCheck:!1,className:"font-mono"})}),g.jsxs("p",{className:"text-label text-fg-4",children:["Must resolve inside the server's"," ",g.jsx("code",{className:"font-mono",children:"allowedConfigDirRoots"})," — a config directory is a credential store, so the server bounds which ones a managed profile may point at."]})]}),g.jsx("div",{className:"flex justify-end",children:g.jsxs($t,{onClick:()=>void U(),disabled:P,children:[P?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(k1,{className:"size-4"}),"Create profile"]})})]})]})}function AR(e){window.location.href=`vscode://file${e}`}function MZ(){const{profiles:e,canManage:t,refresh:n}=CR(),r=ml(),i=o=>{Kn.deleteProfile(o).then(()=>n()).then(()=>Mn.success(`Profile '${o}' deleted`)).catch(l=>Mn.error(l instanceof Error?l.message:"Delete failed"))};return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Profiles"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"What a session runs as: a named Claude Code config directory — its own settings, memory, skills, and credentials — or a model provider for the model-agnostic engine."})]}),e.length===0?g.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-border bg-surface px-4 py-8 text-center",children:[g.jsx(UP,{className:"size-6 text-fg-4"}),g.jsx("p",{className:"text-body-sm text-fg-2",children:"The server declares no profiles."}),g.jsxs("p",{className:"text-label text-fg-4",children:["Pass ",g.jsxs("code",{className:"font-mono",children:["profiles: [","{ name, configDir, … }","]"]})," to"," ",g.jsx("code",{className:"font-mono",children:"createWorkerServer"})," — without the option, a"," ",g.jsx("code",{className:"font-mono",children:"default"})," profile is auto-created from"," ",g.jsx("code",{className:"font-mono",children:"~/.claude"})," when it exists."]})]}):g.jsx("ul",{className:"divide-y divide-border rounded-md border border-border bg-surface",children:e.map(o=>g.jsxs("li",{className:"flex items-center gap-3 px-3 py-2.5",children:[g.jsx(g9,{className:"size-4 shrink-0 text-fg-3"}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"truncate text-body-sm font-medium text-fg-1",children:o.name}),o.description?g.jsx("span",{className:"truncate text-body-sm text-fg-3",children:o.description}):null]}),g.jsx("div",{className:"mt-0.5 truncate font-mono text-label text-fg-4",children:o.configDir??(o.provider?`${o.provider.id}${o.provider.model?` · ${o.provider.model}`:""}`:"")})]}),g.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[g.jsx(ts,{variant:"neutral",children:o.engine??"claude"}),o.defaults?.model?g.jsx(ts,{variant:"neutral",children:o.defaults.model}):null,o.defaults?.permissionMode?g.jsx(ts,{variant:"neutral",children:o.defaults.permissionMode}):null,o.configDir?g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":`Open ${o.name} in VSCode`,title:"Open config dir in VSCode",onClick:()=>AR(o.configDir),children:g.jsx(H3,{className:"size-4"})}):null,g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":`View ${o.name}`,title:"View profile",onClick:()=>void r({to:"/profiles/$profileName",params:{profileName:o.name}}),children:g.jsx(U3,{className:"size-4"})}),o.managed?g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":`Delete ${o.name}`,title:"Delete profile",onClick:()=>i(o.name),children:g.jsx(A1,{className:"size-4"})}):null]})]},o.name))}),t?g.jsx(LZ,{onCreated:n}):null,g.jsxs("p",{className:"text-label text-fg-4",children:["Session and job creates run under the selected profile; when the server declares more than one, picking a profile is required."," ",t?"Profiles created here are stored by the server; the ones declared in its options are code and stay read-only.":"Profiles are declared in server configuration and read-only here."]})]})})}function _n({label:e,children:t}){return g.jsxs("div",{className:"flex items-baseline justify-between gap-4 py-1.5",children:[g.jsx("span",{className:"shrink-0 text-label font-medium text-fg-3",children:e}),g.jsx("span",{className:"min-w-0 text-right text-body-sm text-fg-1",children:t})]})}function Fi({items:e,empty:t}){return e.length===0?g.jsx("span",{className:"text-fg-4",children:t}):g.jsx("span",{className:"flex flex-wrap justify-end gap-1",children:e.map(n=>g.jsx(ts,{variant:"neutral",children:n},n))})}function DZ(){const{profileName:e}=Oh({from:"/profiles/$profileName"}),[t,n]=S.useState(),[r,i]=S.useState();S.useEffect(()=>{let c=!0;return Kn.getProfile(e).then(f=>{c&&n(f)}).catch(f=>{c&&i(f instanceof Error?f.message:"Failed to load profile")}),()=>{c=!1}},[e]);const o=t?.profile,l=t?.config;return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{className:"flex items-end justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs(yc,{to:"/profiles",className:"mb-1 inline-flex items-center gap-1 text-label text-fg-3 hover:text-fg-1",children:[g.jsx(P3,{className:"size-3"}),"Profiles"]}),g.jsx("h1",{className:"truncate text-display-sm font-semibold tracking-tight text-text",children:e}),o?.description?g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:o.description}):null]}),o?.configDir?g.jsxs($t,{variant:"outline",size:"xs",onClick:()=>AR(o.configDir),children:[g.jsx(H3,{className:"size-3"}),"Open in VSCode"]}):null]}),r?g.jsx("div",{className:"rounded-md bg-danger-bg px-3 py-2 text-body-sm text-danger",children:r}):null,!t&&!r?g.jsx(ci,{className:"mx-auto size-5 text-fg-4"}):null,o&&l?g.jsxs(g.Fragment,{children:[g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Worker defaults"})}),g.jsxs(Rs,{className:"flex flex-col divide-y divide-border",children:[g.jsx(_n,{label:"Engine",children:g.jsx(ts,{variant:"neutral",children:o.engine??"claude"})}),o.engine==="provider"?g.jsx(_n,{label:"Provider",children:g.jsx("span",{className:"font-mono text-label",children:o.provider?.id})}):g.jsx(_n,{label:"Config directory",children:g.jsx("span",{className:"font-mono text-label",children:o.configDir})}),g.jsx(_n,{label:"Default model",children:o.defaults?.model??o.provider?.model??g.jsx("span",{className:"text-fg-4",children:"request / engine default"})}),g.jsx(_n,{label:"Default permission mode",children:o.defaults?.permissionMode??g.jsx("span",{className:"text-fg-4",children:"request / engine default"})}),o.engine==="provider"?g.jsxs(g.Fragment,{children:[g.jsx(_n,{label:"Models offered",children:g.jsx(Fi,{items:o.provider?.models??[],empty:"the default model only"})}),g.jsx(_n,{label:"API key variable",children:o.provider?.apiKeyEnv?g.jsx("span",{className:"font-mono text-label",children:o.provider.apiKeyEnv}):g.jsx("span",{className:"text-fg-4",children:"provider SDK default"})})]}):null]})]}),o.engine==="provider"?g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Session grants"})}),g.jsxs(Rs,{className:"flex flex-col divide-y divide-border",children:[g.jsx(_n,{label:"Capabilities",children:g.jsx(Fi,{items:o.session?.capabilities??[],empty:"not declared — whatever the server wired"})}),g.jsx(_n,{label:"MCP servers",children:g.jsx(Fi,{items:o.session?.mcpServers??[],empty:"not declared — every connected server"})}),g.jsx(_n,{label:"Instructions",children:o.session?.instructions?`${o.session.instructions.length} characters`:g.jsx("span",{className:"text-fg-4",children:"none"})})]})]}):null,o.engine==="provider"?null:g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Claude Code configuration"})}),g.jsxs(Rs,{className:"flex flex-col divide-y divide-border",children:[l.settings?g.jsxs(g.Fragment,{children:[g.jsx(_n,{label:"Model (settings.json)",children:l.settings.model??g.jsx("span",{className:"text-fg-4",children:"not set"})}),g.jsx(_n,{label:"Default permission mode",children:l.settings.defaultPermissionMode??g.jsx("span",{className:"text-fg-4",children:"not set"})}),g.jsx(_n,{label:"Permission rules",children:g.jsx("span",{className:"font-mono text-label",children:l.settings.permissionRules?`${l.settings.permissionRules.allow} allow · ${l.settings.permissionRules.ask} ask · ${l.settings.permissionRules.deny} deny`:"—"})}),g.jsx(_n,{label:"Env vars (names only)",children:g.jsx(Fi,{items:l.settings.envKeys??[],empty:"none"})}),g.jsx(_n,{label:"Hooks",children:g.jsx(Fi,{items:l.settings.hooks??[],empty:"none"})})]}):g.jsx(_n,{label:"settings.json",children:g.jsx("span",{className:"text-fg-4",children:"not found"})}),g.jsx(_n,{label:"User memory (CLAUDE.md)",children:l.hasUserMemory?"present":g.jsx("span",{className:"text-fg-4",children:"none"})}),g.jsx(_n,{label:"Skills",children:g.jsx(Fi,{items:l.skills,empty:"none"})}),g.jsx(_n,{label:"Agents",children:g.jsx(Fi,{items:l.agents,empty:"none"})}),g.jsx(_n,{label:"Commands",children:g.jsx(Fi,{items:l.commands,empty:"none"})})]})]}),o.managed?g.jsx(OZ,{profile:o,onSaved:c=>n({...t,profile:c})}):null,g.jsxs("p",{className:"text-label text-fg-4",children:[o.managed?"Stored on the server and editable here. ":"View only — this profile is declared in the server options. ","Other profile configuration lives on the server (the"," ",g.jsx("code",{className:"font-mono",children:"profiles"})," option; for Claude profiles, the config directory itself, e.g. via VSCode). Provider credentials are resolved from the server's environment and never leave it."]})]}):null]})})}function PZ(){const{sessionId:e}=Oh({from:"/sessions/$sessionId"}),t=ml(),[n,r]=S.useState();S.useEffect(()=>{let o=!1;return Kn.getSession(e).then(l=>{o||r(l)}).catch(()=>{Mn.error("Session not found"),t({to:"/sessions"})}),()=>{o=!0}},[e,t]);const i=async()=>{try{await Kn.deleteSession(e)}catch{}t({to:"/sessions"})};return g.jsx(fZ,{client:Kn,sessionId:e,header:g.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[g.jsx(yc,{to:"/sessions","aria-label":"Back to sessions",children:g.jsx($t,{variant:"ghost",size:"icon-sm",children:g.jsx(P3,{className:"size-4"})})}),g.jsx("span",{className:"truncate text-body-sm font-medium text-fg-1",children:n?.title??e.slice(0,8)}),n?.cwd?g.jsx("span",{className:"truncate font-mono text-label text-fg-4",children:n.cwd}):null,g.jsx("span",{className:"flex-1"}),g.jsx(W3,{value:e,"aria-label":"Copy session id"}),g.jsxs($9,{children:[g.jsx(q9,{render:g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Close session",children:g.jsx(A1,{className:"size-4 text-fg-3"})})}),g.jsxs(G9,{children:[g.jsx(X9,{children:"Close this session?"}),g.jsx(K9,{children:"The Claude Code subprocess is terminated. You can resume it later from “Resume a previous session” (the transcript is kept on disk by the SDK)."}),g.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[g.jsx(Y9,{render:g.jsx($t,{variant:"outline",children:"Cancel"})}),g.jsx($t,{variant:"destructive",onClick:()=>void i(),children:"Close session"})]})]})]})]})},e)}const iw="workerdeck.last-cwd";function BZ({onCreated:e}){const[t,n]=S.useState(()=>localStorage.getItem(iw)??""),[r,i]=S.useState(""),[o,l]=S.useState(()=>bx("session")),[c,f]=S.useState(()=>gx("session")),{profiles:d,profile:m,selected:p,select:b}=wR(),y=vR(p,o,c),[E,w]=S.useState(!1),[k,C]=S.useState(),[A,_]=S.useState(!1),N=async O=>{const P=O?.cwd??t.trim();if(!P){Mn.error("Working directory is required");return}w(!0);try{localStorage.setItem(iw,t.trim()||P);const D=await Kn.createSession({cwd:P,profile:m||void 0,prompt:O?void 0:r.trim()||void 0,permissionMode:y.mode,model:y.model.trim()||void 0,resume:O?.sessionId,...y.isProvider?{}:{settingSources:["user","project"],allowDangerouslySkipPermissions:!0}});e(D.id)}catch(D){Mn.error(D instanceof Error?D.message:"Failed to create session")}finally{w(!1)}},M=async()=>{if(!t.trim()){Mn.error("Set a working directory first — resumable sessions are listed per project");return}_(!0);try{C(await Kn.listSdkSessions({dir:t.trim(),limit:20}))}catch(O){Mn.error(O instanceof Error?O.message:"Failed to list resumable sessions")}finally{_(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"New session"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Working directory"}),g.jsx(bn,{value:t,onChange:O=>n(O.target.value),placeholder:"/path/to/project",spellCheck:!1,className:"font-mono"})]}),g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Initial prompt (optional)"}),g.jsx(Xb,{value:r,onChange:O=>i(O.target.value),rows:2,placeholder:"e.g. /verify-content 42, or a task description"})]}),g.jsxs("div",{className:"flex items-end justify-between gap-3",children:[g.jsx(TR,{profiles:d,value:m,onChange:b,className:"min-w-32"}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Permission mode"}),g.jsx(Rc,{variant:"form",mode:y.mode,onModeChange:l,modes:y.modes,className:"min-w-44"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Model"}),g.jsx(xx,{value:y.model,onChange:f,models:y.models,className:"min-w-44"})]}),g.jsxs($t,{onClick:()=>void N(),disabled:E,children:[E?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(k1,{className:"size-4"}),"Create"]})]}),y.isProvider?null:g.jsxs("div",{className:"mt-1 border-t border-border pt-3",children:[g.jsxs("div",{className:"flex items-center justify-between",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Resume a previous session"}),g.jsxs($t,{variant:"ghost",size:"xs",onClick:()=>void M(),disabled:A,children:[A?g.jsx(ci,{className:"size-3 text-current"}):g.jsx(FP,{className:"size-3"}),k?"Reload":"Browse"]})]}),k!==void 0?k.length===0?g.jsx("div",{className:"py-3 text-center text-body-sm text-fg-4",children:"No stored sessions for this directory."}):g.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:k.map(O=>g.jsxs("li",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-surface-hover",children:[g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-body-sm text-fg-1",children:O.customTitle??O.summary}),g.jsxs("div",{className:"flex gap-2 font-mono text-label text-fg-4",children:[O.gitBranch?g.jsx("span",{className:"truncate",children:O.gitBranch}):null,g.jsx("span",{className:"shrink-0",children:R1(O.lastModified)})]})]}),g.jsx($t,{variant:"outline",size:"xs",onClick:()=>void N(O),disabled:E,children:"Resume"})]},O.sessionId))}):null]})]})]})}function jZ(){const e=ml(),{sessions:t,error:n,refresh:r}=kR(),i=o=>void e({to:"/sessions/$sessionId",params:{sessionId:o}});return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{className:"flex items-end justify-between",children:[g.jsxs("div",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Sessions"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"Live Agent SDK sessions on this worker."})]}),g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Refresh",onClick:()=>void r(),children:g.jsx(F3,{className:"size-4"})})]}),n?g.jsxs("div",{className:"rounded-md bg-danger-bg px-3 py-2 text-body-sm text-danger",children:["Can’t reach the worker server: ",n,". Start it with ",g.jsx("code",{className:"font-mono",children:"pnpm server"}),"."]}):null,g.jsx(hZ,{sessions:[...t].sort((o,l)=>(l.lastActivityAt??l.createdAt)-(o.lastActivityAt??o.createdAt)),onSelect:i,onDelete:o=>{Kn.deleteSession(o).then(()=>r()).catch(l=>Mn.error(l instanceof Error?l.message:"Delete failed"))},emptyText:"No live sessions. Create one below."}),g.jsx(BZ,{onCreated:i})]})})}function aw({kind:e,label:t}){const[n,r]=S.useState(()=>gx(e)),[i,o]=S.useState(()=>bx(e));return g.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-2",children:[g.jsx("span",{className:"text-body-sm text-fg-2",children:t}),g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx(Rc,{variant:"form",mode:i,onModeChange:l=>{o(l),yZ(e,l)},className:"min-w-40"}),g.jsx(xx,{value:n,onChange:l=>{r(l),bZ(e,l)},className:"min-w-44"})]})]})}function HZ(){return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4 px-6 py-6",children:[g.jsxs("header",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Settings"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"Client-side preferences. Server policy (auth, cwd roots, API-key requirements) is configured where the worker runs."})]}),g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Appearance"})}),g.jsxs(Rs,{className:"flex items-center justify-between",children:[g.jsx("span",{className:"text-body-sm text-fg-2",children:"Theme"}),g.jsx(xR,{})]})]}),g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Defaults"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsx(aw,{kind:"session",label:"New session"}),g.jsx(aw,{kind:"job",label:"Queue job"}),g.jsx("p",{className:"text-label text-fg-4",children:'Pre-fills the permission mode and model on the new-session and schedule-job forms (still editable per run). "Default (recommended)" leaves the model to the CLI.'})]})]}),g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Worker server"})}),g.jsxs(Rs,{className:"flex flex-col gap-1 text-body-sm text-fg-2",children:[g.jsxs("div",{children:["Endpoint: ",g.jsxs("code",{className:"font-mono text-code",children:[location.origin,"/v1"]})," (dev proxy → ",g.jsx("code",{className:"font-mono text-code",children:"WORKER_URL"}),", default"," ",g.jsx("code",{className:"font-mono text-code",children:"http://127.0.0.1:8787"}),")"]}),g.jsx("div",{className:"text-label text-fg-4",children:"Anthropic credentials are resolved by the SDK from the server operator’s environment — this app never handles them."})]})]})]})})}const fa=wI({component:gZ}),UZ=no({getParentRoute:()=>fa,path:"/",beforeLoad:()=>{throw Ew({to:"/sessions"})}}),zZ=no({getParentRoute:()=>fa,path:"/sessions",component:jZ}),FZ=no({getParentRoute:()=>fa,path:"/sessions/$sessionId",component:PZ}),VZ=no({getParentRoute:()=>fa,path:"/jobs",component:NZ}),$Z=no({getParentRoute:()=>fa,path:"/profiles",component:MZ}),qZ=no({getParentRoute:()=>fa,path:"/profiles/$profileName",component:DZ}),YZ=no({getParentRoute:()=>fa,path:"/settings",component:HZ}),GZ=jI({routeTree:fa.addChildren([UZ,zZ,FZ,VZ,$Z,qZ,YZ]),history:V4()});function XZ(){return g.jsxs(g.Fragment,{children:[g.jsx(zI,{router:GZ}),g.jsx(z7,{})]})}uw();const _R=document.getElementById("root");if(!_R)throw new Error("Root element #root not found");KO.createRoot(_R).render(g.jsx(S.StrictMode,{children:g.jsx(XZ,{})}));const KZ=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:gR},Symbol.toStringTag,{value:"Module"}));export{HQ as A,ZZ as L,Hr as R,hc as _,g as j,S as r};
481
+ `),label:"Logs"}):null,e.result!==void 0?g.jsxs("div",{children:[g.jsx(ag,{code:p||"(empty result)",label:f?"Error":"Result",className:He(f&&"border-danger/40 [&_pre]:text-danger")}),m?g.jsxs("button",{type:"button",className:"mt-1 text-label text-fg-3 underline-offset-2 hover:underline",onClick:()=>o(!0),children:["Show all ",d.length.toLocaleString()," chars"]}):null]}):null]}):null]})}function aZ({item:e}){return g.jsxs("div",{"data-slot":"turn-result",className:"flex items-center gap-2 py-1",children:[g.jsx("div",{className:"h-px flex-1 bg-border"}),g.jsxs("span",{className:He("font-mono text-label",e.isError?"text-danger":"text-fg-4"),children:[e.isError?e.subtype:"turn done"," · ",vj(e.durationMs)," ·"," ",tp(e.totalCostUsd)]}),g.jsx("div",{className:"h-px flex-1 bg-border"})]})}function oZ({item:e}){return g.jsx("div",{"data-slot":"notice",className:He("rounded-md border px-3 py-2 text-body-sm",e.level==="error"?"border-transparent bg-danger-bg text-danger":"border-border bg-surface text-fg-3"),children:e.text})}function lZ({item:e,fileUrl:t}){switch(e.kind){case"user":return g.jsx(fS,{from:"user",children:g.jsx(dS,{children:e.text})});case"assistant_text":return g.jsx(fS,{from:"assistant",children:g.jsx(dS,{children:g.jsx(bR,{streaming:e.streaming,children:e.text})})});case"thinking":return g.jsx(rZ,{isStreaming:e.id==="streaming-thinking",children:e.text});case"tool_call":return g.jsx(iZ,{item:e});case"turn_result":return g.jsx(aZ,{item:e});case"notice":return g.jsx(oZ,{item:e});case"file_delivered":return g.jsx(jj,{item:e,href:t?.(e.path)});default:return null}}function uZ(e){if(e.status!=="running"&&e.status!=="starting")return!1;const t=e.items.at(-1);return t?t.kind==="assistant_text"&&t.streaming||t.kind==="thinking"&&t.id==="streaming-thinking"?!1:t.kind!=="turn_result"||e.status==="running":!0}function cZ({state:e,fileUrl:t,className:n}){return g.jsxs(Dj,{className:n,children:[g.jsxs(Pj,{children:[e.items.length===0&&e.status!=="starting"?g.jsx("div",{className:"py-12 text-center text-body-sm text-fg-4",children:"No messages yet."}):e.items.map(r=>g.jsx(lZ,{item:r,fileUrl:t},`${r.kind}:${r.id}`)),uZ(e)?g.jsx(Hj,{label:e.status==="starting"?"Starting session…":void 0}):null]}),g.jsx(Bj,{})]})}function fZ({client:e,sessionId:t,header:n,className:r}){const[i,o]=S.useState(void 0),{state:l,connected:c,handle:f,send:d,approve:m,deny:p,interrupt:b,setModel:y,setPermissionMode:E}=fj(e,t,{onProtocolError:o});S.useEffect(()=>o(void 0),[t]),gj(f);const w=l.status==="running"||l.status==="awaiting_approval",k=l.status==="failed"||l.status==="closed",C=S.useMemo(()=>{if(l.commands)return l.commands.some(_=>_.name==="model")?l.commands:[{name:"model",description:"Switch the model for this session",argumentHint:"<model>"},...l.commands]},[l.commands]),A=_=>{const N=/^\/model\s+(\S+)$/.exec(_);if(N){y(N[1]);return}d(_)};return g.jsxs("div",{"data-slot":"session-panel",className:He("flex h-full min-h-0 flex-col overflow-hidden bg-bg",r),children:[n,g.jsx(_j,{state:l,connected:c}),i?g.jsx("div",{className:"px-3 pt-2",children:g.jsxs("div",{role:"alert",className:"mx-auto flex w-full max-w-3xl items-start gap-2 rounded-md border border-danger/40 bg-danger-bg px-3 py-2 text-body-sm text-danger",children:[g.jsx("span",{className:"min-w-0 flex-1 break-words",children:i}),g.jsx("button",{type:"button",onClick:()=>o(void 0),"aria-label":"Dismiss error",className:"shrink-0 opacity-70 transition-opacity hover:opacity-100",children:"✕"})]})}):null,g.jsx(cZ,{state:l,fileUrl:t?_=>e.sessionFileUrl(t,_):void 0}),l.pendingApprovals.length>0?g.jsx("div",{className:"px-3 pb-2",children:g.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-2",children:l.pendingApprovals.map(_=>_.toolName==="AskUserQuestion"&&pA(_.input).length>0?g.jsx(Tj,{request:_,onAnswer:m,onDismiss:p},_.id):g.jsx(Ej,{request:_,onApprove:m,onDeny:p},_.id))})}):null,g.jsx(xj,{onSend:A,onInterrupt:b,busy:w,disabled:k||!t,commands:C,toolbar:g.jsxs(g.Fragment,{children:[l.models?.length?g.jsx(hA,{models:l.models,model:l.model,onModelChange:y,disabled:k}):null,l.permissionMode?g.jsx(Rc,{mode:l.permissionMode,onModeChange:E,modes:l.engine==="provider"?ep:void 0,disabled:k}):null]})})]})}function dZ({session:e,active:t,onSelect:n,onDelete:r}){const i=mA[e.status];return g.jsxs("div",{"data-slot":"session-list-item","data-active":t||void 0,className:He("group flex w-full items-center gap-2 rounded-md border border-transparent px-2.5 py-2 text-left transition-colors",t?"border-border bg-surface":"hover:bg-surface-hover"),children:[g.jsxs("button",{type:"button",onClick:()=>n?.(e.id),className:"min-w-0 flex-1 text-left outline-none",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"truncate text-body-sm font-medium text-fg-1",children:e.title??e.id.slice(0,8)}),g.jsx(ts,{variant:i.variant,dot:!0,className:"shrink-0",children:i.label})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 font-mono text-label text-fg-4",children:[g.jsx("span",{className:"truncate",children:e.cwd}),e.profile?g.jsxs("span",{className:"shrink-0",children:["@",e.profile]}):null,g.jsx("span",{className:"shrink-0",children:tp(e.totalCostUsd)}),g.jsx("span",{className:"shrink-0",children:R1(e.lastActivityAt??e.createdAt)})]})]}),r?g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Close session",className:"opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e.id),children:g.jsx(A1,{className:"size-3.5 text-fg-3"})}):null]})}function hZ({sessions:e,activeId:t,onSelect:n,onDelete:r,emptyText:i="No sessions yet.",className:o}){return g.jsx("div",{"data-slot":"session-list",className:He("flex flex-col gap-1",o),children:e.length===0?g.jsx("div",{className:"px-2.5 py-6 text-center text-body-sm text-fg-4",children:i}):e.map(l=>g.jsx(dZ,{session:l,active:l.id===t,onSelect:n,onDelete:r},l.id))})}function pZ({className:e}){return g.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e,children:[g.jsx("path",{d:"M8 3.5h9A3.5 3.5 0 0 1 20.5 7v9"}),g.jsx("rect",{width:"13.5",height:"13.5",x:"3.5",y:"7",rx:"3.5"}),g.jsx("path",{d:"m7 16.5 2.5-2.5L7 11.5"}),g.jsx("circle",{cx:"13.2",cy:"14",r:"1.7",fill:"#2fbf71",stroke:"none"})]})}function xR(){const[e,t]=S.useState(Ub());return g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Toggle theme",onClick:()=>t(WO()),children:e==="dark"?g.jsx(h9,{className:"size-4"}):g.jsx(KP,{className:"size-4"})})}const mZ=[{id:"sessions",label:"Sessions",icon:u9,path:"/sessions"},{id:"jobs",label:"Jobs",icon:z3,path:"/jobs"},{id:"profiles",label:"Profiles",icon:x9,path:"/profiles"},{id:"settings",label:"Settings",icon:i9,path:"/settings"}],tw="workerdeck.sidebar-collapsed";function gZ({children:e}){const t=FI({select:o=>o.location.pathname}),[n,r]=S.useState(()=>{try{return localStorage.getItem(tw)==="1"}catch{return!1}}),i=()=>{r(o=>{try{localStorage.setItem(tw,o?"0":"1")}catch{}return!o})};return g.jsxs("div",{className:"flex h-dvh bg-sidebar",children:[g.jsxs("aside",{className:He("flex shrink-0 flex-col gap-1 p-3 transition-[width] duration-150",n?"w-14 items-center":"w-52"),children:[g.jsxs("div",{className:He("flex items-center py-2",n?"justify-center":"gap-2 px-2"),children:[g.jsx(pZ,{className:"size-4 shrink-0 text-fg-1"}),!n&&g.jsx("span",{className:"text-body-sm font-semibold tracking-tight text-fg-1",children:"workerdeck"})]}),g.jsx("nav",{className:He("mt-1 flex flex-1 flex-col gap-0.5",n&&"items-center"),children:mZ.map(o=>{const l=t.startsWith(o.path);return g.jsxs(yc,{to:o.path,title:n?o.label:void 0,"aria-label":o.label,className:He("flex items-center rounded-md text-body-sm transition-colors outline-none",n?"justify-center p-2":"gap-2 px-2 py-1.5",l?"bg-surface font-medium text-fg-1 shadow-(--shadow-xs)":"text-fg-3 hover:bg-surface-hover hover:text-fg-1"),children:[g.jsx(o.icon,{className:"size-4 shrink-0"}),!n&&o.label]},o.id)})}),g.jsxs("div",{className:He("flex items-center",n?"flex-col gap-1":"justify-between px-1"),children:[!n&&g.jsx("span",{className:"font-mono text-label text-fg-4",children:"v0.1"}),g.jsx(xR,{}),g.jsx("button",{type:"button",onClick:i,title:n?"Expand sidebar":"Collapse sidebar","aria-label":n?"Expand sidebar":"Collapse sidebar",className:"flex size-7 items-center justify-center rounded-md text-fg-3 transition-colors outline-none hover:bg-surface-hover hover:text-fg-1",children:n?g.jsx(JP,{className:"size-4"}):g.jsx(WP,{className:"size-4"})})]})]}),g.jsx("main",{className:"frame-shine m-2 ml-0 flex min-w-0 flex-1 flex-col overflow-hidden rounded-xl",children:e??g.jsx(Fw,{})})]})}const yR=[{value:"default",displayName:"Default (recommended)",description:"The CLI's configured default model"},{value:"fable",displayName:"Fable",description:"Fable 5 · Most capable for your hardest and longest-running tasks"},{value:"opus",displayName:"Opus",description:"Opus 4.8 with 1M context · Best for everyday, complex tasks"},{value:"sonnet",displayName:"Sonnet",description:"Sonnet 5 · Efficient for routine tasks"},{value:"haiku",displayName:"Haiku",description:"Haiku 4.5 · Fastest for quick answers"}],Bb={session:"workerdeck.default-session-model",job:"workerdeck.default-job-model"};function gx(e){return localStorage.getItem(Bb[e])??""}function bZ(e,t){const n=t.trim();n?localStorage.setItem(Bb[e],n):localStorage.removeItem(Bb[e])}const ER={session:"workerdeck.default-session-permission-mode",job:"workerdeck.default-job-permission-mode"},xZ={session:"default",job:"acceptEdits"};function bx(e){const t=localStorage.getItem(ER[e]);return cb.some(r=>r.value===t)?t:xZ[e]}function yZ(e,t){localStorage.setItem(ER[e],t)}function xx({value:e,onChange:t,models:n=yR,className:r}){return g.jsx(hA,{variant:"form",models:n,model:e||void 0,onModelChange:i=>t(i??""),className:r})}function TR({profiles:e,value:t,onChange:n,className:r}){return e.length===0?null:g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Profile"}),g.jsxs(Cc,{items:e.map(i=>({value:i.name,label:i.name})),value:t,onValueChange:i=>n(i),children:[g.jsx(kc,{className:r,children:g.jsx(wc,{})}),g.jsx(Ac,{children:e.map(i=>g.jsx(cl,{value:i.name,children:g.jsx(ul,{children:i.description?`${i.name} — ${i.description}`:i.name})},i.name))})]})]})}class EZ{sessionId;#t;#r;#n;#e=new Map;#s;#l=!1;#u=0;#i=[];#c;constructor(t,n,r={}){this.#t=t,this.sessionId=n,this.#r={reconnect:!0,...r},this.#s=r.afterSeq??0,this.#c=setTimeout(()=>this.#f(),0)}get lastSeq(){return this.#s}on(t,n){let r=this.#e.get(t);return r||(r=new Set,this.#e.set(t,r)),r.add(n),()=>r.delete(n)}send(t){this.#a({type:"user_message",text:t})}approve(t,n){this.#a({type:"permission_decision",requestId:t,behavior:"allow",updatedInput:n})}deny(t,n,r){this.#a({type:"permission_decision",requestId:t,behavior:"deny",message:n,interrupt:r})}interrupt(){this.#a({type:"interrupt"})}setPermissionMode(t){this.#a({type:"set_permission_mode",mode:t})}setModel(t){this.#a({type:"set_model",model:t})}sendToolCallResult(t,n,r){this.#a({type:"tool_call_result",executionId:t,output:n,logs:r})}sendToolCallError(t,n,r,i){this.#a({type:"tool_call_error",executionId:t,reason:n,error:r,logs:i})}closeSession(){this.#a({type:"close"}),this.detach()}detach(){this.#l=!0,clearTimeout(this.#c),this.#n?.close(),this.#n=void 0}#o(t,n){const r=this.#e.get(t);if(r)for(const i of r)try{i(n)}catch{}}#a(t){const n=JSON.stringify(t);this.#n&&this.#n.readyState===1?this.#n.send(n):this.#i.push(n)}#f(){if(this.#l)return;const t=this.#t.openSocket(this.sessionId,this.#s);this.#n=t,t.onopen=()=>{this.#u=0,this.#o("connectionChange",!0);for(const n of this.#i.splice(0))t.send(n)},t.onmessage=n=>{const r=JSON.parse(String(n.data));if(r.type==="attached")this.#o("attached",r);else if(r.type==="event"){if(r.event.seq<=this.#s)return;this.#s=r.event.seq,this.#o("event",r.event)}else r.type==="tool_call_request"?this.#o("toolCallRequest",r):r.type==="tool_call_canceled"?this.#o("toolCallCanceled",{executionId:r.executionId,reason:r.reason}):r.type==="protocol_error"&&this.#o("protocolError",r.message)},t.onclose=()=>{if(this.#o("connectionChange",!1),this.#l||!this.#r.reconnect)return;const n=Math.min(500*2**this.#u++,1e4);this.#c=setTimeout(()=>this.#f(),n)},t.onerror=()=>{}}}class TZ{#t;#r;#n;#e=new Map;#s=!1;#l=0;#u;constructor(t,n={}){this.#t=t,this.#r=n.reconnect??!0,this.#u=setTimeout(()=>this.#c(),0)}on(t,n){let r=this.#e.get(t);return r||(r=new Set,this.#e.set(t,r)),r.add(n),()=>r.delete(n)}detach(){this.#s=!0,clearTimeout(this.#u),this.#n?.close(),this.#n=void 0}#i(t,n){const r=this.#e.get(t);if(r)for(const i of r)try{i(n)}catch{}}#c(){if(this.#s)return;const t=this.#t.openQueueSocket();this.#n=t,t.onopen=()=>{this.#l=0,this.#i("connectionChange",!0)},t.onmessage=n=>{const r=JSON.parse(String(n.data));r.type==="queue_attached"?(this.#i("attached",r.stats),this.#i("stats",r.stats)):r.type==="job_event"?this.#i("event",r.event):r.type==="queue_stats"&&this.#i("stats",r.stats)},t.onclose=()=>{if(this.#i("connectionChange",!1),this.#s||!this.#r)return;const n=Math.min(500*2**this.#l++,1e4);this.#u=setTimeout(()=>this.#c(),n)},t.onerror=()=>{}}}class vZ{#t;#r;#n;constructor(t){this.#t=t,this.#r=t.fetchImpl??fetch.bind(globalThis),this.#n=t.WebSocketImpl??WebSocket}async createSession(t){return(await this.#e("POST","/sessions",t)).session}async listSessions(){return(await this.#e("GET","/sessions")).sessions}async getSession(t){return(await this.#e("GET",`/sessions/${encodeURIComponent(t)}`)).session}async deleteSession(t){return(await this.#e("DELETE",`/sessions/${encodeURIComponent(t)}`)).session}async listSessionFiles(t){return(await this.#e("GET",`/sessions/${encodeURIComponent(t)}/files`)).files}async fetchSessionFile(t,n){const r=await this.#r(this.sessionFileUrl(t,n),{headers:this.#t.headers});if(!r.ok){const i=await r.json().catch(()=>({}));throw new Error(i.error??`GET file failed with ${r.status}`)}return await r.text()}sessionFileUrl(t,n){const r=n.split("/").filter(Boolean).map(encodeURIComponent).join("/");return`${this.#t.baseUrl}/sessions/${encodeURIComponent(t)}/files/${r}`}async resolvePermission(t,n,r){await this.#e("POST",`/sessions/${encodeURIComponent(t)}/permissions/${encodeURIComponent(n)}`,r)}async submitExecutionResult(t,n){return await this.#e("POST",`/executions/${encodeURIComponent(t)}/result`,n)}async listProfiles(){return await this.#e("GET","/profiles")}async getProfile(t){return await this.#e("GET",`/profiles/${encodeURIComponent(t)}`)}async createProfile(t){return(await this.#e("POST","/profiles",t)).profile}async updateProfile(t,n){return(await this.#e("PATCH",`/profiles/${encodeURIComponent(t)}`,n)).profile}async deleteProfile(t){await this.#e("DELETE",`/profiles/${encodeURIComponent(t)}`)}async listSdkSessions(t){const n=new URLSearchParams;t?.dir&&n.set("dir",t.dir),t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset));const r=n.size>0?`?${n.toString()}`:"";return(await this.#e("GET",`/sdk-sessions${r}`)).sdkSessions}async listHostRoots(){return await this.#e("GET","/fs/roots")}async listHostDir(t){const n=`?path=${encodeURIComponent(t)}`;return await this.#e("GET",`/fs/list${n}`)}async findHostFiles(t,n="",r){const i=new URLSearchParams({path:t,q:n});return r!==void 0&&i.set("limit",String(r)),await this.#e("GET",`/fs/find?${i.toString()}`)}async readHostFile(t){const n=`?path=${encodeURIComponent(t)}`;return await this.#e("GET",`/fs/read${n}`)}async writeHostFile(t){return await this.#e("PUT","/fs/write",t)}async createJob(t){return(await this.#e("POST","/jobs",t)).job}async listJobs(){return(await this.#e("GET","/jobs")).jobs}async getJob(t){return(await this.#e("GET",`/jobs/${encodeURIComponent(t)}`)).job}async cancelJob(t){return(await this.#e("DELETE",`/jobs/${encodeURIComponent(t)}`)).job}async queueStats(){return(await this.#e("GET","/queue")).stats}attach(t,n){return new EZ(this,t,n)}attachQueue(t){return new TZ(this,t)}openSocket(t,n){const r=this.#t.buildWsUrl?.(t,n)??`${this.#t.baseUrl.replace(/^http/,"ws")}/sessions/${encodeURIComponent(t)}/ws?afterSeq=${n}`;return new this.#n(r)}openQueueSocket(){const t=this.#t.buildQueueWsUrl?.()??`${this.#t.baseUrl.replace(/^http/,"ws")}/queue/ws`;return new this.#n(t)}async#e(t,n,r){const i=await this.#r(`${this.#t.baseUrl}${n}`,{method:t,headers:{...r!==void 0?{"content-type":"application/json"}:{},...this.#t.headers},body:r!==void 0?JSON.stringify(r):void 0}),o=await i.json().catch(()=>({}));if(!i.ok)throw new Error(o.error??`${t} ${n} failed with ${i.status}`);return o}}const Kn=new vZ({baseUrl:`${location.origin}/v1`});function vR(e,t,n){const r=e?.engine==="provider",i=rj(e?.engine,t)?t:"default";if(!r)return{isProvider:r,modes:void 0,models:yR,mode:i,model:n};const o=e.provider,l=o?.models?.length?o.models:o?.model?[o.model]:[];return{isProvider:r,modes:ep,models:[{value:"default",displayName:"Profile default",description:o?.model??"the profile's configured model"},...l.map(c=>({value:c,displayName:c}))],mode:i,model:l.includes(n)?n:""}}function SZ(e=15e3){const[t,n]=S.useState([]),[r,i]=S.useState(),[o,l]=S.useState(!0),[c,f]=S.useState(!1),[d,m]=S.useState(),p=S.useRef(void 0),b=S.useCallback(async()=>{try{const[E,w]=await Promise.all([Kn.listJobs(),Kn.queueStats()]);n(E),i(w),l(!0),m(void 0)}catch(E){const w=E instanceof Error?E.message:String(E);/not configured/i.test(w)?(l(!1),m(void 0)):m(w)}},[]);S.useEffect(()=>(b(),p.current=setInterval(()=>void b(),e),()=>clearInterval(p.current)),[b,e]);const y=o&&r!==void 0;return S.useEffect(()=>{if(!y)return;const E=Kn.attachQueue(),w=[E.on("attached",()=>void b()),E.on("stats",i),E.on("connectionChange",f),E.on("event",k=>{n(C=>C.some(_=>_.id===k.job.id)?C.map(_=>_.id===k.job.id?k.job:_):[...C,k.job])})];return()=>{for(const k of w)k();E.detach()}},[y,b]),{jobs:t,stats:r,enabled:o,live:c,error:d,refresh:b}}const SR={profiles:[]};let jb,Pg;const Hb=new Set;async function nw(){const e=await Kn.listProfiles().catch(()=>SR);jb=e;for(const t of Hb)t(e);return e}function CR(){const[e,t]=S.useState(jb??SR);S.useEffect(()=>(Hb.add(t),jb||(Pg??=nw()),()=>{Hb.delete(t)}),[]);const n=S.useCallback(async()=>{Pg=nw(),await Pg},[]);return{...e,refresh:n}}function CZ(){return CR().profiles}const rw="workerdeck.last-profile";function wR(){const e=CZ(),[t,n]=S.useState(()=>localStorage.getItem(rw)??""),r=e.some(l=>l.name===t)?t:e[0]?.name??"",i=e.find(l=>l.name===r);return{profiles:e,profile:r,selected:i,select:l=>{n(l),localStorage.setItem(rw,l)}}}function kR(e=5e3){const[t,n]=S.useState([]),[r,i]=S.useState(),o=S.useRef(void 0),l=S.useCallback(async()=>{try{n(await Kn.listSessions()),i(void 0)}catch(c){i(c instanceof Error?c.message:String(c))}},[]);return S.useEffect(()=>(l(),o.current=setInterval(()=>void l(),e),()=>clearInterval(o.current)),[l,e]),{sessions:t,error:r,refresh:l}}const sw="workerdeck.last-cwd",wZ={queued:{label:"Queued",variant:"neutral"},running:{label:"Running",variant:"info",busy:!0},parked:{label:"Parked",variant:"accent"},succeeded:{label:"Succeeded",variant:"success"},failed:{label:"Failed",variant:"danger"},canceled:{label:"Canceled",variant:"warning"}};function kZ({stats:e}){const t=e.dailyTokenLimit!==void 0&&e.dailyTokenLimit>0?e.dailyTokensUsed/e.dailyTokenLimit*100:void 0;return g.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2 rounded-md border border-border bg-surface px-3 py-2 text-body-sm text-fg-2",children:[g.jsxs("span",{children:["Running ",g.jsxs("span",{className:"font-mono text-fg-1",children:[e.running,"/",e.maxConcurrency]})]}),g.jsxs("span",{children:["Queued ",g.jsx("span",{className:"font-mono text-fg-1",children:e.queued})]}),e.parked>0?g.jsxs("span",{children:["Parked ",g.jsx("span",{className:"font-mono text-fg-1",children:e.parked})]}):null,g.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t!==void 0?g.jsx(Z3,{value:t,className:t>=95?"text-danger":t>=80?"text-warning":"text-fg-3"}):null,"Daily tokens"," ",g.jsxs("span",{className:"font-mono text-fg-1",children:[Qi(e.dailyTokensUsed),e.dailyTokenLimit!==void 0?` / ${Qi(e.dailyTokenLimit)}`:""]})]}),e.sessionTokenLimit!==void 0?g.jsxs("span",{children:["Per-job cap ",g.jsx("span",{className:"font-mono text-fg-1",children:Qi(e.sessionTokenLimit)})]}):null,e.paused?g.jsx(ts,{variant:"warning",dot:!0,children:"Paused — daily budget exhausted"}):null]})}function AZ({onScheduled:e}){const[t,n]=S.useState(()=>localStorage.getItem(sw)??""),[r,i]=S.useState(""),[o,l]=S.useState(()=>bx("job")),[c,f]=S.useState("auto"),[d,m]=S.useState(()=>gx("job")),{profiles:p,profile:b,selected:y,select:E}=wR(),w=vR(y,o,d),[k,C]=S.useState(!1),[A,_]=S.useState(""),[N,M]=S.useState(""),[O,P]=S.useState(""),[D,Y]=S.useState(!1),U=async()=>{if(!t.trim()||!r.trim()){Mn.error("Working directory and prompt are required");return}const $=A.trim()?Number(A.trim()):void 0;if($!==void 0&&(!Number.isFinite($)||$<=0)){Mn.error("Max tokens must be a positive number");return}const Q=N.trim()?Number(N.trim()):void 0;if(Q!==void 0&&(!Number.isInteger(Q)||Q<1)){Mn.error("Attempts must be a whole number of at least 1");return}Y(!0);try{localStorage.setItem(sw,t.trim()),await Kn.createJob({session:{cwd:t.trim(),profile:b||void 0,prompt:r.trim(),permissionMode:w.mode,questionBehavior:c,model:w.model.trim()||void 0,...w.isProvider?{}:{settingSources:["user","project"],allowDangerouslySkipPermissions:k||void 0}},maxTokens:$,attempts:Q,webhook:O.trim()?{url:O.trim()}:void 0}),i(""),Mn.success("Job scheduled"),e()}catch(J){Mn.error(J instanceof Error?J.message:"Failed to schedule job")}finally{Y(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Schedule a job"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Working directory"}),g.jsx(bn,{value:t,onChange:$=>n($.target.value),placeholder:"/path/to/project",spellCheck:!1,className:"font-mono"})]}),g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Prompt (the task — runs unattended)"}),g.jsx(Xb,{value:r,onChange:$=>i($.target.value),rows:2,placeholder:"e.g. /verify-content 42, or a task description"})]}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(TR,{profiles:p,value:b,onChange:E,className:"min-w-32"}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Permission mode"}),g.jsx(Rc,{variant:"form",mode:w.mode,onModeChange:l,modes:w.modes,className:"min-w-44"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Questions"}),g.jsxs(Cc,{items:aS.map($=>({value:$.value,label:$.label})),value:c,onValueChange:$=>f($),children:[g.jsx(kc,{className:"min-w-36",children:g.jsx(wc,{})}),g.jsx(Ac,{children:aS.map($=>g.jsx(cl,{value:$.value,children:g.jsx(ul,{children:`${$.label} — ${$.description}`})},$.value))})]})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Model"}),g.jsx(xx,{value:w.model,onChange:m,models:w.models,className:"min-w-40"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Max tokens (optional)"}),g.jsx(bn,{value:A,onChange:$=>_($.target.value),placeholder:"per-job cap",inputMode:"numeric",className:"min-w-28 font-mono"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Attempts (optional)"}),g.jsx(bn,{value:N,onChange:$=>M($.target.value),placeholder:"1",inputMode:"numeric",className:"min-w-20 font-mono"})]}),g.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Webhook URL (optional)"}),g.jsx(bn,{value:O,onChange:$=>P($.target.value),placeholder:"https://…/hook",spellCheck:!1,className:"min-w-44 font-mono"})]}),g.jsxs($t,{onClick:()=>void U(),disabled:D,children:[D?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(k1,{className:"size-4"}),"Schedule"]})]}),w.isProvider?null:g.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 text-body-sm text-fg-2",title:"Spawns the CLI with --dangerously-skip-permissions available, so the mode can be switched on while watching the run. The job still starts in the mode selected above.",children:[g.jsx("input",{type:"checkbox",checked:k,onChange:$=>C($.target.checked),className:"size-3.5 accent-(--color-fg-1)"}),"Allow switching to ",g.jsx("code",{className:"font-mono",children:"bypassPermissions"})," mid-run",g.jsx("span",{className:"text-label text-fg-4",children:"(dangerous)"})]}),g.jsxs("p",{className:"text-label text-fg-4",children:["Unattended runs still surface permission prompts — watch the job's session to approve, or pick a mode that doesn't ask. Unanswered prompts deny after the server's timeout. With Questions set to Ask, webhook deliveries carry the full question so a controller can answer via"," ",g.jsx("code",{className:"font-mono",children:"POST /sessions/:id/permissions/:requestId"}),"."]})]})]})}function _Z({job:e,watchable:t,onChanged:n}){const r=ml(),i=wZ[e.status],o=e.status==="queued"||e.status==="running"||e.status==="parked",l=async()=>{try{await Kn.cancelJob(e.id),n()}catch(c){Mn.error(c instanceof Error?c.message:"Cancel failed")}};return g.jsxs("li",{className:"flex items-center gap-3 rounded-md px-2 py-2 hover:bg-surface-hover",children:[g.jsxs(ts,{variant:i.variant,dot:!i.busy,children:[i.busy?g.jsx(ci,{className:"size-3 text-current"}):null,i.label]}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-body-sm text-fg-1",children:e.prompt}),g.jsxs("div",{className:"flex flex-wrap gap-x-3 font-mono text-label text-fg-4",children:[g.jsx("span",{className:"truncate",children:e.cwd}),e.profile?g.jsxs("span",{className:"shrink-0",children:["@",e.profile]}):null,g.jsx("span",{className:"shrink-0",children:R1(e.finishedAt??e.startedAt??e.createdAt)}),e.maxAttempts!==void 0&&e.maxAttempts>1?g.jsxs("span",{className:"shrink-0",children:["attempt ",e.attempt??1,"/",e.maxAttempts,e.status==="queued"&&e.nextRunAt!==void 0&&e.nextRunAt>Date.now()?" — retry pending":""]}):null,e.usage.tokens>0?g.jsxs("span",{className:"shrink-0",children:[Qi(e.usage.tokens)," tok"]}):null,e.usage.totalCostUsd>0?g.jsx("span",{className:"shrink-0",children:tp(e.usage.totalCostUsd)}):null,e.error?g.jsx("span",{className:"truncate text-danger",children:e.error}):null]})]}),e.sessionId&&t?g.jsxs($t,{variant:"ghost",size:"xs",onClick:()=>void r({to:"/sessions/$sessionId",params:{sessionId:e.sessionId}}),children:[g.jsx(U3,{className:"size-3"}),"Watch"]}):null,o?g.jsxs($t,{variant:"outline",size:"xs",onClick:()=>void l(),children:[g.jsx(V3,{className:"size-3"}),"Cancel"]}):null]})}function NZ(){const{jobs:e,stats:t,enabled:n,live:r,error:i,refresh:o}=SZ(),{sessions:l}=kR(),c=new Set(l.map(d=>d.id)),f=[...e].sort((d,m)=>m.createdAt-d.createdAt);return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{className:"flex items-end justify-between",children:[g.jsxs("div",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Jobs"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"Scheduled one-shot runs with concurrency and token budgets."})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[n?g.jsx(ts,{variant:r?"success":"neutral",dot:!0,children:r?"Live":"Polling"}):null,g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Refresh",onClick:()=>void o(),children:g.jsx(F3,{className:"size-4"})})]})]}),i?g.jsxs("div",{className:"rounded-md bg-danger-bg px-3 py-2 text-body-sm text-danger",children:["Can't reach the worker server: ",i,". Start it with"," ",g.jsx("code",{className:"font-mono",children:"pnpm server"}),"."]}):null,n?g.jsxs(g.Fragment,{children:[t?g.jsx(kZ,{stats:t}):null,f.length===0?g.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-border bg-surface px-4 py-8 text-center",children:[g.jsx(z3,{className:"size-6 text-fg-4"}),g.jsx("p",{className:"text-body-sm text-fg-2",children:"No jobs yet. Schedule one below."})]}):g.jsx("ul",{className:"flex flex-col gap-1 rounded-md border border-border bg-surface p-1",children:f.map(d=>g.jsx(_Z,{job:d,watchable:d.sessionId!==void 0&&c.has(d.sessionId),onChanged:()=>void o()},d.id))}),g.jsx(AZ,{onScheduled:()=>void o()})]}):g.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-border bg-surface px-4 py-8 text-center",children:[g.jsx(CP,{className:"size-6 text-fg-4"}),g.jsx("p",{className:"text-body-sm text-fg-2",children:"The server has no job queue configured."}),g.jsxs("p",{className:"text-label text-fg-4",children:["Pass ",g.jsxs("code",{className:"font-mono",children:["queue: ","{ maxConcurrency, … }"]})," to"," ",g.jsx("code",{className:"font-mono",children:"createWorkerServer"})," — the dev server enables it by default."]})]})]})})}const RZ=["web_search","download","web_fetch","deliver_file"],Od=e=>e.split(",").map(t=>t.trim()).filter(Boolean);function zi({label:e,children:t}){return g.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:e}),t]})}function OZ({profile:e,onSaved:t}){const n=e.engine==="provider",[r,i]=S.useState(e.description??""),[o,l]=S.useState(e.defaults?.model??""),[c,f]=S.useState(e.defaults?.permissionMode),[d,m]=S.useState(e.provider?.model??""),[p,b]=S.useState((e.provider?.models??[]).join(", ")),[y,E]=S.useState(e.session?.capabilities),[w,k]=S.useState((e.session?.mcpServers??[]).join(", ")),[C,A]=S.useState(e.session?.instructions??""),[_,N]=S.useState(!1),M=async()=>{const O={description:r.trim()||void 0,defaults:{model:o.trim()||void 0,permissionMode:c}};n&&(O.provider={...e.provider,id:e.provider?.id??"",model:d.trim()||void 0,models:Od(p).length>0?Od(p):void 0},O.session={capabilities:y,mcpServers:Od(w).length>0?Od(w):void 0,instructions:C.trim()||void 0}),N(!0);try{t(await Kn.updateProfile(e.name,O)),Mn.success("Profile saved")}catch(P){Mn.error(P instanceof Error?P.message:"Failed to save profile")}finally{N(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Edit profile"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsx(zi,{label:"Description",children:g.jsx(bn,{value:r,onChange:O=>i(O.target.value)})}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(zi,{label:"Default model",children:g.jsx(bn,{value:o,onChange:O=>l(O.target.value),placeholder:"unset — request / engine default",className:"font-mono"})}),g.jsx(zi,{label:"Default permission mode",children:g.jsx(Rc,{variant:"form",mode:c,onModeChange:f,modes:n?ep:void 0})})]}),n?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(zi,{label:"Default model id",children:g.jsx(bn,{value:d,onChange:O=>m(O.target.value),className:"font-mono"})}),g.jsx(zi,{label:"Models offered (comma-separated)",children:g.jsx(bn,{value:p,onChange:O=>b(O.target.value),className:"font-mono"})})]}),g.jsx(zi,{label:"Capabilities granted",children:g.jsxs("div",{className:"flex flex-wrap items-center gap-3 py-1.5",children:[g.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-body-sm text-fg-2",children:[g.jsx("input",{type:"checkbox",checked:y===void 0,onChange:O=>E(O.target.checked?void 0:[]),className:"size-3.5 accent-(--color-fg-1)"}),"not declared"]}),RZ.map(O=>g.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-body-sm text-fg-2",children:[g.jsx("input",{type:"checkbox",disabled:y===void 0,checked:y?.includes(O)??!1,onChange:P=>E(D=>P.target.checked?[...D??[],O]:(D??[]).filter(Y=>Y!==O)),className:"size-3.5 accent-(--color-fg-1) disabled:opacity-40"}),g.jsx("code",{className:"font-mono text-label",children:O})]},O))]})}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(zi,{label:"MCP servers (names, comma-separated)",children:g.jsx(bn,{value:w,onChange:O=>k(O.target.value),className:"font-mono"})}),g.jsx(zi,{label:"Instructions",children:g.jsx(bn,{value:C,onChange:O=>A(O.target.value)})})]})]}):null,g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("p",{className:"text-label text-fg-4",children:"Name and engine are fixed — sessions and jobs are pinned to the name, and the engine decides what the rest of these fields mean."}),g.jsxs($t,{onClick:()=>void M(),disabled:_,children:[_?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(r9,{className:"size-4"}),"Save"]})]})]})]})}const IZ=["web_search","download","web_fetch","deliver_file"],Id=e=>e.split(",").map(t=>t.trim()).filter(Boolean);function as({label:e,children:t}){return g.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:e}),t]})}function LZ({onCreated:e}){const[t,n]=S.useState("provider"),[r,i]=S.useState(""),[o,l]=S.useState(""),[c,f]=S.useState(""),[d,m]=S.useState(""),[p,b]=S.useState(""),[y,E]=S.useState(""),[w,k]=S.useState(""),[C,A]=S.useState([]),[_,N]=S.useState(""),[M,O]=S.useState(""),[P,D]=S.useState(!1),Y=t==="provider",U=async()=>{if(!r.trim()){Mn.error("Name is required");return}const $={name:r.trim(),engine:t};if(o.trim()&&($.description=o.trim()),Y){$.provider={id:c.trim(),model:d.trim()||void 0,models:Id(p).length>0?Id(p):void 0,apiKeyEnv:y.trim()||void 0};const Q={};C.length>0&&(Q.capabilities=C),Id(_).length>0&&(Q.mcpServers=Id(_)),M.trim()&&(Q.instructions=M.trim()),Object.keys(Q).length>0&&($.session=Q)}else $.configDir=w.trim();D(!0);try{await Kn.createProfile($),await e(),i(""),l(""),O(""),Mn.success(`Profile '${$.name}' created`)}catch(Q){Mn.error(Q instanceof Error?Q.message:"Failed to create profile")}finally{D(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"New profile"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(as,{label:"Engine",children:g.jsxs(Cc,{items:[{value:"provider",label:"provider"},{value:"claude",label:"claude"}],value:t,onValueChange:$=>n($),children:[g.jsx(kc,{className:"min-w-32",children:g.jsx(wc,{})}),g.jsxs(Ac,{children:[g.jsx(cl,{value:"provider",children:g.jsx(ul,{children:"provider — model-agnostic engine"})}),g.jsx(cl,{value:"claude",children:g.jsx(ul,{children:"claude — Agent SDK + config dir"})})]})]})}),g.jsx(as,{label:"Name",children:g.jsx(bn,{value:r,onChange:$=>i($.target.value),placeholder:"kimi"})}),g.jsx(as,{label:"Description (optional)",children:g.jsx(bn,{value:o,onChange:$=>l($.target.value),placeholder:"what this profile is for"})})]}),Y?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(as,{label:"Provider id",children:g.jsx(bn,{value:c,onChange:$=>f($.target.value),placeholder:"anthropic / openai / moonshotai",className:"font-mono"})}),g.jsx(as,{label:"Default model",children:g.jsx(bn,{value:d,onChange:$=>m($.target.value),placeholder:"kimi-k3",className:"font-mono"})}),g.jsx(as,{label:"Models offered (comma-separated)",children:g.jsx(bn,{value:p,onChange:$=>b($.target.value),placeholder:"kimi-k3, kimi-k2",className:"font-mono"})}),g.jsx(as,{label:"API key variable",children:g.jsx(bn,{value:y,onChange:$=>E($.target.value),placeholder:"MOONSHOT_API_KEY",className:"font-mono"})})]}),g.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[g.jsx(as,{label:"Capabilities granted",children:g.jsx("div",{className:"flex flex-wrap gap-3 py-1.5",children:IZ.map($=>g.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-body-sm text-fg-2",children:[g.jsx("input",{type:"checkbox",checked:C.includes($),onChange:Q=>A(J=>Q.target.checked?[...J,$]:J.filter(te=>te!==$)),className:"size-3.5 accent-(--color-fg-1)"}),g.jsx("code",{className:"font-mono text-label",children:$})]},$))})}),g.jsx(as,{label:"MCP servers (names, comma-separated)",children:g.jsx(bn,{value:_,onChange:$=>N($.target.value),placeholder:"deepwiki",className:"font-mono"})})]}),g.jsx(as,{label:"Instructions (optional)",children:g.jsx(bn,{value:M,onChange:$=>O($.target.value),placeholder:"prepended to the session's system prompt"})}),g.jsx("p",{className:"text-label text-fg-4",children:"Leave capabilities and MCP servers empty to inherit whatever the server's engine factory wired — that factory is the ceiling either way, so a grant here can never exceed it. MCP servers are named, never configured: their transport config (and any credentials in it) stays on the server."})]}):g.jsxs(g.Fragment,{children:[g.jsx(as,{label:"Config directory",children:g.jsx(bn,{value:w,onChange:$=>k($.target.value),placeholder:"/Users/you/.claude",spellCheck:!1,className:"font-mono"})}),g.jsxs("p",{className:"text-label text-fg-4",children:["Must resolve inside the server's"," ",g.jsx("code",{className:"font-mono",children:"allowedConfigDirRoots"})," — a config directory is a credential store, so the server bounds which ones a managed profile may point at."]})]}),g.jsx("div",{className:"flex justify-end",children:g.jsxs($t,{onClick:()=>void U(),disabled:P,children:[P?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(k1,{className:"size-4"}),"Create profile"]})})]})]})}function AR(e){window.location.href=`vscode://file${e}`}function MZ(){const{profiles:e,canManage:t,refresh:n}=CR(),r=ml(),i=o=>{Kn.deleteProfile(o).then(()=>n()).then(()=>Mn.success(`Profile '${o}' deleted`)).catch(l=>Mn.error(l instanceof Error?l.message:"Delete failed"))};return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Profiles"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"What a session runs as: a named Claude Code config directory — its own settings, memory, skills, and credentials — or a model provider for the model-agnostic engine."})]}),e.length===0?g.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-md border border-border bg-surface px-4 py-8 text-center",children:[g.jsx(UP,{className:"size-6 text-fg-4"}),g.jsx("p",{className:"text-body-sm text-fg-2",children:"The server declares no profiles."}),g.jsxs("p",{className:"text-label text-fg-4",children:["Pass ",g.jsxs("code",{className:"font-mono",children:["profiles: [","{ name, configDir, … }","]"]})," to"," ",g.jsx("code",{className:"font-mono",children:"createWorkerServer"})," — without the option, a"," ",g.jsx("code",{className:"font-mono",children:"default"})," profile is auto-created from"," ",g.jsx("code",{className:"font-mono",children:"~/.claude"})," when it exists."]})]}):g.jsx("ul",{className:"divide-y divide-border rounded-md border border-border bg-surface",children:e.map(o=>g.jsxs("li",{className:"flex items-center gap-3 px-3 py-2.5",children:[g.jsx(g9,{className:"size-4 shrink-0 text-fg-3"}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"truncate text-body-sm font-medium text-fg-1",children:o.name}),o.description?g.jsx("span",{className:"truncate text-body-sm text-fg-3",children:o.description}):null]}),g.jsx("div",{className:"mt-0.5 truncate font-mono text-label text-fg-4",children:o.configDir??(o.provider?`${o.provider.id}${o.provider.model?` · ${o.provider.model}`:""}`:"")})]}),g.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[g.jsx(ts,{variant:"neutral",children:o.engine??"claude"}),o.defaults?.model?g.jsx(ts,{variant:"neutral",children:o.defaults.model}):null,o.defaults?.permissionMode?g.jsx(ts,{variant:"neutral",children:o.defaults.permissionMode}):null,o.configDir?g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":`Open ${o.name} in VSCode`,title:"Open config dir in VSCode",onClick:()=>AR(o.configDir),children:g.jsx(H3,{className:"size-4"})}):null,g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":`View ${o.name}`,title:"View profile",onClick:()=>void r({to:"/profiles/$profileName",params:{profileName:o.name}}),children:g.jsx(U3,{className:"size-4"})}),o.managed?g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":`Delete ${o.name}`,title:"Delete profile",onClick:()=>i(o.name),children:g.jsx(A1,{className:"size-4"})}):null]})]},o.name))}),t?g.jsx(LZ,{onCreated:n}):null,g.jsxs("p",{className:"text-label text-fg-4",children:["Session and job creates run under the selected profile; when the server declares more than one, picking a profile is required."," ",t?"Profiles created here are stored by the server; the ones declared in its options are code and stay read-only.":"Profiles are declared in server configuration and read-only here."]})]})})}function _n({label:e,children:t}){return g.jsxs("div",{className:"flex items-baseline justify-between gap-4 py-1.5",children:[g.jsx("span",{className:"shrink-0 text-label font-medium text-fg-3",children:e}),g.jsx("span",{className:"min-w-0 text-right text-body-sm text-fg-1",children:t})]})}function Fi({items:e,empty:t}){return e.length===0?g.jsx("span",{className:"text-fg-4",children:t}):g.jsx("span",{className:"flex flex-wrap justify-end gap-1",children:e.map(n=>g.jsx(ts,{variant:"neutral",children:n},n))})}function DZ(){const{profileName:e}=Oh({from:"/profiles/$profileName"}),[t,n]=S.useState(),[r,i]=S.useState();S.useEffect(()=>{let c=!0;return Kn.getProfile(e).then(f=>{c&&n(f)}).catch(f=>{c&&i(f instanceof Error?f.message:"Failed to load profile")}),()=>{c=!1}},[e]);const o=t?.profile,l=t?.config;return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{className:"flex items-end justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs(yc,{to:"/profiles",className:"mb-1 inline-flex items-center gap-1 text-label text-fg-3 hover:text-fg-1",children:[g.jsx(P3,{className:"size-3"}),"Profiles"]}),g.jsx("h1",{className:"truncate text-display-sm font-semibold tracking-tight text-text",children:e}),o?.description?g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:o.description}):null]}),o?.configDir?g.jsxs($t,{variant:"outline",size:"xs",onClick:()=>AR(o.configDir),children:[g.jsx(H3,{className:"size-3"}),"Open in VSCode"]}):null]}),r?g.jsx("div",{className:"rounded-md bg-danger-bg px-3 py-2 text-body-sm text-danger",children:r}):null,!t&&!r?g.jsx(ci,{className:"mx-auto size-5 text-fg-4"}):null,o&&l?g.jsxs(g.Fragment,{children:[g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Worker defaults"})}),g.jsxs(Rs,{className:"flex flex-col divide-y divide-border",children:[g.jsx(_n,{label:"Engine",children:g.jsx(ts,{variant:"neutral",children:o.engine??"claude"})}),o.engine==="provider"?g.jsx(_n,{label:"Provider",children:g.jsx("span",{className:"font-mono text-label",children:o.provider?.id})}):g.jsx(_n,{label:"Config directory",children:g.jsx("span",{className:"font-mono text-label",children:o.configDir})}),g.jsx(_n,{label:"Default model",children:o.defaults?.model??o.provider?.model??g.jsx("span",{className:"text-fg-4",children:"request / engine default"})}),g.jsx(_n,{label:"Default permission mode",children:o.defaults?.permissionMode??g.jsx("span",{className:"text-fg-4",children:"request / engine default"})}),o.engine==="provider"?g.jsxs(g.Fragment,{children:[g.jsx(_n,{label:"Models offered",children:g.jsx(Fi,{items:o.provider?.models??[],empty:"the default model only"})}),g.jsx(_n,{label:"API key variable",children:o.provider?.apiKeyEnv?g.jsx("span",{className:"font-mono text-label",children:o.provider.apiKeyEnv}):g.jsx("span",{className:"text-fg-4",children:"provider SDK default"})})]}):null]})]}),o.engine==="provider"?g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Session grants"})}),g.jsxs(Rs,{className:"flex flex-col divide-y divide-border",children:[g.jsx(_n,{label:"Capabilities",children:g.jsx(Fi,{items:o.session?.capabilities??[],empty:"not declared — whatever the server wired"})}),g.jsx(_n,{label:"MCP servers",children:g.jsx(Fi,{items:o.session?.mcpServers??[],empty:"not declared — every connected server"})}),g.jsx(_n,{label:"Instructions",children:o.session?.instructions?`${o.session.instructions.length} characters`:g.jsx("span",{className:"text-fg-4",children:"none"})})]})]}):null,o.engine==="provider"?null:g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Claude Code configuration"})}),g.jsxs(Rs,{className:"flex flex-col divide-y divide-border",children:[l.settings?g.jsxs(g.Fragment,{children:[g.jsx(_n,{label:"Model (settings.json)",children:l.settings.model??g.jsx("span",{className:"text-fg-4",children:"not set"})}),g.jsx(_n,{label:"Default permission mode",children:l.settings.defaultPermissionMode??g.jsx("span",{className:"text-fg-4",children:"not set"})}),g.jsx(_n,{label:"Permission rules",children:g.jsx("span",{className:"font-mono text-label",children:l.settings.permissionRules?`${l.settings.permissionRules.allow} allow · ${l.settings.permissionRules.ask} ask · ${l.settings.permissionRules.deny} deny`:"—"})}),g.jsx(_n,{label:"Env vars (names only)",children:g.jsx(Fi,{items:l.settings.envKeys??[],empty:"none"})}),g.jsx(_n,{label:"Hooks",children:g.jsx(Fi,{items:l.settings.hooks??[],empty:"none"})})]}):g.jsx(_n,{label:"settings.json",children:g.jsx("span",{className:"text-fg-4",children:"not found"})}),g.jsx(_n,{label:"User memory (CLAUDE.md)",children:l.hasUserMemory?"present":g.jsx("span",{className:"text-fg-4",children:"none"})}),g.jsx(_n,{label:"Skills",children:g.jsx(Fi,{items:l.skills,empty:"none"})}),g.jsx(_n,{label:"Agents",children:g.jsx(Fi,{items:l.agents,empty:"none"})}),g.jsx(_n,{label:"Commands",children:g.jsx(Fi,{items:l.commands,empty:"none"})})]})]}),o.managed?g.jsx(OZ,{profile:o,onSaved:c=>n({...t,profile:c})}):null,g.jsxs("p",{className:"text-label text-fg-4",children:[o.managed?"Stored on the server and editable here. ":"View only — this profile is declared in the server options. ","Other profile configuration lives on the server (the"," ",g.jsx("code",{className:"font-mono",children:"profiles"})," option; for Claude profiles, the config directory itself, e.g. via VSCode). Provider credentials are resolved from the server's environment and never leave it."]})]}):null]})})}function PZ(){const{sessionId:e}=Oh({from:"/sessions/$sessionId"}),t=ml(),[n,r]=S.useState();S.useEffect(()=>{let o=!1;return Kn.getSession(e).then(l=>{o||r(l)}).catch(()=>{Mn.error("Session not found"),t({to:"/sessions"})}),()=>{o=!0}},[e,t]);const i=async()=>{try{await Kn.deleteSession(e)}catch{}t({to:"/sessions"})};return g.jsx(fZ,{client:Kn,sessionId:e,header:g.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[g.jsx(yc,{to:"/sessions","aria-label":"Back to sessions",children:g.jsx($t,{variant:"ghost",size:"icon-sm",children:g.jsx(P3,{className:"size-4"})})}),g.jsx("span",{className:"truncate text-body-sm font-medium text-fg-1",children:n?.title??e.slice(0,8)}),n?.cwd?g.jsx("span",{className:"truncate font-mono text-label text-fg-4",children:n.cwd}):null,g.jsx("span",{className:"flex-1"}),g.jsx(W3,{value:e,"aria-label":"Copy session id"}),g.jsxs($9,{children:[g.jsx(q9,{render:g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Close session",children:g.jsx(A1,{className:"size-4 text-fg-3"})})}),g.jsxs(G9,{children:[g.jsx(X9,{children:"Close this session?"}),g.jsx(K9,{children:"The Claude Code subprocess is terminated. You can resume it later from “Resume a previous session” (the transcript is kept on disk by the SDK)."}),g.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[g.jsx(Y9,{render:g.jsx($t,{variant:"outline",children:"Cancel"})}),g.jsx($t,{variant:"destructive",onClick:()=>void i(),children:"Close session"})]})]})]})]})},e)}const iw="workerdeck.last-cwd";function BZ({onCreated:e}){const[t,n]=S.useState(()=>localStorage.getItem(iw)??""),[r,i]=S.useState(""),[o,l]=S.useState(()=>bx("session")),[c,f]=S.useState(()=>gx("session")),{profiles:d,profile:m,selected:p,select:b}=wR(),y=vR(p,o,c),[E,w]=S.useState(!1),[k,C]=S.useState(),[A,_]=S.useState(!1),N=async O=>{const P=O?.cwd??t.trim();if(!P){Mn.error("Working directory is required");return}w(!0);try{localStorage.setItem(iw,t.trim()||P);const D=await Kn.createSession({cwd:P,profile:m||void 0,prompt:O?void 0:r.trim()||void 0,permissionMode:y.mode,model:y.model.trim()||void 0,resume:O?.sessionId,...y.isProvider?{}:{settingSources:["user","project"],allowDangerouslySkipPermissions:!0}});e(D.id)}catch(D){Mn.error(D instanceof Error?D.message:"Failed to create session")}finally{w(!1)}},M=async()=>{if(!t.trim()){Mn.error("Set a working directory first — resumable sessions are listed per project");return}_(!0);try{C(await Kn.listSdkSessions({dir:t.trim(),limit:20}))}catch(O){Mn.error(O instanceof Error?O.message:"Failed to list resumable sessions")}finally{_(!1)}};return g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"New session"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Working directory"}),g.jsx(bn,{value:t,onChange:O=>n(O.target.value),placeholder:"/path/to/project",spellCheck:!1,className:"font-mono"})]}),g.jsxs("label",{className:"flex flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Initial prompt (optional)"}),g.jsx(Xb,{value:r,onChange:O=>i(O.target.value),rows:2,placeholder:"e.g. /verify-content 42, or a task description"})]}),g.jsxs("div",{className:"flex items-end justify-between gap-3",children:[g.jsx(TR,{profiles:d,value:m,onChange:b,className:"min-w-32"}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Permission mode"}),g.jsx(Rc,{variant:"form",mode:y.mode,onModeChange:l,modes:y.modes,className:"min-w-44"})]}),g.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Model"}),g.jsx(xx,{value:y.model,onChange:f,models:y.models,className:"min-w-44"})]}),g.jsxs($t,{onClick:()=>void N(),disabled:E,children:[E?g.jsx(ci,{className:"size-3.5 text-current"}):g.jsx(k1,{className:"size-4"}),"Create"]})]}),y.isProvider?null:g.jsxs("div",{className:"mt-1 border-t border-border pt-3",children:[g.jsxs("div",{className:"flex items-center justify-between",children:[g.jsx("span",{className:"text-label font-medium text-fg-3",children:"Resume a previous session"}),g.jsxs($t,{variant:"ghost",size:"xs",onClick:()=>void M(),disabled:A,children:[A?g.jsx(ci,{className:"size-3 text-current"}):g.jsx(FP,{className:"size-3"}),k?"Reload":"Browse"]})]}),k!==void 0?k.length===0?g.jsx("div",{className:"py-3 text-center text-body-sm text-fg-4",children:"No stored sessions for this directory."}):g.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:k.map(O=>g.jsxs("li",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-surface-hover",children:[g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-body-sm text-fg-1",children:O.customTitle??O.summary}),g.jsxs("div",{className:"flex gap-2 font-mono text-label text-fg-4",children:[O.gitBranch?g.jsx("span",{className:"truncate",children:O.gitBranch}):null,g.jsx("span",{className:"shrink-0",children:R1(O.lastModified)})]})]}),g.jsx($t,{variant:"outline",size:"xs",onClick:()=>void N(O),disabled:E,children:"Resume"})]},O.sessionId))}):null]})]})]})}function jZ(){const e=ml(),{sessions:t,error:n,refresh:r}=kR(),i=o=>void e({to:"/sessions/$sessionId",params:{sessionId:o}});return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-5 px-6 py-6",children:[g.jsxs("header",{className:"flex items-end justify-between",children:[g.jsxs("div",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Sessions"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"Live Agent SDK sessions on this worker."})]}),g.jsx($t,{variant:"ghost",size:"icon-sm","aria-label":"Refresh",onClick:()=>void r(),children:g.jsx(F3,{className:"size-4"})})]}),n?g.jsxs("div",{className:"rounded-md bg-danger-bg px-3 py-2 text-body-sm text-danger",children:["Can’t reach the worker server: ",n,". Start it with ",g.jsx("code",{className:"font-mono",children:"pnpm server"}),"."]}):null,g.jsx(hZ,{sessions:[...t].sort((o,l)=>(l.lastActivityAt??l.createdAt)-(o.lastActivityAt??o.createdAt)),onSelect:i,onDelete:o=>{Kn.deleteSession(o).then(()=>r()).catch(l=>Mn.error(l instanceof Error?l.message:"Delete failed"))},emptyText:"No live sessions. Create one below."}),g.jsx(BZ,{onCreated:i})]})})}function aw({kind:e,label:t}){const[n,r]=S.useState(()=>gx(e)),[i,o]=S.useState(()=>bx(e));return g.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-2",children:[g.jsx("span",{className:"text-body-sm text-fg-2",children:t}),g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx(Rc,{variant:"form",mode:i,onModeChange:l=>{o(l),yZ(e,l)},className:"min-w-40"}),g.jsx(xx,{value:n,onChange:l=>{r(l),bZ(e,l)},className:"min-w-44"})]})]})}function HZ(){return g.jsx("div",{className:"flex-1 overflow-y-auto",children:g.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4 px-6 py-6",children:[g.jsxs("header",{children:[g.jsx("h1",{className:"text-display-sm font-semibold tracking-tight text-text",children:"Settings"}),g.jsx("p",{className:"mt-0.5 text-body-sm text-muted-foreground",children:"Client-side preferences. Server policy (auth, cwd roots, API-key requirements) is configured where the worker runs."})]}),g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Appearance"})}),g.jsxs(Rs,{className:"flex items-center justify-between",children:[g.jsx("span",{className:"text-body-sm text-fg-2",children:"Theme"}),g.jsx(xR,{})]})]}),g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Defaults"})}),g.jsxs(Rs,{className:"flex flex-col gap-3",children:[g.jsx(aw,{kind:"session",label:"New session"}),g.jsx(aw,{kind:"job",label:"Queue job"}),g.jsx("p",{className:"text-label text-fg-4",children:'Pre-fills the permission mode and model on the new-session and schedule-job forms (still editable per run). "Default (recommended)" leaves the model to the CLI.'})]})]}),g.jsxs(As,{children:[g.jsx(_s,{children:g.jsx(Ns,{children:"Worker server"})}),g.jsxs(Rs,{className:"flex flex-col gap-1 text-body-sm text-fg-2",children:[g.jsxs("div",{children:["Endpoint: ",g.jsxs("code",{className:"font-mono text-code",children:[location.origin,"/v1"]})," (dev proxy → ",g.jsx("code",{className:"font-mono text-code",children:"WORKER_URL"}),", default"," ",g.jsx("code",{className:"font-mono text-code",children:"http://127.0.0.1:8787"}),")"]}),g.jsx("div",{className:"text-label text-fg-4",children:"Anthropic credentials are resolved by the SDK from the server operator’s environment — this app never handles them."})]})]})]})})}const fa=wI({component:gZ}),UZ=no({getParentRoute:()=>fa,path:"/",beforeLoad:()=>{throw Ew({to:"/sessions"})}}),zZ=no({getParentRoute:()=>fa,path:"/sessions",component:jZ}),FZ=no({getParentRoute:()=>fa,path:"/sessions/$sessionId",component:PZ}),VZ=no({getParentRoute:()=>fa,path:"/jobs",component:NZ}),$Z=no({getParentRoute:()=>fa,path:"/profiles",component:MZ}),qZ=no({getParentRoute:()=>fa,path:"/profiles/$profileName",component:DZ}),YZ=no({getParentRoute:()=>fa,path:"/settings",component:HZ}),GZ=jI({routeTree:fa.addChildren([UZ,zZ,FZ,VZ,$Z,qZ,YZ]),history:V4()});function XZ(){return g.jsxs(g.Fragment,{children:[g.jsx(zI,{router:GZ}),g.jsx(z7,{})]})}uw();const _R=document.getElementById("root");if(!_R)throw new Error("Root element #root not found");KO.createRoot(_R).render(g.jsx(S.StrictMode,{children:g.jsx(XZ,{})}));const KZ=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:gR},Symbol.toStringTag,{value:"Module"}));export{HQ as A,ZZ as L,Hr as R,hc as _,g as j,S as r};
package/dist/index.html CHANGED
@@ -18,7 +18,7 @@
18
18
  }
19
19
  })()
20
20
  </script>
21
- <script type="module" crossorigin src="/assets/index-p6gzNhpM.js"></script>
21
+ <script type="module" crossorigin src="/assets/index-DylL4Hn2.js"></script>
22
22
  <link rel="stylesheet" crossorigin href="/assets/index-B-6d1dTe.css">
23
23
  </head>
24
24
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workerdeck/web",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "The WorkerDeck dashboard as prebuilt static files: session list, create/resume flow, live panel, jobs, profiles, settings. Ships dist/ plus the path to it — serve it from the same origin as the gateway. Zero runtime dependencies.",
6
6
  "license": "MIT",
@@ -35,10 +35,10 @@
35
35
  "rimraf": "^6.1.3",
36
36
  "tailwindcss": "^4.3.1",
37
37
  "vite": "^6.3.0",
38
- "@workerdeck/protocol": "0.6.0",
39
- "@workerdeck/react": "0.6.0",
40
- "@workerdeck/ui": "0.6.0",
41
- "@workerdeck/client": "0.6.0"
38
+ "@workerdeck/protocol": "0.7.0",
39
+ "@workerdeck/client": "0.7.0",
40
+ "@workerdeck/ui": "0.7.0",
41
+ "@workerdeck/react": "0.7.0"
42
42
  },
43
43
  "author": "Tobias Strebitzer",
44
44
  "repository": {