forge-cw 0.1.11 → 0.1.13

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.
@@ -0,0 +1,31 @@
1
+ var Fr=Object.defineProperty;var Br=(e,n,a)=>n in e?Fr(e,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[n]=a;var Xn=(e,n,a)=>Br(e,typeof n!="symbol"?n+"":n,a);import{jsxs as i,jsx as t,Fragment as J}from"preact/jsx-runtime";import{Fragment as _r,Component as Kr,render as Ur}from"preact";import{useState as b,useMemo as ee,useEffect as F,useRef as oe,useCallback as V}from"preact/hooks";import{signal as Y,computed as $a}from"@preact/signals";import{ToastContainer as Hr,Tabs as se,UsageMeter as za,ToggleSwitch as Mn,showToast as A,ActionButton as E,ForgeTerminal as qr,Drawer as xt,EmptyState as je,Modal as He,Badge as Ta}from"@forge-dev/ui";import{createPortal as Gr}from"preact/compat";import{definePanel as Vr,ModuleRequestError as Bt}from"@forge-dev/sdk";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function a(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=a(o);fetch(o.href,l)}})();const Ra="forge-theme",Jr=()=>{try{return localStorage.getItem(Ra)==="light"?"light":"dark"}catch{return"dark"}},mt=Y(Jr());document.documentElement.setAttribute("data-theme",mt.value);const ja=e=>{mt.value=e,document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(Ra,e)}catch{}},ze=Y(!1),ea=()=>ja(mt.value==="dark"?"light":"dark"),Yr=({sidebar:e,children:n})=>i("div",{class:"forge-shell",style:{minHeight:"100vh",display:"grid",gridTemplateColumns:"236px minmax(0,1fr)",background:"var(--bg)",color:"var(--ink)"},children:[e,t("div",{class:`sb-scrim${ze.value?" open":""}`,onClick:()=>{ze.value=!1}}),t("div",{class:"min-w-0 flex flex-col relative",style:{minHeight:"100vh"},children:n}),t(Hr,{})]}),ta=[["--blue","--purple"],["--teal","--blue"],["--orange","--red"],["--green","--teal"]],Pa=e=>ta[e%ta.length],Z=(e,n=18)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,We={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)"},de={padding:"10px 14px",borderRadius:"12px",fontSize:"12.5px"},Qr={personal:"--blue",project:"--green",client:"--green",team:"--purple"},Be=e=>Qr[e??""]??"--ink-2",Zr={decision:"--purple",context:"--teal",playbook:"--green",memory:"--orange",instinct:"--red",rule:"--blue",skill:"--ink-2"},na=e=>Zr[e]??"--ink-3",Rt=[{id:"memory",label:"Memory",sections:["What happened","Lesson","Rule of thumb"]},{id:"decision",label:"Decision",sections:["Decision","Why","Consequences"]},{id:"playbook",label:"Playbook",sections:["When","Steps"]},{id:"instinct",label:"Instinct",sections:["When","Do","Evidence"]},{id:"rule",label:"Rule",sections:["Rule","Why"]},{id:"context",label:"Context",sections:[]}],Oe=(e,n,a)=>({label:e,glyph:n,token:a,ink:`var(${a})`,fill:Z(a)}),kn={task:Oe("Dev","D","--orange"),review:Oe("Review","R","--blue"),loop:Oe("Loop","L","--purple"),general:Oe("General","G","--green")},Xr={create:Oe("Create","C","--teal"),login:Oe("Login","A","--ink-2")},Fn=e=>kn[e]??Xr[e]??kn.task,qe=[{key:"dev",sessionType:"task"},{key:"review",sessionType:"review"},{key:"loop",sessionType:"loop"},{key:"general",sessionType:"general"}],Bn=e=>{var n;return kn[((n=qe.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"].label},eo=e=>{var n;return((n=qe.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"},_n={working:{label:"Working",token:"--green",attention:!1},waiting:{label:"Waiting for you",token:"--orange",attention:!0},permission:{label:"Needs approval",token:"--red",attention:!0},error:{label:"Stopped on an error",token:"--red",attention:!0},exited:{label:"Exited",token:"--ink-3",attention:!1},idle:{label:"Idle",token:"--ink-3",attention:!1}},_e=e=>!!(e&&(_n[e.state].attention||e.state==="exited"&&(e.exitCode??0)!==0)),_t=e=>e.state==="exited"&&e.exitCode?`Exited with code ${e.exitCode}`:_n[e.state].label,Ot=e=>e.state==="exited"&&e.exitCode?"--red":_n[e.state].token,q=e=>e.sessionDir?`${e.project}::${e.sessionDir}`:`${e.project}::${e.task??e.pr}`,ie=e=>e.project==="__general"?"":e.project,vt=e=>e.sessionDir??(e.type==="review"?`review-pr-${e.pr}`:e.type==="loop"?`loop-${e.task}`:`task-${e.task}`),pe=e=>e.type==="review"?`PR #${e.pr}`:e.type==="general"?e.task??`General (${e.account})`:e.type==="create"?`Create: ${e.task??"project"}`:e.type==="loop"?`Loop: ${e.task??"loop"}`:e.type==="login"?`Login: ${e.account} · ${ue(e.harness).label}`:e.task??"unknown",to={linear:"Linear",notion:"Notion"},Kn=e=>{var a;const n=e.source?to[e.source]:void 0;return n&&((a=e.source_url)!=null&&a.startsWith("https://"))?{label:n,url:e.source_url}:null},Jt=e=>{const n=Math.floor((Date.now()-new Date(e).getTime())/6e4);if(n<1)return"now";if(n<60)return`${n}m`;const a=Math.floor(n/60);if(a<24)return`${a}h`;const r=Math.floor(a/24);return r<30?`${r}d`:`${Math.floor(r/30)}mo`},jt=(e,n)=>({label:e,color:`var(--forge-harness-${n})`,bg:Z(`--forge-harness-${n}`)}),no={claude:jt("Claude Code","claude"),codex:jt("Codex","codex"),pi:jt("Pi","pi"),opencode:jt("OpenCode","opencode")},ue=e=>no[e??"claude"]??{label:e??"claude",color:"var(--ink-3)",bg:"var(--elev)"},Aa=e=>{const n=ue(e.harness).label;return e.provider&&e.provider!=="native"?`${n} · ${e.model||e.provider}`:n},ao=[{id:"",label:"Default",description:"Recommended model"},{id:"haiku",label:"Haiku",description:"Fast, simple tasks"},{id:"sonnet",label:"Sonnet",description:"Daily coding"},{id:"opus",label:"Opus",description:"Complex reasoning"}],Ia=(e,n,a,r)=>{var o,l;return(e?(o=a[e])==null?void 0:o.harness:void 0)??((l=r.accounts.find(c=>c.name===n))==null?void 0:l.default_harness)??"claude"},Pe=(e,n,a)=>{var r;return(r=e.accounts.find(o=>o.name===n))==null?void 0:r.harnesses.find(o=>o.harness===a)},ro=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,oo=new Intl.DateTimeFormat(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}),La=(e,n=Date.now())=>{if(!e)return null;const a=new Date(e).getTime();if(!Number.isFinite(a))return null;const r=Math.round((a-n)/6e4);if(r<=0)return"resets now";if(r<60)return`resets in ${r} m`;const o=Math.floor(r/60);if(o>=24)return`resets ${oo.format(Math.round(a/6e4)*6e4)}`;const l=r%60;return`resets in ${o} h${l?` ${l} m`:""}`},Ea=e=>e.map(n=>({label:n.label,percent:n.percent,severity:n.severity,scope:n.scope,reset:La(n.resetsAt)})),Na=Y(null);async function io(){const e=await fetch("/api/health");Na.value=(await e.json()).version??null}const it=Y(null);async function Oa(){const e=await fetch("/api/skills");if(!e.ok)throw new Error("fetch failed");it.value=await e.json()}const Se=({size:e=7,color:n,live:a,glow:r=a})=>{const o=n??(a?"var(--green)":"var(--ink-3)");return t("span",{"aria-hidden":"true",class:`shrink-0 inline-block${a?" breathe":""}`,style:{width:`${e}px`,height:`${e}px`,borderRadius:"50%",background:o,boxShadow:r?`0 0 8px ${o}`:"none"}})},nn=5,Da="forge-sidebar-collapsed",lo=()=>{try{const e=localStorage.getItem(Da);return e?JSON.parse(e):[]}catch{return[]}},so=(e,n)=>Number(n.live)-Number(e.live)||n.count-e.count||e.name.localeCompare(n.name),co=({projects:e,accounts:n,selected:a,onSelect:r,onAdd:o})=>{const[l,c]=b(""),[s,d]=b(lo),[x,g]=b([]),v=l.trim().toLowerCase(),k=ee(()=>{const y=[...n,...e.map(w=>w.account).filter(w=>!n.includes(w))];return Array.from(new Set(y)).map((w,p)=>({account:w,index:p,items:e.filter(h=>h.account===w&&(!v||h.name.toLowerCase().includes(v))).sort(so),active:e.filter(h=>h.account===w).reduce((h,m)=>h+m.count,0)})).filter(w=>w.items.length>0)},[e,n,v]),S=y=>{const w=s.includes(y)?s.filter(p=>p!==y):[...s,y];d(w);try{localStorage.setItem(Da,JSON.stringify(w))}catch{}};return i("div",{class:"flex flex-col sb-section min-h-0",style:{gap:"6px",flex:"0 1 auto",minHeight:"120px"},children:[i("div",{class:"flex items-center justify-between shrink-0",style:{padding:"0 9px"},children:[t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)",letterSpacing:".02em"},children:"Projects"}),t("button",{type:"button","aria-label":"Add project",title:"Add project (P)",class:"grid place-items-center cursor-pointer",style:{border:0,background:"none",color:"var(--blue)",padding:"0 2px"},onClick:o,children:t("span",{class:"i-lucide-plus",style:{width:"14px",height:"14px"}})})]}),i("label",{class:"relative shrink-0 block",style:{margin:"0 2px"},children:[t("span",{class:"i-lucide-search absolute pointer-events-none",style:{left:"9px",top:"8px",width:"12px",height:"12px",color:"var(--ink-3)"}}),t("input",{type:"search",class:"field","aria-label":"Filter projects",placeholder:"Filter projects",value:l,style:{height:"28px",padding:"0 8px 0 27px",borderRadius:"8px",fontSize:"12.5px",background:"var(--elev)"},onInput:y=>c(y.target.value),onKeyDown:y=>{y.key==="Escape"&&c("")}})]}),i("div",{class:"flex flex-col overflow-y-auto min-h-0",style:{gap:"8px",overscrollBehavior:"contain"},children:[k.length===0&&i("p",{style:{padding:"4px 9px",fontSize:"12px",color:"var(--ink-3)"},children:["No project matches “",l.trim(),"”."]}),k.map(y=>{const w=v!==""||!s.includes(y.account),p=v!==""||x.includes(y.account)||y.items.some((f,P)=>P>=nn&&f.name===a),h=p?y.items:y.items.slice(0,nn),[m,u]=Pa(y.index),z=y.items.some(f=>f.live);return i("div",{class:"flex flex-col shrink-0",style:{gap:"1px"},children:[i("button",{type:"button","aria-expanded":w,class:"flex items-center w-full text-left cursor-pointer transition-colors duration-160 hover:bg-elev",style:{gap:"7px",height:"26px",padding:"0 7px",borderRadius:"8px",border:0,background:"none",color:"var(--ink-2)"},onClick:()=>S(y.account),children:[t("span",{class:"i-lucide-chevron-right shrink-0",style:{width:"11px",height:"11px",color:"var(--ink-3)",transform:w?"rotate(90deg)":"none",transition:"transform .2s var(--ease)"}}),t("span",{class:"grid place-items-center shrink-0",style:{width:"16px",height:"16px",borderRadius:"5px",background:`linear-gradient(160deg, var(${m}), var(${u}))`,color:"#fff",fontSize:"9px",fontWeight:700},children:y.account.charAt(0).toUpperCase()}),t("span",{class:"flex-1 truncate",style:{fontSize:"12px",fontWeight:600},children:y.account}),z&&t(Se,{size:5,live:!0,glow:!1}),t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},title:`${y.items.length} projects · ${y.active} active tasks`,children:y.items.length})]}),w&&i("div",{class:"flex flex-col",style:{gap:"1px",marginLeft:"13px",paddingLeft:"6px",borderLeft:"1px solid var(--hair)",animation:"riseIn .24s var(--ease) both"},children:[h.map(f=>{const P=a===f.name;return i("button",{type:"button","aria-pressed":P,class:"flex items-center w-full text-left shrink-0 cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",style:{gap:"8px",height:"27px",padding:"0 8px",borderRadius:"8px",fontSize:"13px",color:"var(--ink)",border:`1px solid ${P?"var(--hair)":"transparent"}`,background:P?"var(--card)":"transparent",boxShadow:P?"var(--shadow-s)":"none"},onClick:()=>r(f.name),children:[t(Se,{size:6,live:f.live}),t("span",{class:"flex-1 truncate",style:{fontWeight:P?600:450,opacity:f.count>0||f.live||P?1:.62},children:f.name}),f.count>0&&t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:f.count})]},f.name)}),y.items.length>nn&&v===""&&t("button",{type:"button",class:"text-left cursor-pointer hover:underline",style:{padding:"3px 8px",border:0,background:"none",color:"var(--blue)",fontSize:"11.5px",fontWeight:500},onClick:()=>g(p?x.filter(f=>f!==y.account):[...x,y.account]),children:p?"Show less":`Show all ${y.items.length}`})]})]},y.account)})]})]})},Wa={context:null,tokens:null,cost:null},po=250,Kt=new Map,uo=/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g,Ye=(e,n)=>{let a=null;for(const r of e.matchAll(n))a=r;return a},an=e=>{const n=parseFloat(e),a=e.slice(-1).toLowerCase();return a==="k"?n*1e3:a==="m"?n*1e6:n};function ho(e){const n={},a=Ye(e,/(?:ctx|context)[:\s]*(\d{1,3}(?:\.\d+)?)\s*%/gi)??Ye(e,/[▓█▒░]+\s*(\d{1,3}(?:\.\d+)?)\s*%/g);a&&(n.context=Math.min(100,parseFloat(a[1])));const r=Ye(e,/(\d+(?:\.\d+)?[kKmM]?)\s*↑\s*(\d+(?:\.\d+)?[kKmM]?)\s*↓/g),o=Ye(e,/\((\d+(?:\.\d+)?[kKmM])\s*\/\s*\d+(?:\.\d+)?[kKmM]\)/g);r?n.tokens=an(r[1])+an(r[2]):o&&(n.tokens=an(o[1]));const l=Ye(e,/\$(\d+\.\d{2})\b/g);return l&&(n.cost=parseFloat(l[1])),n}const Ma=e=>{let n=Kt.get(e);return n||(n={tail:"",timer:null,metrics:Y(Wa)},Kt.set(e,n)),n},Fa=e=>Ma(e).metrics,fo=e=>{e.timer=null;const n=e.metrics.value,a={...n,...ho(e.tail)};(a.context!==n.context||a.tokens!==n.tokens||a.cost!==n.cost)&&(e.metrics.value=a)};function go(e,n){const a=Ma(e);a.tail=(a.tail+n.slice(-4e3*2).replace(uo,"")).slice(-4e3),a.timer||(a.timer=setTimeout(()=>fo(a),po))}function xo(e){const n=Kt.get(e);n&&(n.timer&&clearTimeout(n.timer),n.metrics.value=Wa,Kt.delete(e))}const Ba=e=>e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e),_a=e=>`$${e.toFixed(2)}`,dt=Y(null),mo=6e4;let Qe=null,Ze=null,rn=0;function aa(e=!1){return Qe||(Qe=fetch(`/api/cw/usage${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(dt.value=n,Qe=null,n)),Qe)}function Ka(){return rn+=1,aa(),Ze||(Ze=setInterval(()=>{document.visibilityState==="visible"&&aa()},mo)),()=>{rn-=1,rn===0&&Ze&&(clearInterval(Ze),Ze=null)}}const vo=(e,n)=>{var a;return((a=dt.value)!=null&&a.available?dt.value.usage.find(r=>r.account===e&&r.harness===n):null)??null},Ae=Y({}),ra=Y(null),Ua=2e3,yo=15e3;let Xe=null,Ha=0,on=!1;const Dt=new Set,bo=(e,n)=>!!e&&_e(n)&&(e.state!==n.state||e.since!==n.since);async function qa(){if(!on){on=!0,Ha=Date.now();try{const e=await fetch("/api/cw/session-states");if(!e.ok)return;const{states:n}=await e.json(),a=Ae.value;Ae.value=n;for(const[r,o]of Object.entries(n))if(bo(a[r],o))for(const l of Dt)l(r,o)}catch{}finally{on=!1}}}const ko=()=>{const e=document.visibilityState==="visible"?Ua:yo;Date.now()-Ha>=e-100&&qa()};function wo(e){return Dt.add(e),Xe||(qa(),Xe=setInterval(ko,Ua)),()=>{Dt.delete(e),Dt.size===0&&Xe&&(clearInterval(Xe),Xe=null)}}const Ga="forge.notify-sessions",Yt=typeof window<"u"&&"Notification"in window,So=()=>{try{return Yt&&Notification.permission==="granted"&&localStorage.getItem(Ga)==="1"}catch{return!1}},Un=Y(So());async function Co(e){if(e&&(!Yt||(Notification.permission==="default"?await Notification.requestPermission():Notification.permission)!=="granted"))return!1;Un.value=e;try{localStorage.setItem(Ga,e?"1":"0")}catch{}return!0}function oa(e,n,a,r){if(!Un.value||!Yt||Notification.permission!=="granted")return;const o=new Notification(e,{body:n,tag:a});o.onclick=()=>{window.focus(),r(),o.close()}}const $e=Y([]),$o=1e4;let et=null,ln=0;async function pt(){try{const e=await fetch("/api/modules");e.ok&&($e.value=await e.json())}catch{}}const ia=()=>{pt()};function zo(){return ln++,et||(pt(),et=setInterval(()=>{pt()},$o),window.addEventListener("focus",ia)),()=>{ln--,ln===0&&et&&(clearInterval(et),et=null,window.removeEventListener("focus",ia))}}const Va=e=>e.filter(n=>n.state!=="legacy"&&(n.view||n.state==="disabled")),Ja=e=>e.lastDenial?`Denied ${e.lastDenial.permission}: ${e.lastDenial.value}`:e.lastJobError??e.lastEventError??null,ut=Y([]),Ya=$a(()=>{var n;const e={};for(const a of ut.value){const r=e[n=a.moduleId]??(e[n]={badge:0,attention:0});a.kind==="badge"?r.badge+=a.count??0:a.seen||r.attention++}return e}),Qa=5e3,To=15e3;let tt=null,Za=0,la=!1,sn=!1;const Wt=new Set,sa=e=>`${e.moduleId}\0${e.key}\0${e.createdAt}`;async function Xa(){if(!sn){sn=!0,Za=Date.now();try{const e=await fetch("/api/modules/notifications");if(!e.ok)return;const{items:n}=await e.json(),a=new Set(ut.value.map(sa));if(ut.value=n,la){for(const r of n)if(r.kind==="attention"&&!r.seen&&!a.has(sa(r)))for(const o of Wt)o(r)}la=!0}catch{}finally{sn=!1}}}const Ro=()=>{const e=document.visibilityState==="visible"?Qa:To;Date.now()-Za>=e-100&&Xa()};function jo(e){return Wt.add(e),tt||(Xa(),tt=setInterval(Ro,Qa)),()=>{Wt.delete(e),Wt.size===0&&tt&&(clearInterval(tt),tt=null)}}async function Po(e){ut.value=ut.value.map(n=>n.moduleId===e?{...n,seen:!0}:n),await fetch(`/api/modules/${encodeURIComponent(e)}/notifications/seen`,{method:"POST"}).catch(()=>{})}const er=[{view:"list",label:"Tasks",glyph:"T",token:"--blue"},{view:"accounts",label:"Accounts",glyph:"A",token:"--purple"},{view:"skills",label:"Skills",glyph:"S",token:"--green"},{view:"prototypes",label:"Prototypes",glyph:"P",token:"--orange"},{view:"qa",label:"QA",glyph:"Q",token:"--teal"},{view:"memory",label:"Memory",glyph:"M",token:"--red"}],tr="flex items-center w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",nr=e=>({borderRadius:"9px",border:`1px solid ${e?"var(--hair)":"transparent"}`,background:e?"var(--card)":"transparent",boxShadow:e?"var(--shadow-s)":"none",color:"var(--ink)"}),ar="flex flex-col text-left cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m",wn={gap:"6px",padding:"9px 10px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",color:"var(--ink)"},Sn={fontSize:"10.5px",color:"var(--ink-3)"},Cn=({children:e})=>t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)",letterSpacing:".02em"},children:e}),Ao=({id:e,session:n,index:a,onOpen:r})=>{const o=Fa(e).value,l=Ae.value[e],c=_e(l),s=n.type==="loop",d=(o==null?void 0:o.context)??null,[x,g]=a%2===0?["var(--blue)","var(--purple)"]:["var(--purple)","var(--blue)"],v=c?_t(l):s?n.loop_interval?`every ${n.loop_interval}`:"self-paced":o&&(o.tokens!==null||o.cost!==null)?[o.tokens!==null?`${Ba(o.tokens)} tokens`:null,o.cost!==null?_a(o.cost):null].filter(Boolean).join(" · "):ie(n)||n.account;return i("button",{type:"button",class:ar,style:c?{...wn,borderColor:`var(${Ot(l)})`}:wn,onClick:r,title:l?_t(l):void 0,children:[i("span",{class:"flex items-center w-full",style:{gap:"6px"},children:[t(Se,{size:6,color:l?`var(${Ot(l)})`:x,live:!l||l.state==="working"||c}),t("span",{class:"truncate",style:{fontSize:"12.5px",fontWeight:600},children:pe(n)}),t("span",{class:"flex-1"}),t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-2)"},children:d!==null?`${Math.round(d)}%`:"—"})]}),i("span",{class:"relative block w-full overflow-hidden",style:{height:"5px",borderRadius:"99px",background:"var(--elev)"},children:[t("span",{class:"block h-full",style:{width:`${d??0}%`,borderRadius:"99px",background:`linear-gradient(90deg, ${x}, ${g})`,transition:"width .6s var(--ease)"}}),t("span",{class:"absolute inset-y-0 left-0",style:{width:"30%",background:"linear-gradient(90deg, transparent, rgba(255,255,255,.22), transparent)",animation:"sweep 2.6s ease-in-out infinite"}})]}),t("span",{class:"mono truncate w-full",style:c?{...Sn,color:`var(${Ot(l)})`,fontWeight:600}:Sn,children:v})]})},Io=({view:e,onNavigate:n})=>{const a=Va($e.value);if(a.length===0)return null;const r=Ya.value;return i("nav",{class:"flex flex-col sb-section",style:{gap:"2px"},"aria-label":"Modules",children:[t("span",{style:{padding:"0 9px 4px"},children:t(Cn,{children:"Modules"})}),a.map(o=>{const l=`module:${o.id}`,c=e===l,s=o.state!=="enabled",d=s?null:Ja(o),x=r[o.id],g=o.color??"var(--ink-3)";return i("button",{type:"button","aria-current":c?"page":void 0,title:s?`${o.displayName} is disabled: ${o.reason??""}`:d??o.displayName,class:tr,style:{...nr(c),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:c?600:450,opacity:s?.5:1},onClick:()=>n(l),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"18px",height:"18px",borderRadius:"5px",fontSize:"10px",fontWeight:600,background:c?`color-mix(in srgb, ${g} 18%, transparent)`:"var(--elev)",color:c?g:"var(--ink-3)"},children:o.displayName.charAt(0).toUpperCase()}),t("span",{class:"flex-1 sb-label truncate",children:o.displayName}),d&&t("span",{class:"sb-label","aria-label":"Has a warning",style:{width:"6px",height:"6px",borderRadius:"50%",background:"var(--orange)"}}),x&&x.attention>0&&t("span",{class:"mono sb-label","aria-label":`${x.attention} need you`,style:{fontSize:"10.5px",fontWeight:700,padding:"0 6px",borderRadius:"99px",color:"#fff",background:"var(--red)"},children:x.attention}),x&&x.badge>0&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:x.badge})]},`${o.id}-${o.source}`)})]})},Lo=()=>i("label",{class:"flex items-center justify-between",style:{gap:"8px",padding:"0 9px",fontSize:"12px",color:"var(--ink-2)"},children:[t("span",{class:"sb-label",children:"Notify me when a session or module needs me"}),t(Mn,{checked:Un.value,label:"Notify me when a session or module needs me",onChange:e=>{Co(e).then(n=>{n||A("The browser blocked notifications for Forge","error")})}})]}),Eo=({account:e,harness:n,windows:a,stale:r,onOpen:o})=>{const l=a.reduce((s,d)=>d.percent>s.percent?d:s),c=ue(n).label;return i("button",{type:"button",class:ar,style:wn,onClick:o,title:`Usage limits for ${e} on ${c}`,children:[i("span",{class:"flex items-center w-full",style:{gap:"6px"},children:[t("span",{class:"truncate",style:{fontSize:"12.5px",fontWeight:600},children:e}),t("span",{class:"flex-1"}),t("span",{class:"mono truncate",style:{fontSize:"10px",color:"var(--ink-3)"},children:c})]}),t(za,{bars:Ea(a),size:"sm"}),t("span",{class:"mono truncate w-full",style:Sn,children:r?"last known values":La(l.resetsAt)})]})},No=({view:e,counts:n,projects:a,accounts:r,selectedProject:o,live:l,onNavigate:c,onSelectProject:s,onAddProject:d,onOpenLive:x,onSearch:g})=>{var w;const v=Na.value,k=er.map(p=>{var h;return{...p,count:p.view==="skills"?((h=it.value)==null?void 0:h.length)??null:n[p.view]??null}});F(()=>Ka(),[]),F(()=>{io().catch(()=>{})},[]);const S=[...l].sort((p,h)=>Number(_e(Ae.value[h.key]))-Number(_e(Ae.value[p.key]))),y=(w=dt.value)!=null&&w.available?dt.value.usage.filter(p=>p.state==="ok"&&p.windows.some(h=>!h.scope)):[];return i("aside",{class:`forge-sidebar flex flex-col${ze.value?" open":""}`,"aria-label":"Sidebar",style:{position:"sticky",top:0,height:"100vh",overflowY:"auto",overscrollBehavior:"contain",gap:"18px",padding:"14px 10px 12px",background:"var(--bg-2)",borderRight:"1px solid var(--hair)"},children:[i("div",{role:"button",tabIndex:0,class:"flex items-center cursor-pointer",style:{gap:"9px",padding:"2px 8px"},onClick:()=>c("list"),onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&c("list")},children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"22px",height:"22px",borderRadius:"7px",background:"linear-gradient(160deg, var(--blue), var(--purple))",boxShadow:"var(--shadow-s)",fontSize:"12px",fontWeight:700,color:"#fff"},children:"F"}),t("span",{class:"sb-label",style:{fontSize:"15px",fontWeight:600,letterSpacing:"-0.015em"},children:"Forge"}),t("span",{class:"flex-1 sb-label"}),v&&t("span",{class:"mono sb-label",style:{fontSize:"10px",color:"var(--ink-3)"},title:"Forge version",children:v})]}),g&&i("button",{type:"button",class:"flex items-center text-left cursor-pointer transition-all duration-180 ease-spring text-ink2 hover:text-ink hover:border-hair2 hover:-translate-y-px hover:shadow-m",style:{gap:"8px",padding:"6px 9px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",fontSize:"12.5px",boxShadow:"var(--shadow-s)"},onClick:g,"aria-label":"Search (⌘K)",children:[t("span",{class:"i-lucide-search shrink-0",style:{width:"13px",height:"13px",opacity:.7}}),t("span",{class:"flex-1 sb-label",children:"Search"}),t("kbd",{class:"sb-label",style:{fontSize:"10px",padding:"1px 5px",borderRadius:"5px",background:"var(--elev)",border:"1px solid var(--hair)"},children:"⌘K"})]}),t("nav",{class:"flex flex-col",style:{gap:"2px"},"aria-label":"Sections",children:k.map(p=>{const h=e===p.view;return i("button",{type:"button","aria-current":h?"page":void 0,title:p.label,class:tr,style:{...nr(h),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:h?600:450},onClick:()=>c(p.view),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"18px",height:"18px",borderRadius:"5px",fontSize:"10px",fontWeight:600,background:h?Z(p.token):"var(--elev)",color:h?`var(${p.token})`:"var(--ink-3)"},children:p.glyph}),t("span",{class:"flex-1 sb-label",children:p.label}),p.count!==null&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:p.count})]},p.view)})}),t(Io,{view:e,onNavigate:c}),t(co,{projects:a,accounts:r,selected:o,onSelect:s,onAdd:d}),i("div",{class:"flex flex-col",style:{marginTop:"auto",flex:"none",gap:"8px"},children:[l.length>0&&i("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Cn,{children:"Live now"})}),S.map((p,h)=>t(Ao,{id:p.key,session:p.session,index:h,onOpen:()=>x(p.session)},p.key))]}),y.length>0&&i("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Cn,{children:"Limits"})}),y.map(p=>t(Eo,{account:p.account,harness:p.harness,windows:p.windows.filter(h=>!h.scope),stale:p.stale,onOpen:()=>c("accounts")},`${p.account}/${p.harness}`))]}),Yt&&t("div",{class:"sb-section",children:t(Lo,{})}),t("div",{class:"sb-section",children:t(se,{fill:!0,size:"xs",label:"Appearance",tabs:[{id:"light",label:"Light"},{id:"dark",label:"Dark"}],active:mt.value,onChange:p=>ja(p==="light"?"light":"dark")})})]})]})};function yt(){const e=oe(null);return F(()=>{var n;(n=e.current)==null||n.focus()},[]),e}const ca=(e,n,a)=>{const r=Fn(e.type);return{id:q(e),label:ie(e)?`${pe(e)} · ${ie(e)}`:pe(e),hint:n,glyph:r.glyph,token:r.token,run:()=>a(e)}},Oo=({openTabs:e,sessions:n,projects:a,commands:r,onOpenSession:o,onSelectProject:l,onClose:c})=>{const[s,d]=b(""),[x,g]=b(0),v=oe(null),k=yt(),S=ee(()=>{const u=s.trim().toLowerCase(),z=M=>!u||M.label.toLowerCase().includes(u),f=new Set(e.map(q)),P=e.map((M,T)=>ca(M,T<5?`⌘${T+1}`:"open",o)),I=n.filter(M=>M.status==="active"&&!f.has(q(M))).map(M=>ca(M,"resume",o)),N=u?a.map(M=>({id:`project:${M}`,label:M,hint:"project",glyph:"P",token:"--green",run:()=>l(M)})):[];return[{name:"Live now",items:P.filter(z)},{name:"Tasks",items:I.filter(z).slice(0,u?12:6)},{name:"Projects",items:N.filter(z).slice(0,6)},{name:"Commands",items:r.filter(z)}].filter(M=>M.items.length>0)},[s,e,n,a,r,o,l]),y=S.flatMap(u=>u.items),w=Math.min(x,y.length-1);F(()=>{var u,z;(z=(u=v.current)==null?void 0:u.querySelector('[data-active="true"]'))==null||z.scrollIntoView({block:"nearest"})},[w]);const p=u=>{u&&(c(),u.run())},h=oe({flat:y,current:w,activate:p});h.current={flat:y,current:w,activate:p},F(()=>{const u=z=>{const{flat:f,current:P,activate:I}=h.current,N=f.length;z.key==="ArrowDown"?(z.preventDefault(),g(M=>N?(Math.min(M,N-1)+1)%N:0)):z.key==="ArrowUp"?(z.preventDefault(),g(M=>N?(Math.min(M,N-1)-1+N)%N:0)):z.key==="Enter"?(z.preventDefault(),I(f[P])):z.key==="Escape"&&(z.preventDefault(),c())};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[c]);let m=-1;return t("div",{class:"fixed inset-0 z-[60] flex justify-center items-start overflow-auto",style:{background:"rgba(0,0,0,.42)",backdropFilter:"blur(6px)",WebkitBackdropFilter:"blur(6px)",padding:"88px 16px 16px"},onClick:c,children:i("div",{role:"dialog","aria-modal":"true","aria-label":"Command palette",class:"flex flex-col overflow-hidden",style:{width:"min(560px, 100%)",maxHeight:"calc(100vh - 104px)",borderRadius:"18px",background:"var(--glass)",backdropFilter:"blur(30px) saturate(180%)",WebkitBackdropFilter:"blur(30px) saturate(180%)",border:"1px solid var(--hair-2)",boxShadow:"var(--shadow-l)",animation:"popIn .26s var(--ease) both"},onClick:u=>u.stopPropagation(),children:[t("input",{ref:k,role:"combobox","aria-expanded":"true","aria-controls":"palette-list","aria-activedescendant":y[w]?`palette-${y[w].id}`:void 0,"aria-label":"Search tasks, projects and commands",class:"shrink-0",style:{height:"48px",padding:"0 16px",border:0,borderBottom:"1px solid var(--hair)",background:"transparent",color:"var(--ink)",fontSize:"16px",outline:"none"},placeholder:"Task, project, skill or command…",value:s,onInput:u=>{d(u.target.value),g(0)}}),i("div",{id:"palette-list",role:"listbox",ref:v,class:"overflow-auto",style:{padding:"6px"},children:[y.length===0&&i("p",{style:{padding:"14px 10px",fontSize:"13px",color:"var(--ink-2)"},children:["Nothing matches “",s,"”."]}),S.map(u=>i("div",{role:"group","aria-label":u.name,children:[t("div",{style:{padding:"7px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:u.name}),u.items.map(z=>{m+=1;const f=m,P=f===w;return i("button",{id:`palette-${z.id}`,type:"button",role:"option","aria-selected":P,"data-active":P,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"10px",padding:"8px 10px",borderRadius:"10px",border:0,background:P?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px",transition:"background .14s"},onMouseMove:()=>{P||g(f)},onClick:()=>p(z),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"22px",height:"22px",borderRadius:"7px",fontSize:"10px",fontWeight:700,background:z.token?Z(z.token):"var(--elev)",color:z.token?`var(${z.token})`:"var(--ink-2)"},children:z.glyph}),t("span",{class:"flex-1 min-w-0 truncate",children:z.label}),t("span",{class:"mono shrink-0",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:z.hint})]},z.id)})]},u.name))]}),t("div",{class:"flex shrink-0",style:{gap:"14px",padding:"8px 14px",borderTop:"1px solid var(--hair)"},children:["↑↓ move","↵ open","esc close"].map(u=>t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:u},u))})]})})},Qt=Y(null),Do=3e3;let nt=null;function ge(e=!1){return nt||(nt=fetch(`/api/cw/harnesses${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(Qt.value=n,nt=null,n)),nt)}const ht=new Set;let lt=null;const rr=()=>{ht.size===0&&lt&&(clearInterval(lt),lt=null)},Wo=async()=>{const e=await ge(!0),n=Date.now();for(const a of ht){const r=e.available&&a.check(e.doctor);(r||n>a.deadline)&&(ht.delete(a),a.onDone(r))}rr()};function Mo(e,{timeoutMs:n=6e5,onDone:a=()=>{}}={}){const r={check:e,deadline:Date.now()+n,onDone:a};return ht.add(r),lt||(lt=setInterval(Wo,Do)),()=>{ht.delete(r),rr()}}const Me=(e,n,a)=>{var r;return!!(e!=null&&e.available&&((r=e.capabilities[n])!=null&&r.includes(a)))},or=e=>/linear\.app/.test(e)?"linear":/notion\.(so|site)/.test(e)?"notion":null,ir=(e,n,a)=>{const r=or(a);return!!(e!=null&&e.available&&r&&!Me(e,n,"mcp")&&!e.contextTokens[r])},$n=Y(null);let cn=null;function lr(){return cn||(cn=fetch("/api/cw/editors").then(e=>e.json()).then(e=>{$n.value=e}).catch(()=>{$n.value={enabled:!1,editors:[]}})),cn}async function Fo(e,n){const a=await fetch("/api/cw/open-in-editor",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:e.project,sessionDir:vt(e),editor:n})}),r=await a.json().catch(()=>({ok:!1,error:`HTTP ${a.status}`}));if(!a.ok||!r.ok)throw new Error(r.error??"Could not open the editor")}const ft=e=>e.unpushed??e.commits??0,sr={OPEN:"open",MERGED:"merged",CLOSED:"closed"},Bo={passing:"✓",failing:"✗",pending:"…",none:""};function _o(e){if(e.workspace==="missing")return"Workspace not created yet";if(e.closeWarnings.includes("state-unknown")&&e.branch===null)return"Changes unknown";const n=[];e.diff&&e.diff.files>0&&n.push(`+${e.diff.insertions} −${e.diff.deletions} · ${e.diff.files} file${e.diff.files===1?"":"s"}`),e.uncommitted>0&&n.push(`${e.uncommitted} uncommitted`);const a=ft(e);if(a>0&&n.push(`${a} unpushed`),e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":sr[e.pr.state];n.push(`PR #${e.pr.number} ${r}`),e.pr.checks!=="none"&&n.push(`checks ${Bo[e.pr.checks]}`),e.pr.review==="APPROVED"&&n.push("approved"),e.pr.review==="CHANGES_REQUESTED"&&n.push("changes requested")}return n.length>0?n.join(" · "):e.workspace==="ready"?"No changes yet":""}const Ko={passing:"checks pass",failing:"checks failing",pending:"checks running",none:""},da=(e,n)=>`${e} ${n}${e===1?"":"s"}`;function Uo(e){if(e.workspace==="missing")return"not created yet";if(e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":sr[e.pr.state];return[`PR #${e.pr.number} ${r}`,Ko[e.pr.checks]].filter(Boolean).join(" · ")}const n=[];e.diff&&e.diff.files>0&&n.push(da(e.diff.files,"file")),e.commits&&n.push(da(e.commits,"commit"));const a=ft(e);return a>0&&e.commits&&n.push(`${a} unpushed`),e.uncommitted>0&&n.push(`${e.uncommitted} uncommitted`),n.length>0?n.join(" · "):"no changes yet"}async function ke(e,n){const a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),r=await a.json().catch(()=>({}));if(!a.ok||r.error)throw new Error(r.error??`Request failed (${a.status})`);return r}const we=e=>e instanceof Error?e.message:String(e);function Hn(e,n){navigator.clipboard.writeText(e).then(()=>A(`${n} copied`,"info"),()=>A(`Could not copy the ${n.toLowerCase()}`,"error"))}const Ho=({session:e,muted:n})=>{const a=ue(e.harness);return i("span",{class:`harness-pill inline-flex items-center shrink-0 whitespace-nowrap${n?" opacity-60":""}`,style:{gap:"6px",padding:"3px 9px",borderRadius:"99px",background:a.bg,color:a.color,fontSize:"11.5px",fontWeight:600},children:[t("span",{style:{width:"6px",height:"6px",borderRadius:"50%",background:a.color}}),Aa(e)]})},xe=Y(null),qo=6e4;let at=null,rt=null,dn=0;function Te(e=!1){return at&&!e||(at=fetch(`/api/kioku/status${e?"?fresh=1":""}`).then(n=>n.json()).then(n=>{JSON.stringify(n)!==JSON.stringify(xe.value)&&(xe.value=n)}).catch(()=>{xe.value??(xe.value={installed:!1,version:null,brains:[],projects:{},activity:[],viewer:null})}).finally(()=>{at=null})),at}function cr(){return dn+=1,xe.value||Te(),rt||(rt=setInterval(()=>{document.visibilityState==="visible"&&Te()},qo)),()=>{dn-=1,dn===0&&rt&&(clearInterval(rt),rt=null)}}const ae=e=>e.name??e.key,Ut=e=>e.reduce((n,a)=>n+a.pages,0);function qn(e){const n=xe.value;return n!=null&&n.installed?(n.projects[e]??[]).flatMap(a=>n.brains.find(r=>ae(r)===a.name)??[]):[]}function dr(e){return F(()=>cr(),[]),qn(e)}const Go=({project:e})=>{const[n,a]=b(null),r=dr(e);return r.length===0?null:i("span",{class:"inline-flex items-center shrink-0 whitespace-nowrap",style:{gap:"6px",padding:"3px 9px",borderRadius:"99px",background:"var(--elev)",border:"1px solid var(--hair)",color:"var(--ink-2)",fontSize:"11.5px",fontWeight:600},"aria-label":`Memory: ${r.map(ae).join(", ")}`,onMouseEnter:o=>a(o.currentTarget.getBoundingClientRect()),onMouseLeave:()=>a(null),children:[t("span",{class:"inline-flex",children:r.map((o,l)=>t("span",{style:{width:"9px",height:"9px",borderRadius:"50%",background:`var(${Be(o.tier)})`,border:"2px solid var(--card)",marginLeft:l===0?0:"-4px"}},o.key))}),t("span",{class:"mono",children:Ut(r)}),n&&Gr(i("span",{class:"flex flex-col",style:{position:"fixed",top:`${n.bottom+8}px`,right:`${window.innerWidth-n.right}px`,zIndex:50,width:"240px",gap:"6px",padding:"10px 12px",borderRadius:"12px",background:"var(--card-2)",border:"1px solid var(--hair-2)",boxShadow:"var(--shadow-l)",animation:"riseIn .2s var(--ease) both"},children:[t("span",{style:{fontSize:"10.5px",fontWeight:600,letterSpacing:".03em",color:"var(--ink-3)"},children:"THIS SESSION REMEMBERS"}),r.map(o=>i("span",{class:"flex items-center",style:{gap:"7px",fontSize:"12px",color:"var(--ink)",fontWeight:500},children:[t(Se,{color:`var(${Be(o.tier)})`}),ae(o),t("span",{style:{color:"var(--ink-3)",fontWeight:400},children:o.tier}),t("span",{class:"flex-1"}),t("span",{class:"mono",style:{color:"var(--ink-2)"},children:o.pages})]},o.key))]}),document.body)]})},zn=Y({}),pr=Y(0),Vo=6e4,Pt=new Map,ur=e=>`${e.project}::${vt(e)}`;function Tn(e,n=!1){const a=ur(e),r=Pt.get(a);if(r&&!n)return r;const o=`/api/cw/review-state/${encodeURIComponent(e.project)}/${encodeURIComponent(vt(e))}${n?"?fresh=1":""}`,l=fetch(o).then(async c=>c.ok?{state:await c.json(),error:null}:{state:null,error:`Forge could not read this task (HTTP ${c.status})`}).catch(()=>({state:null,error:"Could not reach the Forge server"})).then(c=>(zn.value={...zn.value,[a]:c},Pt.get(a)===l&&Pt.delete(a),c));return Pt.set(a,l),l}function Jo(){pr.value++}function hr(e,{poll:n=!1}={}){const a=ur(e),r=pr.value;return F(()=>{if(Tn(e),!n)return;const o=setInterval(()=>{Tn(e,!0)},Vo);return()=>clearInterval(o)},[a,n,r]),zn.value[a]??null}const Rn=({type:e,size:n=28,radius:a=9,font:r=11})=>{const o=Fn(e);return t("span",{class:"grid place-items-center shrink-0",title:o.label,style:{width:`${n}px`,height:`${n}px`,borderRadius:`${a}px`,background:o.fill,color:o.ink,fontSize:`${r}px`,fontWeight:700},children:o.glyph})},Yo=()=>i("span",{class:"inline-flex items-center shrink-0",style:{gap:"5px",padding:"1px 8px",borderRadius:"99px",background:Z("--green"),color:"var(--green)",fontSize:"11px",fontWeight:600},children:[t(Se,{size:5,color:"var(--green)",live:!0,glow:!1}),"live"]}),fr=({label:e,href:n})=>{const a={padding:"1px 7px",borderRadius:"99px",background:"var(--elev)",border:"1px solid var(--hair)",color:"var(--ink-2)",fontSize:"11px"};return n?i("a",{class:"inline-flex items-center gap-1 shrink-0 hover:text-ink",style:a,href:n,target:"_blank",rel:"noopener noreferrer",title:n,onClick:r=>r.stopPropagation(),onKeyDown:r=>r.stopPropagation(),children:[e," ",t("span",{class:"i-lucide-external-link",style:{width:"10px",height:"10px"}})]}):t("span",{class:"shrink-0",style:a,children:e})},gr=({session:e})=>{const n=Kn(e);return n&&t(fr,{label:n.label,href:n.url})},Qo=({session:e})=>Kn(e)?t(gr,{session:e}):e.source?t("span",{class:"task-chip contents",children:t(fr,{label:e.source,href:e.source_url})}):null,xr=e=>e.type==="review"?`review/pr-${e.pr}`:e.type==="loop"?`loop/${e.task??"loop"}`:e.type==="task"?`task/${e.task}`:null,Zo=({session:e,project:n})=>{var l;const a=hr(e),r=((l=a==null?void 0:a.state)==null?void 0:l.branch)??xr(e),o=a?a.error!==null?"changes unknown":Uo(a.state):"checking…";return t(mr,{branch:r,status:o,project:n})},mr=({branch:e,status:n,project:a})=>i("div",{class:"task-meta flex items-center min-w-0",style:{gap:"9px",marginTop:"2px"},children:[a&&t("span",{class:"shrink-0",style:{fontSize:"12px",fontWeight:600,color:"var(--ink-2)"},children:a}),e===null?t("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"—"}):t("button",{type:"button",class:"mono truncate min-w-0 cursor-copy hover:text-ink transition-colors duration-160",style:{fontSize:"11.5px",color:"var(--ink-3)",padding:0,border:0,background:"transparent"},title:"Copy branch name",onClick:r=>{r.stopPropagation(),Hn(e,"Branch")},onKeyDown:r=>r.stopPropagation(),children:e}),t("span",{class:"whitespace-nowrap truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:n})]}),Xo=e=>e.type==="loop"?e.loop_interval?`every ${e.loop_interval}`:"self-paced":`${e.opens} session${e.opens===1?"":"s"}`,vr=({session:e,isOpenInTab:n,onSelect:a,onMarkDone:r,showProject:o})=>{const l=o?ie(e)||"no project":void 0,[c,s]=b(!1),d=e.type==="task"||e.type==="review",x=async()=>{if(!(!r||c)){s(!0);try{await r()}finally{s(!1)}}};return i("div",{class:"task-row group flex items-center cursor-pointer transition-colors duration-160 hover:bg-elev",style:{gap:"13px",padding:"11px 15px",borderBottom:"1px solid var(--hair)"},onClick:a,role:"button",tabIndex:0,"aria-label":`${n?"Open":"Resume"} ${pe(e)}`,onKeyDown:g=>{g.target===g.currentTarget&&(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),a())},children:[t(Rn,{type:e.type}),i("div",{class:"flex-1 min-w-0",children:[i("div",{class:"flex items-center min-w-0",style:{gap:"8px"},children:[t("span",{class:"truncate",style:{fontSize:"14px",fontWeight:600},children:pe(e)}),n&&e.status==="active"&&t(Yo,{}),t(Qo,{session:e})]}),d?t(Zo,{session:e,project:l}):t(mr,{branch:xr(e),status:Xo(e),project:l})]}),t(Go,{project:ie(e)}),t(Ho,{session:e}),t("span",{class:"mono shrink-0 text-right",style:{width:"52px",fontSize:"11.5px",color:"var(--ink-3)"},title:new Date(e.last_opened).toLocaleString(),children:Jt(e.last_opened)}),r&&t("button",{type:"button",class:`task-done grid place-items-center shrink-0 cursor-pointer transition-all duration-180 ease-spring hover:text-green disabled:cursor-wait ${c?"":"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"}`,style:{width:"28px",height:"28px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink-2)"},onClick:g=>{g.stopPropagation(),x()},disabled:c,title:c?"Closing…":"Mark done","aria-label":"Mark done",children:t("span",{class:c?"i-lucide-loader-2 animate-spin":"i-lucide-check",style:{width:"14px",height:"14px"}})}),t("span",{class:"shrink-0 whitespace-nowrap",style:n?{padding:"5px 11px",borderRadius:"9px",background:"linear-gradient(180deg, var(--blue-2), var(--blue))",color:"#fff",fontSize:"12.5px",fontWeight:600,boxShadow:"var(--shadow-m)"}:{padding:"5px 11px",borderRadius:"9px",background:"var(--elev)",color:"var(--ink)",fontSize:"12.5px",fontWeight:600},children:n?"Open":"Resume"})]})},ei=({session:e,onSelect:n})=>i("div",{class:"flex items-center cursor-pointer transition-colors duration-160 hover:bg-elev",style:{gap:"12px",padding:"9px 15px",borderBottom:"1px solid var(--hair)",color:"var(--ink-2)"},onClick:n,role:"button",tabIndex:0,onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),n())},children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"22px",height:"22px",borderRadius:"7px",background:"var(--elev)"},children:t("span",{class:"i-lucide-check",style:{width:"12px",height:"12px"}})}),i("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px"},children:[pe(e)," ",t("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:ie(e)})]}),t(gr,{session:e}),t("span",{class:"mono shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:Jt(e.closed??e.last_opened)})]}),ti=({project:e,account:n,accounts:a,onDeleted:r,onMoved:o})=>{const[l,c]=b(null),[s,d]=b(null),[x,g]=b(!1),[v,k]=b(!1),[S,y]=b(""),[w,p]=b(!1),h=(a??[]).filter($=>$!==n);F(()=>{let $=!1;return fetch(`/api/cw/mcps?project=${encodeURIComponent(e)}`).then(B=>B.json()).catch(()=>null).then(B=>{$||c(B)}),()=>{$=!0}},[e]);const m=l?Object.keys(l.global):[],u=(l==null?void 0:l.project)??[],z=(l==null?void 0:l.cw)??[],f=(l==null?void 0:l.plugins)??[],P=[...u.map($=>`${$} (project)`),...m,...z.map($=>`${$} (CW)`)],I=$=>{d(s===$?null:$),y(""),g(!1)},N=async()=>{k(!0);try{(await(await fetch("/api/cw/delete-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:e,deleteFiles:x})})).json()).ok&&(A(`Project "${e}" deleted${x?" (files removed)":""}`,"info"),r==null||r())}catch{A("Failed to delete project","error")}finally{k(!1),d(null)}},M=async()=>{if(S){p(!0);try{const B=await(await fetch("/api/cw/move-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:e,toAccount:S})})).json();B.ok?(A(`Project "${e}" moved to "${S}"`,"success"),d(null),y(""),o==null||o()):A(B.error??"Failed to move project","error")}catch{A("Failed to move project","error")}finally{p(!1)}}};if(!l)return null;const T={padding:"12px 15px",borderTop:"1px solid var(--hair)",display:"flex",flexDirection:"column",gap:"10px"},R=($,B)=>({padding:"5px 11px",borderRadius:"9px",border:"1px solid var(--hair)",fontSize:"12.5px",fontWeight:500,background:B?"var(--elev)":"var(--card)",color:$==="red"?"var(--red)":"var(--ink)",boxShadow:"var(--shadow-s)"});return i("section",{style:{borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",overflow:"hidden"},"aria-label":"Project settings",children:[i("div",{class:"flex items-center flex-wrap",style:{padding:"10px 15px",gap:"8px 12px"},children:[i("div",{class:"flex-1 min-w-0 flex flex-col",style:{gap:"2px",fontSize:"12.5px",color:"var(--ink-2)"},children:[P.length>0&&i("span",{class:"truncate",title:P.join(", "),children:["MCP · ",P.join(", ")]}),f.length>0&&i("span",{class:"truncate",title:f.join(", "),children:["Plugins · ",f.join(", ")]}),P.length===0&&f.length===0&&t("span",{children:"No MCPs or plugins for this project"})]}),h.length>0&&t("button",{type:"button",class:"cursor-pointer",style:R("ink",s==="move"),"aria-expanded":s==="move",onClick:()=>I("move"),children:"Move to account"}),t("button",{type:"button",class:"cursor-pointer",style:R("red",s==="delete"),"aria-expanded":s==="delete",onClick:()=>I("delete"),children:"Delete project"})]}),s==="move"&&i("div",{style:T,children:[i("p",{style:{fontSize:"13px"},children:['Move "',e,'" to a different account.']}),i("select",{class:"field",value:S,onChange:$=>y($.target.value),children:[t("option",{value:"",children:"Select account…"}),h.map($=>t("option",{value:$,children:$},$))]}),i("div",{class:"flex",style:{gap:"8px"},children:[t(E,{label:w?"Moving…":"Move project",variant:"primary",size:"sm",loading:w,disabled:!S,onClick:M}),t(E,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),y("")}})]})]}),s==="delete"&&i("div",{style:T,children:[i("p",{style:{fontSize:"13px"},children:['This unregisters "',e,'" from CW.']}),i("label",{class:"flex items-center cursor-pointer",style:{gap:"8px",fontSize:"12.5px",color:"var(--ink-2)"},children:[t("input",{type:"checkbox",checked:x,onChange:$=>g($.target.checked)}),"Also delete project files from disk"]}),x&&t("p",{style:{fontSize:"12.5px",color:"var(--red)"},children:"This permanently deletes all files. It cannot be undone."}),i("div",{class:"flex",style:{gap:"8px"},children:[t(E,{label:v?"Deleting…":x?"Delete project and files":"Unregister project",variant:"destructive",size:"sm",loading:v,onClick:N}),t(E,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),g(!1)}})]})]})]})},yr=e=>e.trim().replace(/\s+/g,"-").toLowerCase();function Zt(e){const n=e.trim();return n?/github\.com\/.+\/pull\/\d+/.test(n)||/^#?\d{1,6}$/.test(n)?{kind:"pr",type:"review"}:/linear\.app/.test(n)?{kind:"linear",type:"dev"}:/notion\.(so|site)/.test(n)?{kind:"notion",type:"dev"}:{kind:"name",type:"dev",slug:yr(n)}:null}const ni="A PR link becomes a review. A Linear or Notion link becomes a dev task with its notes.";function ai(e,n){const a=Zt(e),r=n.project?` on ${n.project}`:"";if(n.type==="general")return{text:`General session as ${n.account||"an account"}${n.project?` in ${n.project}`:", outside any project"}, run by ${n.harness}.`,ready:!!n.account};if(!n.project)return{text:"Pick a project to start.",ready:!1};if(!a)return{text:ni,ready:!1};if(n.type==="loop")return{text:`Loop${r} — pick its interval in the next step.`,ready:!0};if(n.type==="review")return{text:a.kind==="pr"?`Pull request detected — this becomes a review${r}, run by ${n.harness}.`:`Review of “${e.trim()}”${r}, run by ${n.harness}.`,ready:!0};switch(a.kind){case"linear":return{text:"Linear ticket detected — a dev task, and the ticket lands in TASK_NOTES.md first.",ready:!0};case"notion":return{text:"Notion page detected — a dev task, and the page lands in TASK_NOTES.md first.",ready:!0};case"pr":return{text:`Dev task${r} from pull request ${e.trim()}, run by ${n.harness}.`,ready:!0};case"name":return{text:`Dev task${r} · branch task/${a.slug}`,ready:!0}}}const Gn=(e,n)=>{var a;return n??((a=Zt(e))==null?void 0:a.type)??"dev"},me=Y(""),Ke=Y(null),Fe=Y(""),Ht=Y(""),qt=e=>{me.value=e,Ke.value=null},Vn=(e,n,a)=>a&&e!=="claude"?"Loop uses Claude Code's /loop":(n==null?void 0:n.status)==="not_installed"?typeof n.detail=="string"&&n.detail?n.detail:"Not installed":null,ri=(e,n,a,r,o)=>{var s;if(o)return o;if((a==null?void 0:a.status)==="not_logged_in")return"Not logged in";if((a==null?void 0:a.status)==="error"&&typeof a.detail=="string")return a.detail;const l=(s=e.harnesses.find(d=>d.name===n))==null?void 0:s.version,c=a==null?void 0:a.model;return[r?"Default":l,c].filter(Boolean).join(" · ")||(r?"Default":"")},oi=({doctor:e,account:n,value:a,defaultHarness:r,isLoop:o,onChange:l,onOpenAccounts:c})=>i("div",{class:"flex flex-col",style:{gap:"6px"},role:"radiogroup","aria-label":"Harness",children:[t("span",{style:{fontSize:"12px",color:"var(--ink-2)"},children:"Harness · this task only"}),t("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:"8px"},children:e.harnesses.map(s=>{const d=Pe(e,n,s.name),x=Vn(s.name,d,o),g=ue(s.name),v=a===s.name,k=(d==null?void 0:d.status)==="not_logged_in",S=ri(e,s.name,d,s.name===r,x);return i("div",{role:"radio","aria-checked":v,tabIndex:x?-1:0,"aria-disabled":!!x,title:x??void 0,class:`flex items-start transition-all duration-180 ease-spring ${x?"cursor-not-allowed":"cursor-pointer hover:bg-elev"}`,style:{gap:"9px",padding:"10px 11px",borderRadius:"12px",border:`1px solid ${v?"var(--blue)":"var(--hair)"}`,background:v?Z("--blue"):"var(--card)",boxShadow:v?"var(--shadow-s)":"none",opacity:x?.45:1},onClick:()=>{x||l(s.name)},onKeyDown:y=>{!x&&(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),l(s.name))},children:[t("span",{class:"shrink-0",style:{width:"8px",height:"8px",borderRadius:"50%",marginTop:"5px",background:g.color,boxShadow:v?`0 0 8px ${g.color}`:"none"}}),i("span",{class:"flex flex-col min-w-0",children:[t("span",{style:{fontSize:"12.5px",fontWeight:600},children:g.label}),t("span",{class:"truncate",style:{fontSize:"11.5px",color:"var(--ink-2)"},title:S,children:S}),k&&c&&t("button",{type:"button",class:"self-start cursor-pointer",style:{border:0,background:"none",padding:0,color:"var(--blue)",fontSize:"11.5px",fontWeight:600},onClick:y=>{y.stopPropagation(),c()},onKeyDown:y=>y.stopPropagation(),children:"Connect"})]})]},s.name)})})]}),ii=({options:e,value:n,label:a,onPick:r,onClose:o})=>{const[l,c]=b(""),[s,d]=b(0),x=yt(),g=oe(null),v=l.trim().toLowerCase(),k=ee(()=>e.filter(w=>{var p;return!v||w.label.toLowerCase().includes(v)||((p=w.group)==null?void 0:p.toLowerCase().includes(v))}),[e,v]);F(()=>{const w=k.findIndex(p=>p.value===n);d(w>=0&&!v?w:0)},[v]),F(()=>{var w,p;(p=(w=g.current)==null?void 0:w.querySelector('[data-active="true"]'))==null||p.scrollIntoView({block:"nearest"})},[s]);const S=w=>{if(w.key==="ArrowDown")w.preventDefault(),d(p=>Math.min(p+1,k.length-1));else if(w.key==="ArrowUp")w.preventDefault(),d(p=>Math.max(p-1,0));else if(w.key==="Enter"){w.preventDefault();const p=k[s];p&&r(p.value)}else w.key==="Escape"&&(w.preventDefault(),w.stopPropagation(),o())};let y;return i("div",{class:"popover absolute right-0 top-full z-40 flex flex-col",style:{marginTop:"6px",width:"260px",maxHeight:"320px",padding:"6px",borderRadius:"12px",background:"var(--card-2)",backdropFilter:"none",WebkitBackdropFilter:"none"},onKeyDown:S,children:[i("label",{class:"relative block shrink-0",children:[t("span",{class:"i-lucide-search absolute pointer-events-none",style:{left:"9px",top:"9px",width:"12px",height:"12px",color:"var(--ink-3)"}}),t("input",{ref:x,type:"search",class:"field",role:"combobox","aria-expanded":"true","aria-label":`Search ${a.toLowerCase()}`,placeholder:`Search ${a.toLowerCase()}s`,value:l,style:{height:"30px",padding:"0 8px 0 27px",borderRadius:"8px",fontSize:"12.5px",background:"var(--elev)"},onInput:w=>c(w.target.value)})]}),i("div",{ref:g,role:"listbox","aria-label":a,class:"overflow-y-auto min-h-0",style:{marginTop:"6px"},children:[k.length===0&&i("p",{style:{padding:"8px 10px",fontSize:"12.5px",color:"var(--ink-3)"},children:["No match for “",l.trim(),"”."]}),k.map((w,p)=>{const h=w.group&&w.group!==y?w.group:null;y=w.group;const m=p===s,u=w.value===n;return i("div",{children:[h&&t("div",{style:{padding:"7px 9px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:h}),i("button",{type:"button",role:"option","aria-selected":u,"data-active":m,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"8px",padding:"6px 9px",borderRadius:"8px",border:0,background:m?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px"},onMouseMove:()=>{m||d(p)},onClick:()=>r(w.value),children:[t("span",{class:"flex-1 truncate",style:{fontWeight:u?600:400,color:w.value?"var(--ink)":"var(--ink-2)"},children:w.label}),u&&t("span",{class:"i-lucide-check shrink-0",style:{width:"13px",height:"13px",color:"var(--blue)"}})]})]},w.value||"__empty")})]})]})},br=({label:e,value:n,options:a,onChange:r,placeholder:o="Choose…",size:l="sm",width:c})=>{const[s,d]=b(!1),x=oe(null),g=a.find(k=>k.value===n);return F(()=>{if(!s)return;const k=S=>{x.current&&!x.current.contains(S.target)&&d(!1)};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[s]),i("div",{ref:x,class:"relative",style:{width:c},children:[i("button",{type:"button","aria-haspopup":"listbox","aria-expanded":s,"aria-label":e,class:"field flex items-center text-left cursor-pointer",style:l==="sm"?{width:c??"auto",minWidth:"130px",maxWidth:"200px",height:"30px",padding:"0 9px 0 10px",borderRadius:"9px",fontSize:"12.5px",background:"var(--bg-2)",gap:"6px"}:{gap:"6px",boxShadow:"var(--shadow-s)"},onClick:()=>d(k=>!k),onKeyDown:k=>{k.key==="ArrowDown"&&(k.preventDefault(),d(!0))},children:[t("span",{class:"flex-1 truncate",style:{color:g&&g.value?"var(--ink)":"var(--ink-2)"},children:(g==null?void 0:g.label)??o}),t("span",{class:"i-lucide-chevrons-up-down shrink-0",style:{width:"12px",height:"12px",color:"var(--ink-3)"}})]}),s&&t(ii,{options:a,value:n,label:e,onPick:k=>{r(k),d(!1)},onClose:()=>d(!1)})]})},jn=(e,n,a=Object.keys(e))=>{const r=o=>{const l=n.indexOf(o);return l<0?n.length:l};return[...a].sort((o,l)=>r(e[o].account)-r(e[l].account)||o.localeCompare(l)).map(o=>({value:o,label:o,group:e[o].account}))},kr=({ctx:e,size:n="md"})=>{const{text:a,ready:r}=ai(me.value,{...e,harness:ue(e.harness).label}),o=r&&(e.type==="general"||Zt(me.value)!==null);return i("p",{class:"flex items-center min-w-0","aria-live":"polite",style:{gap:"7px",fontSize:n==="md"?"12.5px":"12px",color:o?"var(--blue)":"var(--ink-3)"},children:[o&&t("span",{class:"grid place-items-center shrink-0",style:{width:"16px",height:"16px",borderRadius:"50%",background:Z("--blue",22)},children:t("span",{class:"i-lucide-check",style:{width:"10px",height:"10px"}})}),t("span",{class:"min-w-0",style:{overflowWrap:"anywhere"},children:a})]})},wr=({fill:e})=>t(se,{fill:e,label:"Task type",tabs:qe.map(n=>({id:n.key,label:Bn(n.key)})),active:Gn(me.value,Ke.value),onChange:n=>{Ke.value=n}}),li={width:"auto",maxWidth:"180px",height:"30px",padding:"0 26px 0 10px",borderRadius:"9px",fontSize:"12.5px",background:"var(--bg-2)"},si=({label:e,value:n,onChange:a,options:r})=>i("label",{class:"inline-flex items-center shrink-0",style:{gap:"6px",fontSize:"12px",color:"var(--ink-3)"},children:[e,t("select",{class:"field","aria-label":e,style:li,value:n,onChange:o=>a(o.target.value),children:r.map(o=>t("option",{value:o.value,children:o.label},o.value))})]}),ci=({projects:e,accounts:n,onStarted:a,onOpenDrawer:r})=>{var u,z;const[o,l]=b(!1),c=Qt.value,s=c!=null&&c.available?c.doctor:null,d=Gn(me.value,Ke.value),x=d==="general",g=Fe.value,v=Object.keys(e).sort(),k=x?Ht.value||((u=e[g])==null?void 0:u.account)||n[0]||"":((z=e[g])==null?void 0:z.account)??"",S=v.filter(f=>e[f].account===k),y=d==="loop"?"claude":s?Ia(g||void 0,k,e,s):"claude",w=me.value.trim(),p=o||(x?!k:!w||!g),h=async()=>{if(p)return;const f=s?Pe(s,k,y):void 0,P=s?Vn(y,f,d==="loop"):null,I=!x&&ir(c,y,w);if(d==="loop"||P||I||(f==null?void 0:f.status)==="not_logged_in"){r();return}l(!0);try{const T=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x?{type:d,account:k,project:g||void 0,harness:s?y:void 0}:{type:d,project:g,task:w,account:k||void 0,harness:s?y:void 0})})).json();T.ok?(A(x?"Session started":d==="review"?"Review started":"Task started","success"),x||qt(""),a(T.session)):A(T.error??"Failed to start","error")}catch{A("Failed to start","error")}finally{l(!1)}},m=f=>{var P;Ht.value=f,g&&((P=e[g])==null?void 0:P.account)!==f&&(Fe.value="")};return i("section",{style:{position:"relative",zIndex:5,padding:"14px",borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",animation:"riseIn .34s var(--ease) both"},"aria-label":"Start a task",children:[i("div",{class:"flex items-center flex-wrap",style:{gap:"9px"},children:[t("input",{class:"field min-w-0",style:{flex:"1 1 300px",height:"40px",padding:"0 13px",borderRadius:"11px",background:"var(--bg-2)",fontSize:"14.5px"},placeholder:x?"A general session needs no name — pick the account below":"Paste a Linear ticket, a PR link, or type a task name","aria-label":"Task name, ticket or pull request",value:me.value,onInput:f=>qt(f.target.value),onKeyDown:f=>{f.key==="Enter"&&h()}}),t(wr,{}),t("button",{type:"button",disabled:p,class:p?"":"cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:brightness-106",style:{height:"40px",padding:"0 18px",borderRadius:"11px",border:0,fontSize:"13.5px",fontWeight:600,background:p&&!o?"var(--elev)":"linear-gradient(180deg, var(--blue-2), var(--blue))",color:p&&!o?"var(--ink-3)":"#fff",boxShadow:p&&!o?"none":"var(--shadow-m)",opacity:p&&!o?.8:1,cursor:p?"not-allowed":"pointer"},onClick:()=>void h(),children:o?"Starting…":x?"Launch":"Start"})]}),i("div",{class:"flex items-center flex-wrap",style:{gap:"8px 14px",marginTop:"10px",padding:"0 2px"},children:[t("div",{class:"flex-1 min-w-0",style:{flexBasis:"280px"},children:t(kr,{ctx:{type:d,project:g,account:k,harness:y}})}),x&&t(si,{label:"Account",value:k,onChange:m,options:n.map(f=>({value:f,label:f}))}),i("div",{class:"inline-flex items-center shrink-0",style:{gap:"6px",fontSize:"12px",color:"var(--ink-3)"},children:[t("span",{"aria-hidden":"true",children:"Project"}),t(br,{label:"Project",value:g,onChange:f=>{Fe.value=f},placeholder:x?"No project":"Choose…",options:x?[{value:"",label:"No project"},...jn(e,n,S)]:jn(e,n,v)})]})]})]})},Ge=({title:e,subtitle:n,leading:a,children:r,sticky:o=!0,size:l="lg"})=>i("header",{class:`glass flex items-center flex-wrap shrink-0 ${o?"sticky top-0 z-20":""}`,style:{gap:"12px 14px",padding:"12px 22px",borderBottom:"1px solid var(--hair)"},children:[t(Jn,{}),a,i("div",{class:"min-w-0",children:[t("h1",{class:"truncate",style:{fontSize:l==="lg"?"20px":"18px",fontWeight:700,letterSpacing:"-0.02em"},children:e}),n&&t("p",{class:"truncate",style:{marginTop:"1px",fontSize:"12.5px",color:"var(--ink-2)"},children:n})]}),t("span",{style:{flex:"1 1 40px"}}),r&&t("div",{class:"flex items-center flex-wrap",style:{gap:"7px"},children:r})]}),di=({label:e="Tasks",onClick:n})=>i("button",{type:"button",class:"inline-flex items-center gap-1 shrink-0 whitespace-nowrap cursor-pointer transition-all duration-180 ease-spring text-ink2 hover:text-ink",style:{padding:"5px 10px",borderRadius:"8px",border:"1px solid var(--hair)",background:"var(--card)",fontSize:"12.5px"},onClick:n,children:[t("span",{"aria-hidden":"true",children:"←"})," ",e]}),Jn=()=>t("button",{type:"button",class:"sb-toggle place-items-center shrink-0 cursor-pointer text-ink2 hover:text-ink",style:{width:"30px",height:"30px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",boxShadow:"var(--shadow-s)"},"aria-label":"Open sidebar",onClick:()=>{ze.value=!0},children:t("span",{class:"i-lucide-menu",style:{width:"15px",height:"15px"}})}),Pn=Y({}),pa=new Set;function pi(e){!e||pa.has(e)||(pa.add(e),fetch(`/api/cw/detect/${encodeURIComponent(e)}`).then(n=>n.ok?n.json():null).catch(()=>null).then(n=>{Pn.value={...Pn.value,[e]:n}}))}const Sr=e=>{if(!e)return[];const n=[];return e.framework&&n.push(e.framework),e.testRunner&&n.push(e.testRunner),e.hasTailwind&&n.push("Tailwind"),e.hasShadcn&&n.push("shadcn"),e.hasPlaywright&&n.push("Playwright"),e.hasDockerfile&&n.push("Docker"),n};function Cr(e){return F(()=>{pi(e)},[e]),Pn.value[e]}const ua=10,$r="forge-task-layout",ui=()=>{try{return localStorage.getItem($r)==="project"?"project":"recent"}catch{return"recent"}},Mt={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",overflow:"hidden"},Ft={padding:"11px 15px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},hi=({project:e,account:n,sessions:a,index:r,openTabKeys:o,onSelectTask:l,onMarkDone:c})=>{const s=Sr(Cr(e)),d=a.some(x=>o.has(q(x)));return i("section",{style:{...Mt,animation:`riseIn .4s var(--ease) ${r*70}ms both`},"aria-label":e||"No project",children:[i("div",{class:"flex items-center flex-wrap",style:{...Ft,gap:"10px"},children:[t(Se,{size:9,live:d}),t("span",{style:{fontSize:"14px",fontWeight:650,letterSpacing:"-0.01em"},children:e||"No project"}),t("span",{class:"truncate",style:{fontSize:"12.5px",color:"var(--ink-2)"},children:[n,s.join(" · ")].filter(Boolean).join(" · ")}),t("span",{class:"flex-1"}),i("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[a.length," task",a.length===1?"":"s"]})]}),a.map(x=>t(vr,{session:x,isOpenInTab:o.has(q(x)),onSelect:()=>l(x),onMarkDone:x.type==="login"?void 0:()=>c(x)},q(x)))]})},fi=({spaces:e,allSpaces:n,projects:a,accountNames:r,filterAccount:o,filterProject:l,onFilterProject:c,filterType:s,onFilterType:d,harnessNames:x,filterHarness:g,onFilterHarness:v,showDone:k,onShowDone:S,openTabKeys:y,onSelectTask:w,onMarkDone:p,onNewTask:h,onCreateProject:m,onRefresh:u,onStarted:z})=>{var H,ce;const[f,P]=b(ui),I=L=>{P(L);try{localStorage.setItem($r,L)}catch{}},N=ee(()=>e.filter(L=>L.status==="active"),[e]),M=ee(()=>e.filter(L=>L.status==="done"),[e]),T=ee(()=>n.filter(L=>L.status==="active").length,[n]),R=ee(()=>n.filter(L=>L.status==="done").length,[n]),$=ee(()=>n.filter(L=>L.status==="active"&&y.has(q(L))).length,[n,y]),B=ee(()=>n.filter(L=>L.status==="active"&&(!o||L.account===o)&&(!l||L.project===l)&&(!g||(L.harness??"claude")===g)),[n,o,l,g]),j=ee(()=>{const L=new Map;for(const Q of N){const te=ie(Q),ve=L.get(te)??[];ve.push(Q),L.set(te,ve)}return Array.from(L,([Q,te])=>({project:Q,sessions:te}))},[N]),D=l?((H=a[l])==null?void 0:H.account)??((ce=N[0])==null?void 0:ce.account):void 0,W=l?`${D?`${D} · `:""}${B.length} active`:`${T} active · ${R} done · ${$} agent${$===1?"":"s"} working`;return i(J,{children:[i(Ge,{title:l??"Tasks",subtitle:W,children:[t(E,{label:"Add project",variant:"secondary",onClick:m}),t(E,{label:"New task",variant:"primary",onClick:h})]}),i("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"16px",maxWidth:"1180px"},children:[t(ci,{projects:a,accounts:r,onStarted:z,onOpenDrawer:h}),i("div",{class:"flex items-center flex-wrap",style:{gap:"12px"},children:[t(se,{label:"Filter by type",tabs:[{id:"all",label:"All",count:B.length},...qe.map(L=>({id:L.key,label:Bn(L.key),count:B.filter(Q=>Q.type===L.sessionType).length}))],active:s??"all",onChange:L=>d(L==="all"?null:L)}),x.length>1&&t(se,{label:"Filter by harness",tabs:[{id:"all",label:"Any harness"},...x.map(L=>({id:L,label:ue(L).label}))],active:g??"all",onChange:L=>v(L==="all"?null:L)}),t("span",{class:"flex-1"}),!l&&t(se,{size:"sm",label:"Order tasks",tabs:[{id:"recent",label:"Recent"},{id:"project",label:"By project"}],active:f,onChange:L=>I(L==="project"?"project":"recent")}),t("button",{type:"button","aria-pressed":k,class:"cursor-pointer transition-all duration-180 ease-spring",style:{padding:"6px 12px",borderRadius:"9px",border:"1px solid var(--hair)",background:k?"var(--card)":"transparent",color:k?"var(--ink)":"var(--ink-2)",fontSize:"12.5px",fontWeight:500,boxShadow:k?"var(--shadow-s)":"none"},onClick:()=>S(!k),children:k?"Hide done":"Show done"})]}),l&&t(ti,{project:l,account:D,accounts:r,onDeleted:()=>{c(null),u()},onMoved:u}),f==="recent"&&!l&&N.length>0&&i("section",{style:{...Mt,animation:"riseIn .4s var(--ease) both"},"aria-label":"Recently opened",children:[i("div",{class:"flex items-center",style:{...Ft,gap:"10px"},children:[t("span",{class:"i-lucide-clock shrink-0",style:{width:"14px",height:"14px",color:"var(--ink-2)"}}),t("span",{style:{fontSize:"14px",fontWeight:650,letterSpacing:"-0.01em"},children:"Recently opened"}),t("span",{class:"flex-1"}),i("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[N.length," task",N.length===1?"":"s"]})]}),N.map(L=>t(vr,{session:L,showProject:!0,isOpenInTab:y.has(q(L)),onSelect:()=>w(L),onMarkDone:L.type==="login"?void 0:()=>p(L)},q(L)))]}),(f==="project"||l)&&j.map((L,Q)=>{var te;return t(hi,{project:L.project,account:((te=a[L.project])==null?void 0:te.account)??L.sessions[0].account,sessions:L.sessions,index:Q,openTabKeys:y,onSelectTask:w,onMarkDone:p},L.project)}),j.length===0&&i("section",{style:{...Mt,animation:"riseIn .4s var(--ease) both"},children:[l&&i("div",{class:"flex items-center",style:{...Ft,gap:"10px"},children:[t(Se,{size:9}),t("span",{style:{fontSize:"14px",fontWeight:650,letterSpacing:"-0.01em"},children:l})]}),i("div",{class:"flex flex-col items-center text-center",style:{padding:"28px 16px",gap:"12px"},children:[t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:s||g?"No active tasks match these filters.":l?`No active tasks on ${l}.`:"No active tasks. Start something new."}),t(E,{label:"New task",variant:"primary",onClick:h})]})]}),k&&M.length>0&&i("section",{style:{...Mt,boxShadow:"var(--shadow-s)"},"aria-label":"Done",children:[i("div",{style:{...Ft,padding:"10px 15px",fontSize:"13px",fontWeight:600,color:"var(--ink-2)"},children:["Done · last ",Math.min(ua,M.length)," of ",M.length]}),M.slice(0,ua).map(L=>t(ei,{session:L,onSelect:()=>w(L)},q(L)))]})]})]})},Ie={padding:"6px 12px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink)",fontSize:"12.5px",fontWeight:500,boxShadow:"var(--shadow-s)",whiteSpace:"nowrap"},Ue="inline-flex items-center gap-1 cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m hover:text-ink",zr={...Ie,color:"var(--ink-3)",boxShadow:"none"},Tr=({href:e,title:n,children:a})=>i("a",{class:Ue,style:Ie,href:e,target:"_blank",rel:"noopener noreferrer",title:n,children:[a," ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),gi=({entry:e})=>{var a;const n=(a=e==null?void 0:e.state)==null?void 0:a.github;if(!n||n.url===null){const r=e?e.error??(n==null?void 0:n.reason)??"This task has no GitHub remote":"Checking the repository…";return i("button",{type:"button",class:"inline-flex items-center gap-1 cursor-not-allowed",style:zr,disabled:!0,title:r,children:["GitHub ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]})}return t(Tr,{href:n.url,title:n.label,children:"GitHub"})},xi=({session:e})=>{const n=Kn(e);return n&&t(Tr,{href:n.url,title:n.url,children:n.label})},mi=({session:e,entry:n})=>{var x;const[a,r]=b(!1),o=oe(null);F(()=>{lr()},[]),F(()=>{if(!a)return;const g=v=>{o.current&&!o.current.contains(v.target)&&r(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a]);const l=$n.value,c=l!=null&&l.enabled?l.editors:[];if(c.length===0)return null;const s=(x=n==null?void 0:n.state)==null?void 0:x.workspace;if(s!=="ready")return i("button",{type:"button",class:"cursor-not-allowed",style:zr,disabled:!0,title:n?s==="missing"?"Workspace not created yet":"This session has no worktree":"Checking the worktree…",children:["Open in ",c.length===1?c[0].label:"editor"]});const d=async g=>{r(!1);try{await Fo(e,g)}catch(v){A(v.message,"error")}};return c.length===1?i("button",{type:"button",class:Ue,style:Ie,onClick:()=>d(c[0].id),children:["Open in ",c[0].label]}):i("div",{class:"relative",ref:o,children:[i("button",{type:"button",class:Ue,style:Ie,"aria-expanded":a,onClick:()=>r(g=>!g),children:["Open in editor ",t("span",{class:"i-lucide-chevron-down",style:{width:"12px",height:"12px"}})]}),a&&t("div",{class:"popover absolute right-0 top-full z-30 flex flex-col",style:{marginTop:"6px",minWidth:"160px",padding:"5px",borderRadius:"12px"},children:c.map(g=>t("button",{type:"button",class:"text-left cursor-pointer hover:bg-elev",style:{padding:"7px 10px",borderRadius:"8px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>d(g.id),children:g.label},g.id))})]})},vi={"--orange":"--red","--blue":"--purple","--purple":"--blue","--green":"--teal"},ot=({label:e,index:n,color:a="var(--ink)",bar:r,title:o,children:l})=>i("div",{class:"min-w-0",title:o,style:{padding:"10px 12px",borderRadius:"13px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",animation:`riseIn .34s var(--ease) ${n*60}ms both`},children:[t("div",{style:{fontSize:"11.5px",color:"var(--ink-2)"},children:e}),t("div",{class:"mono truncate",style:{fontSize:"19px",fontWeight:650,color:a,marginTop:"2px"},children:l}),r!==void 0&&t("div",{style:{height:"5px",borderRadius:"99px",background:"var(--elev)",marginTop:"7px",overflow:"hidden"},children:t("div",{style:{height:"100%",width:`${r??0}%`,borderRadius:"99px",background:"linear-gradient(90deg, var(--blue), var(--purple))",transition:"width .6s var(--ease)"}})})]}),yi=({value:e,onChange:n,onSend:a,onCancel:r})=>{const o=yt();return i("form",{class:"flex items-center",style:{gap:"6px",marginTop:"6px"},onSubmit:l=>{l.preventDefault(),a()},children:[t("input",{ref:o,type:"text",class:"field flex-1",style:{height:"28px",fontSize:"12.5px"},value:e,maxLength:500,placeholder:"Payments retry at most three times",onInput:l=>n(l.target.value),onKeyDown:l=>{l.key==="Escape"&&r()}}),t(E,{label:"Send",variant:"primary",size:"sm",disabled:!e.trim(),onClick:a})]})},bi=({session:e,onOpen:n})=>{const a=ie(e),r=dr(a),[o,l]=b(null);if(r.length===0)return null;const c=e.harness==="claude"&&e.status==="active",s=async()=>{if(o!=null&&o.trim())try{await ke("/api/kioku/remember",{project:a,sessionDir:vt(e),text:o}),A("Sent to the agent to remember","success"),l(null)}catch(d){A(we(d),"error")}};return i("div",{class:"min-w-0",style:{gridColumn:"span 2",padding:"10px 12px",borderRadius:"13px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",animation:"riseIn .34s var(--ease) 360ms both"},children:[i("div",{class:"flex items-center",style:{fontSize:"11.5px",color:"var(--ink-2)"},children:["Memory · ",Ut(r)," pages",t("span",{class:"flex-1"}),c&&o===null&&t("button",{type:"button",class:"cursor-pointer hover:text-ink",style:{border:0,background:"none",padding:0,fontSize:"11.5px",fontWeight:600,color:"var(--blue)"},onClick:()=>l(""),children:"Remember…"})]}),o!==null&&t(yi,{value:o,onChange:l,onSend:s,onCancel:()=>l(null)}),t("div",{class:"flex items-center flex-wrap",style:{gap:"4px",marginTop:"6px"},children:r.map((d,x)=>i("span",{class:"inline-flex items-center",style:{gap:"4px"},children:[x>0&&t("span",{style:{color:"var(--ink-3)",fontSize:"11px"},children:"→"}),t("button",{type:"button",class:"cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px",style:{padding:"2px 9px",borderRadius:"99px",fontSize:"12px",fontWeight:600,border:0,background:Z(Be(d.tier)),color:`var(${Be(d.tier)})`},title:`${d.tier??"brain"} · ${d.pages} pages`,onClick:()=>n==null?void 0:n(a),children:ae(d)})]},d.key))})]})},pn=({title:e,items:n,tone:a,empty:r})=>i("div",{style:{padding:"11px 13px",borderRadius:"13px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)"},children:[t("div",{style:{fontSize:"11.5px",fontWeight:600,color:"var(--ink-2)",marginBottom:"5px"},children:e}),i("div",{class:"flex flex-wrap",style:{gap:"5px"},children:[n.length===0&&t("span",{style:{fontSize:"12px",color:"var(--ink-3)"},children:r}),n.map(o=>t("span",{title:o.title,style:{padding:"2px 8px",borderRadius:"99px",fontSize:"11px",fontWeight:500,background:a&&!o.muted?Z(a):"var(--elev)",color:a&&!o.muted?`var(${a})`:"var(--ink-2)",opacity:o.muted?.6:1},children:o.name},o.name))]})]}),ki=({session:e,active:n,onDone:a,onOpenMemory:r})=>{const[o,l]=b(""),[c,s]=b(!1),[d,x]=b(!1),[g,v]=b(0),[k,S]=b(null),[y,w]=b(!1),p=q(e),h=vt(e),m=e.type==="task"||e.type==="review",u=hr(e,{poll:n&&e.type==="task"}),z=Fn(e.type),f=e.type==="login",P=Sr(Cr(f?"":ie(e))),I=Fa(p).value,N=encodeURIComponent(e.project),M=encodeURIComponent(h),R=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal/${N}/${M}?k=${g}`;F(()=>{if(f)return;let L=!1;return Promise.all([fetch(`/api/cw/tools?project=${N}`).then(Q=>Q.json()).catch(()=>null),fetch(`/api/cw/git/branch/${N}/${M}`).then(Q=>Q.json()).catch(()=>null)]).then(([Q,te])=>{L||(Q&&S(Q),l((te==null?void 0:te.branch)||e.task||e.pr||""))}),()=>{L=!0}},[p]);const $=()=>{s(!1),v(L=>L+1)},B=(k==null?void 0:k.mcps)??[],j=(k==null?void 0:k.plugins)??[],D=(u==null?void 0:u.state)??null,W=(D==null?void 0:D.branch)??o,H=u?u.error!==null?"Changes unknown":_o(u.state):"Checking changes…",ce=[ie(e)||"no project",e.account,[Aa(e),e.provider&&e.provider!=="native"?null:e.model].filter(Boolean).join(", "),`${e.opens} session${e.opens===1?"":"s"}`].filter(Boolean).join(" · ");return i("div",{class:"flex flex-col h-full min-w-0",children:[i("div",{class:"flex flex-col shrink-0",style:{padding:"14px 20px",gap:"12px"},children:[i("div",{class:"flex items-center flex-wrap",style:{gap:"12px"},children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"34px",height:"34px",borderRadius:"11px",background:`linear-gradient(160deg, var(${z.token}), var(${vi[z.token]??z.token}))`,boxShadow:"var(--shadow-m)",color:"#fff",fontSize:"13px",fontWeight:700},"aria-hidden":"true",children:z.glyph}),i("div",{class:"min-w-0",children:[t("h1",{class:"truncate",style:{fontSize:"19px",fontWeight:700,letterSpacing:"-0.02em"},children:pe(e)}),t("p",{class:"truncate",style:{marginTop:"1px",fontSize:"12.5px",color:"var(--ink-2)"},children:ce}),!f&&t("p",{class:"mono truncate",style:{marginTop:"2px",fontSize:"11.5px",color:"var(--ink-3)"},title:H,children:H})]}),t("span",{style:{flex:"1 1 60px"}}),i("div",{class:"flex flex-wrap items-center",style:{gap:"7px"},children:[!f&&t("button",{type:"button",class:Ue,style:Ie,"aria-expanded":y,onClick:()=>w(L=>!L),children:y?"Hide context":`Context · ${B.length} MCP, ${j.length} plugins`}),!f&&t(xi,{session:e}),!f&&t(gi,{entry:u}),!f&&t(mi,{session:e,entry:u}),c&&t(E,{label:"Restart",variant:"secondary",size:"sm",onClick:$}),e.status==="active"&&!f&&t(E,{label:"Mark done",variant:"primary",size:"sm",onClick:a})]})]}),!f&&i("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(138px, 1fr))",gap:"9px"},children:[t(ot,{index:0,label:"Context used",color:"var(--blue)",bar:(I==null?void 0:I.context)??null,title:"Read from the harness status line",children:(I==null?void 0:I.context)!=null?`${Math.round(I.context)}%`:"—"}),t(ot,{index:1,label:"Tokens",children:(I==null?void 0:I.tokens)!=null?Ba(I.tokens):"—"}),t(ot,{index:2,label:"Cost",color:"var(--green)",children:(I==null?void 0:I.cost)!=null?_a(I.cost):"—"}),m&&t(ot,{index:3,label:"Commits",children:(D==null?void 0:D.commits)??"—"}),m&&t(ot,{index:4,label:"Unpushed",color:D&&ft(D)>0?"var(--orange)":"var(--ink)",children:D?ft(D):"—"}),t(bi,{session:e,onOpen:r}),W&&i("button",{type:"button",class:"text-left cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m min-w-0",style:{padding:"10px 12px",borderRadius:"13px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",color:"var(--ink)",animation:"riseIn .34s var(--ease) 300ms both"},title:"Copy branch name",onClick:()=>Hn(W,"Branch"),children:[i("div",{class:"flex items-center",style:{gap:"4px",fontSize:"11.5px",color:"var(--ink-2)"},children:["Branch ",t("span",{class:"i-lucide-copy",style:{width:"11px",height:"11px"}})]}),t("div",{class:"mono truncate",style:{fontSize:"13px",fontWeight:600,marginTop:"6px"},children:W})]})]}),y&&i("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:"9px",animation:"riseIn .3s var(--ease) both"},children:[t(pn,{title:`MCP · ${B.length}`,tone:"--blue",empty:"No MCP servers",items:B.map(L=>({name:L.name,title:`${L.type} · ${L.source}`}))}),t(pn,{title:`Plugins · ${j.length}`,tone:"--green",empty:"No plugins",items:j.map(L=>({name:L.name,muted:!L.enabled,title:`${L.enabled?"enabled":"disabled"} · ${L.marketplace}${L.hasMcp?` · MCP ${L.mcpName??""}`:""}`}))}),t(pn,{title:"Stack",tone:null,empty:"Nothing detected",items:P.map(L=>({name:L}))})]})]}),t("div",{class:"task-terminal relative flex-1 min-h-0",style:{margin:"0 20px 20px",borderRadius:"14px",overflow:"hidden",background:"var(--term)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-l)"},children:i("div",{class:"absolute inset-0 flex flex-col",children:[i("div",{class:"flex items-center shrink-0",style:{gap:"7px",padding:"8px 12px",borderBottom:"1px solid rgba(255,255,255,.08)"},children:[t("span",{style:{width:"11px",height:"11px",borderRadius:"50%",background:"#ff5f57"}}),t("span",{style:{width:"11px",height:"11px",borderRadius:"50%",background:"#febc2e"}}),t("span",{style:{width:"11px",height:"11px",borderRadius:"50%",background:"#28c840"}}),i("span",{class:"mono truncate",style:{fontSize:"11px",color:"#8a8a92",marginLeft:"6px"},children:[W||pe(e)," — ",e.harness??"claude"]}),t("span",{class:"flex-1"}),t("span",{class:"mono",style:{fontSize:"11px",color:d?"#30d158":"#8a8a92"},children:d?"connected":c?"exited":"offline"})]}),i("div",{class:"relative flex-1 min-h-0",style:{padding:"12px 6px 6px 14px"},children:[t(qr,{wsUrl:R,theme:mt.value,focused:n,onOutput:L=>go(p,L),onExit:()=>s(!0),onGiveUp:()=>s(!0),onConnectionChange:x}),!d&&!c&&t("div",{class:"absolute inset-0 grid place-items-center pointer-events-none",style:{background:"rgba(0,0,0,.35)"},children:t("span",{style:{fontSize:"13px",color:"rgba(255,255,255,.7)"},children:"Connecting…"})})]})]})})]})},Ce={fontSize:"12px",color:"var(--ink-2)"},re=e=>e.target.value,U=({label:e,plain:n,children:a})=>i(n?"div":"label",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:Ce,children:e}),a]}),wi={dev:"New dev task",review:"Review a pull request",loop:"New loop",general:"New session"},Si={dev:"A worktree session that ends in a pull request. Paste a Linear or Notion link and the ticket lands in TASK_NOTES.md first.",review:"Opens a pull request in a review worktree and walks the agent through the diff.",loop:"A recurring Claude Code /loop on one project — babysit PRs, fix failing tests, work a backlog.",general:"A plain agent session on an account, optionally inside a project. No worktree."},Ci={dev:"Task name or ticket URL",review:"Pull request number or URL",loop:"Loop prompt",general:""},$i={dev:"fix-auth or https://linear.app/…",review:"42 or https://github.com/…/pull/42",loop:"Babysit my open PRs…",general:""},zi=[{id:"",label:"Auto"},{id:"feature",label:"feature"},{id:"bugfix",label:"bugfix"},{id:"refactor",label:"refactor"}],un={boxShadow:"var(--shadow-s)"},At=e=>/^[\w./:#-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Ti=({projects:e,accounts:n,initialAccount:a,initialProject:r,onClose:o,onCreated:l,onOpenAccounts:c})=>{var Tt;const s=Gn(me.value,Ke.value),[d,x]=b(""),[g,v]=b(""),[k,S]=b(""),[y,w]=b(""),[p,h]=b(""),[m,u]=b(!1),[z,f]=b(!1),[P,I]=b(""),[N,M]=b("claude"),T=yt();F(()=>{ge()},[]);const R=Qt.value,$=R!=null&&R.available?R.doctor:null,B=Object.keys(e),j=s==="general",D=s==="review",W=s==="loop",H=me.value,ce=!P.trim()||/^\d+[smh]$/.test(P.trim()),L=n.length>0?n:Array.from(new Set(Object.values(e).map(_=>_.account).filter(Boolean))).sort(),Q=d?B.filter(_=>{var C;return((C=e[_])==null?void 0:C.account)===d}):B;F(()=>{const _=r&&!a&&e[r]?e[r].account:void 0,C=a??_,O=C&&L.includes(C)?C:L[0]??"";x(O);const K=O?B.filter(ne=>{var X;return((X=e[ne])==null?void 0:X.account)===O}):B,G=r&&K.includes(r)?r:!j&&K.length>0?K[0]:"";G&&v(G)},[]);const te=oe(!1);F(()=>{if(!te.current){te.current=!0;return}!j&&!g&&Q.length>0&&v(Q[0])},[j]);const ve=_=>{x(_);const C=B.filter(O=>{var K;return((K=e[O])==null?void 0:K.account)===_});!j&&C.length>0&&!C.includes(g)?v(C[0]):j&&g&&!C.includes(g)&&v("")},kt=$?Ia(g||void 0,d,e,$):"claude";F(()=>{!$||!d||M(W?"claude":kt)},[R==null?void 0:R.available,d,g,W]);const ye=$?Pe($,d,N):void 0,wt=!$||Me(R,N,"skip_permissions"),be=!$||N==="claude",Ee=be||!j,he=$?Vn(N,ye,W):null,St=ue(N).label;F(()=>{wt||u(!1),h(be?"":(ye==null?void 0:ye.model)??"")},[N]),F(()=>{be||h((ye==null?void 0:ye.model)??"")},[d]);const Ct=or(H),Ve=ir(R,N,H),$t=!j&&!H.trim()||W&&!ce||!j&&!g||!!he,zt=async()=>{if(!$t){f(!0);try{const _={type:s,account:d||void 0,skipPermissions:m||void 0};$&&(_.harness=N),W?(_.project=g,_.loopPrompt=H.trim(),_.loopInterval=P.trim()||void 0):j?g&&(_.project=g):(_.project=g,_.task=H.trim(),_.description=k.trim()||void 0,_.workflow=y||void 0),_.model=Ee&&p||void 0;const O=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)})).json();O.ok?(A(j?"Session started":W?"Loop started":"Task started","success"),j||qt(""),l(O.session)):A(O.error??"Failed to start","error")}catch{A("Failed to start","error")}finally{f(!1)}}},en=d||L[0]||"default",tn=j?`cw launch ${At(en)}`:W?`cw loop ${g||"<project>"} ${At(H.trim()||"<prompt>")}${P.trim()?` --every ${P.trim()}`:""}`:D?`cw review ${g||"<project>"} ${At(H.trim()||"<pr>")}`:`cw work ${g||"<project>"} ${H.trim()?At(((Tt=Zt(H))==null?void 0:Tt.kind)==="name"?yr(H):H.trim()):"<task>"}`;return i(xt,{title:wi[s],onClose:o,children:[t(wr,{fill:!0}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",lineHeight:1.5},children:Si[s]}),!j&&i("div",{class:"flex flex-col",style:{gap:"5px"},children:[t(U,{label:Ci[s],children:t("input",{class:"field",style:{...un,fontSize:"14px"},placeholder:$i[s],value:H,ref:T,onInput:_=>{const C=_.target.value;W?me.value=C:qt(C)},onKeyDown:_=>{_.key==="Enter"&&zt()}})}),!W&&t(kr,{ctx:{type:s,project:g,account:d,harness:N},size:"sm"})]}),i("div",{class:"grid",style:{gridTemplateColumns:"1fr 1fr",gap:"10px"},children:[t(U,{label:"Account",children:t("select",{class:"field",value:d,onChange:_=>{const C=_.target.value;ve(C),Ht.value=C},children:L.map(_=>t("option",{value:_,children:_},_))})}),t(U,{plain:!0,label:j?"Project · optional":"Project",children:t(br,{label:"Project",size:"md",width:"100%",value:g,placeholder:j?"No project":"Choose…",onChange:_=>{v(_),Fe.value=_},options:[...j?[{value:"",label:"No project"}]:[],...jn(e,L,Q)]})})]}),W&&i(U,{label:"Interval · optional",children:[t("input",{class:"field mono",style:{...un,borderColor:ce?void 0:"var(--red)"},value:P,placeholder:"auto — Claude decides the pace",onInput:_=>I(_.target.value)}),!ce&&t("span",{style:{fontSize:"12px",color:"var(--red)"},children:"Use forms like 30s, 5m, 2h — or leave it empty to self-pace"})]}),(s==="dev"||D)&&t(U,{label:"Description (optional)",children:t("textarea",{class:"field",rows:3,style:un,placeholder:"Context the agent reads first…",value:k,onInput:_=>S(_.target.value)})}),$&&t(oi,{doctor:$,account:d,value:N,defaultHarness:kt,isLoop:W,onChange:M,onOpenAccounts:c}),Ee&&i("div",{class:"grid",style:{gridTemplateColumns:s==="dev"?"1fr 1fr":"1fr",gap:"10px"},children:[i("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:Ce,children:"Model"}),be?t(se,{fill:!0,size:"sm",label:"Model",tabs:ao.map(_=>({id:_.id,label:_.label})),active:p,onChange:h}):t("input",{class:"field mono",style:{height:"32px",fontSize:"12.5px"},value:p,placeholder:"the account's model","aria-label":"Model",onInput:_=>h(_.target.value)})]}),s==="dev"&&i("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:Ce,children:"Workflow"}),t(se,{fill:!0,size:"sm",label:"Workflow",tabs:zi,active:y,onChange:w})]})]}),wt&&i("div",{class:"flex items-center",style:{gap:"10px",padding:"10px 12px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)"},children:[i("span",{class:"flex-1",style:{fontSize:"13px"},children:["Bypass permissions ",t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:"--skip-permissions"})]}),t(Mn,{checked:m,onChange:u,label:"Bypass permissions"})]}),Ve&&i("p",{style:{fontSize:"12.5px",padding:"10px 12px",borderRadius:"12px",background:Z("--orange"),color:"var(--ink)"},children:[St," has no MCP and CW has no ",Ct==="linear"?"LINEAR_API_KEY":"NOTION_TOKEN",", so the ticket will not reach TASK_NOTES.md. The task still starts, without the ticket."]}),t(E,{label:z?"Starting…":j?"Launch session":W?"Start loop":D?"Start review":"Start task",variant:"primary",size:"lg",block:!0,loading:z,disabled:$t,onClick:zt}),he&&t("p",{style:{fontSize:"12px",color:"var(--red)",textAlign:"center"},children:he}),t("p",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)",textAlign:"center",overflowWrap:"anywhere"},children:tn})]})},Gt=Y(null),An=Y(null);async function Yn(){const e=await fetch("/api/skills/plugins");if(!e.ok)throw new Error("fetch failed");Gt.value=await e.json()}async function In(){const e=await fetch("/api/skills/marketplaces");if(!e.ok)throw new Error("fetch failed");An.value=await e.json()}const Le=({title:e,sub:n,children:a})=>i("div",{class:"glass flex items-center flex-wrap shrink-0",style:{gap:"10px",padding:"12px 20px",borderBottom:"1px solid var(--hair)"},children:[i("div",{class:"min-w-0",children:[t("h2",{style:{fontSize:"17px",fontWeight:650,letterSpacing:"-0.015em",overflowWrap:"anywhere"},children:e}),n&&t("p",{class:"mono",style:{marginTop:"1px",fontSize:"11.5px",color:"var(--ink-3)",overflowWrap:"anywhere"},children:n})]}),t("span",{style:{flex:"1 1 40px"}}),a]});function Ri(e){const n=new Set;for(const a of e.skills){const r=a.path.split(/[\\/]/),o=r.lastIndexOf("skills");o>=0&&r.length-o===3&&n.add(r[o+1])}return[...n].sort()}function ji(e){return`add-skill-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,30).replace(/-+$/,"")||Date.now()}`}function Pi(e,n,a){return["Add a new skill to this repository and open a pull request.",`The skill: ${n}`,a?`Area: ${a}`:"",e.contributing?"Follow CONTRIBUTING.md.":"",e.projectSkills.length>0?`Use this repository's own skills: ${e.projectSkills.map(r=>`/${r}`).join(", ")}`:""].filter(Boolean).join(`
2
+ `)}const Rr=e=>`/api/skills/plugins/${encodeURIComponent(e)}`;async function Qn(e,n){try{return await ke(e,n)}catch(a){return A(we(a),"error"),null}}async function jr(e,n,a){await Qn("/api/skills/plugins/install",{id:e,account:a})&&(A(`${n} installed in ${a} · applies to new sessions`,"success"),await Promise.all([Yn(),In()]).catch(()=>{}))}const Pr=(e,n)=>n?e.skills.filter(a=>a.name.toLowerCase().includes(n)||a.description.toLowerCase().includes(n)):e.skills,Ai=({list:e,query:n,selected:a,onSelect:r})=>{const o=e.flatMap(l=>{const c=Pr(l,n).length;return!n||c>0||l.name.toLowerCase().includes(n)?[{p:l,count:c}]:[]});return o.length===0?null:i("div",{style:{marginTop:"10px"},children:[t("p",{style:{padding:"6px 11px",fontSize:"11px",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase",color:"var(--ink-3)"},children:"Plugins"}),o.map(({p:l,count:c})=>{const s=a===l.id;return i("button",{type:"button","aria-current":s?"true":void 0,class:"flex items-center w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",style:{gap:"8px",padding:"9px 11px",marginBottom:"4px",borderRadius:"11px",border:`1px solid ${s?"var(--hair)":"transparent"}`,background:s?"var(--card)":"transparent",boxShadow:s?"var(--shadow-s)":"none",color:"var(--ink)"},onClick:()=>r(l.id),children:[t("span",{class:"i-lucide-package shrink-0",style:{width:"13px",height:"13px",color:"var(--ink-3)"}}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:l.name}),t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:c})]},l.id)})]})},ha={fontSize:"12px",fontWeight:600,color:"var(--ink-2)",margin:"0 0 8px"},Ar={gap:"10px",padding:"9px 12px",borderRadius:"11px",border:"1px solid var(--hair)",background:"var(--card)"},Ii=({plugin:e,install:n})=>{const[a,r]=b(!1),o=n.scope==="global"?"global":n.scopeRef,l=async()=>{r(!0);const c=await Qn(`${Rr(e.id)}/update`,{scope:n.scope,scopeRef:n.scopeRef});r(!1),c&&(A(`${e.name} ${c.version??""} · applies to new sessions`,"success"),Yn().catch(()=>{}))};return i("div",{class:"flex items-center",style:Ar,children:[t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:o}),t("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:n.version}),t("span",{style:{fontSize:"11.5px",color:n.enabled?"var(--green)":"var(--ink-3)"},children:n.enabled?"on":"off"}),t(E,{label:a?"Updating…":"Update",variant:"secondary",size:"sm",loading:a,onClick:l})]})},Li=({plugin:e,account:n})=>{const[a,r]=b(!1);return i("div",{class:"flex items-center",style:Ar,children:[t("span",{class:"flex-1",style:{fontSize:"13px",color:"var(--ink-2)"},children:n}),t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"not installed"}),t(E,{label:a?"Installing…":"Install",variant:"secondary",size:"sm",loading:a,onClick:async()=>{r(!0),await jr(e.id,e.name,n),r(!1)}})]})},Ei=({plugin:e,name:n,onBack:a})=>{const[r,o]=b(null),[l,c]=b(!1);return F(()=>{let s=!1;return o(null),c(!1),fetch(`${Rr(e.id)}/skills/${encodeURIComponent(n)}`).then(d=>d.ok?d.json():Promise.reject(new Error("not found"))).then(d=>{s||o(d.content)}).catch(()=>{s||c(!0)}),()=>{s=!0}},[e.id,n]),i(J,{children:[t(Le,{title:n,sub:`${e.name} · read-only`,children:t(E,{label:"Back",variant:"secondary",size:"sm",onClick:a})}),i("div",{class:"flex-1 min-h-0 overflow-auto",style:{padding:"12px 20px 20px"},children:[t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",margin:"0 0 10px"},children:"Comes from the plugin. To change it, propose the change in the repository."}),l?t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Skill not found."}):r===null?t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Loading skill…"}):t("pre",{class:"mono",style:{margin:0,padding:"14px 16px",borderRadius:"14px",border:"1px solid var(--hair)",background:"var(--card)",fontSize:"12.5px",lineHeight:1.7,whiteSpace:"pre-wrap",overflowWrap:"anywhere",boxShadow:"var(--shadow-s)"},children:r})]})]})},Ni=({plugin:e,accounts:n,query:a,onSelectSkill:r,onPropose:o})=>{const l=new Set(e.installs.map(s=>s.scopeRef)),c=n.filter(s=>!l.has(s));return i(J,{children:[i(Le,{title:e.name,sub:e.repo?`${e.repo} · Claude Code only`:"Claude Code only",children:[e.repo&&t("a",{href:`https://github.com/${e.repo}`,target:"_blank",rel:"noreferrer",style:{fontSize:"12.5px",color:"var(--blue)"},children:"GitHub"}),e.project&&o&&t(E,{label:"Propose a skill",variant:"primary",size:"sm",onClick:o})]}),t("div",{class:"flex-1 min-h-0 overflow-auto",children:i("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"18px",maxWidth:"720px"},children:[e.description&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)",margin:0},children:e.description}),!e.project&&e.repo&&i("p",{style:{fontSize:"12.5px",color:"var(--ink-3)",margin:0},children:["Register ",t("span",{class:"mono",children:e.repo})," as a CW project to propose skills."]}),i("section",{children:[t("h3",{style:ha,children:"Accounts"}),i("div",{class:"flex flex-col",style:{gap:"6px"},children:[e.installs.map(s=>t(Ii,{plugin:e,install:s},`${s.scope}/${s.scopeRef}`)),c.map(s=>t(Li,{plugin:e,account:s},s))]})]}),i("section",{children:[i("h3",{style:ha,children:["Skills (",e.skills.length,")"]}),t("div",{class:"flex flex-col",style:{gap:"4px"},children:Pr(e,a).map(s=>i("button",{type:"button",class:"flex items-center w-full text-left cursor-pointer hover:bg-elev",style:{gap:"10px",padding:"8px 11px",borderRadius:"10px",border:0,background:"transparent",color:"var(--ink)"},onClick:()=>r(s.name),children:[t("span",{class:"shrink-0",style:{fontSize:"13px",fontWeight:600},children:s.name}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:s.description}),t("span",{class:"i-lucide-chevron-right shrink-0",style:{width:"13px",height:"13px",color:"var(--ink-3)"}})]},s.name))})]})]})})]})},Oi=({accounts:e})=>{const[n,a]=b(""),r=e.includes(n)?n:e[0]??"",[o,l]=b(""),[c,s]=b(""),[d,x]=b(""),[g,v]=b(!1),[k,S]=b(null);F(()=>{An.value===null&&In().catch(()=>A("Failed to load marketplaces","error"))},[]);const y=An.value,w=(y==null?void 0:y.find(f=>f.name===o))??(y==null?void 0:y[0]),p=new Set((Gt.value??[]).flatMap(f=>f.installs.some(P=>P.scope==="account"&&P.scopeRef===r)?[f.id]:[])),h=c.trim().toLowerCase(),m=((w==null?void 0:w.plugins)??[]).filter(f=>!h||f.name.toLowerCase().includes(h)||f.description.toLowerCase().includes(h)),u=async()=>{v(!0);const f=await Qn("/api/skills/marketplaces",{source:d.trim(),account:r});v(!1),f&&(A(`Marketplace added to ${r}`,"success"),x(""),await In().catch(()=>{}))},z=async(f,P)=>{S(f),await jr(f,P,r),S(null)};return i(J,{children:[t(Le,{title:"Add a plugin",sub:r?`Claude Code only · installs into ${r}`:"Claude Code only"}),i("div",{class:"flex-1 min-h-0 overflow-auto flex flex-col",style:{padding:"14px 20px 20px",gap:"8px"},children:[i("div",{class:"flex flex-col",style:{gap:"10px",maxWidth:"560px",marginBottom:"6px"},children:[e.length===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)",margin:0},children:"Plugins install into a CW account. Add one in Accounts first."}),e.length>0&&t(U,{label:"Account",children:t("select",{class:"field",value:r,onChange:f=>a(f.target.value),children:e.map(f=>t("option",{value:f,children:f},f))})}),y&&y.length>0&&t(U,{label:"Marketplace",children:t("select",{class:"field",value:w==null?void 0:w.name,onChange:f=>l(f.target.value),children:y.map(f=>i("option",{value:f.name,children:[f.name," · ",f.source]},f.name))})}),t(U,{label:"Add a marketplace",children:i("div",{class:"flex",style:{gap:"8px"},children:[t("input",{class:"field flex-1",value:d,placeholder:"owner/repo, git URL or path",onInput:f=>x(f.target.value),onKeyDown:f=>{f.key==="Enter"&&d.trim()&&u()}}),t(E,{label:g?"Adding…":"Add",variant:"secondary",size:"sm",loading:g,disabled:!d.trim()||!r,onClick:u})]})}),w&&w.plugins.length>0&&t("input",{class:"field",type:"search","aria-label":"Filter plugins",value:c,placeholder:`Filter ${w.plugins.length} plugins`,onInput:f=>s(f.target.value)})]}),y===null&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Loading marketplaces…"}),(y==null?void 0:y.length)===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"No marketplace yet. Add one above."}),w&&m.length===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:h?"No plugin matches.":"This marketplace lists no plugins."}),m.map((f,P)=>i("div",{class:"flex items-center",style:{gap:"12px",padding:"11px 15px",borderRadius:"13px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",animation:`riseIn .3s var(--ease) ${Math.min(P,8)*40}ms both`},children:[i("div",{class:"flex-1 min-w-0",children:[i("div",{class:"flex items-center min-w-0",style:{gap:"8px"},children:[t("span",{class:"truncate",style:{fontSize:"13.5px",fontWeight:600},children:f.name}),f.category&&t("span",{class:"mono shrink-0",style:{fontSize:"11px",color:"var(--ink-3)"},children:f.category})]}),f.description&&t("div",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-2)"},title:f.description,children:f.description})]}),p.has(f.id)?t("span",{style:{fontSize:"12px",color:"var(--green)"},children:"Installed"}):t(E,{label:k===f.id?"Installing…":"Install",variant:"secondary",size:"sm",loading:k===f.id,disabled:k!==null||!r,onClick:()=>z(f.id,f.name)})]},f.id))]})]})},Di=({plugin:e,accounts:n,onSubmit:a,onCancel:r})=>{const o=Ri(e),l=e.installs.filter(p=>p.scope==="account").map(p=>p.scopeRef),c=n.find(p=>l.includes(p))??n[0]??"",[s,d]=b(""),[x,g]=b(o[0]??""),[v,k]=b(c),[S,y]=b(!1),w=async()=>{y(!0);try{await a(s.trim(),o.length>1?x:void 0,v)}finally{y(!1)}};return i(J,{children:[t(Le,{title:"Propose a skill",sub:`${e.repo??e.name} · project ${e.project??""}`}),t("div",{class:"flex-1 min-h-0 overflow-auto",children:i("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"14px",maxWidth:"560px"},children:[i("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",margin:0},children:["Starts a task in ",t("span",{class:"mono",children:e.project})," that writes the skill and opens a pull request for review."]}),t(U,{label:"What the skill does and when to use it",children:t("textarea",{class:"field",rows:4,value:s,placeholder:"Summarize a release's merged PRs into notes when someone asks for a changelog",onInput:p=>d(p.target.value)})}),o.length>1&&t(U,{label:"Area",children:t("select",{class:"field",value:x,onChange:p=>g(p.target.value),children:o.map(p=>t("option",{value:p,children:p},p))})}),n.length>0&&t(U,{label:"Account",children:t("select",{class:"field",value:v,onChange:p=>k(p.target.value),children:n.map(p=>t("option",{value:p,children:p},p))})}),i("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(E,{label:S?"Starting…":"Start task",variant:"primary",loading:S,disabled:!s.trim()||!v,onClick:w}),t(E,{label:"Cancel",variant:"secondary",onClick:r})]})]})})]})},Wi={global:"--blue",account:"--orange",project:"--green"},It=e=>`${e.scope}/${e.scopeRef}/${e.dirName}`;function Mi(e,n){return e==="global"?"global":e==="account"?`account/${encodeURIComponent(n)}`:`project/${encodeURIComponent(n)}`}const st=e=>e.scope==="global"?"Global":`${e.scope==="account"?"Account":"Project"} · ${e.scopeRef}`,Fi=e=>e.scope==="global"?`~/.claude/skills/${e.dirName}`:e.scope==="account"?`~/.cw/accounts/${e.scopeRef}/skills/${e.dirName}`:`<${e.scopeRef}>/.claude/skills/${e.dirName}`,Bi={global:"Lands in ~/.claude/skills; CW links it into every account when a Claude Code session starts.",account:"Every session on this account loads it.",project:"Sessions in this project load it from its .claude/skills."},Ir=e=>e[0]?{scope:"account",scopeRef:e[0]}:{scope:"global",scopeRef:"global"},Ln=e=>e.scope==="global"||e.scopeRef!=="",Lr=({accounts:e,projects:n,value:a,onChange:r})=>{const o=l=>{const c=l==="account"?e:n;r({scope:l,scopeRef:l==="global"?"global":c.includes(a.scopeRef)?a.scopeRef:c[0]??""})};return i(J,{children:[i("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:Ce,children:"Scope"}),t(se,{label:"Scope",tabs:[{id:"account",label:"Account"},{id:"project",label:"Project"},{id:"global",label:"Global"}],active:a.scope,onChange:l=>o(l)}),t("span",{style:{fontSize:"12px",color:"var(--ink-3)"},children:Bi[a.scope]})]}),a.scope!=="global"&&t(U,{label:a.scope==="account"?"Account":"Project",children:t("select",{class:"field",value:a.scopeRef,onChange:l=>r({...a,scopeRef:l.target.value}),children:(a.scope==="account"?e:n).map(l=>t("option",{value:l,children:l},l))})})]})},_i=(e,n,a)=>[...n.map(r=>({scope:"account",scopeRef:r})),...a.map(r=>({scope:"project",scopeRef:r})),{scope:"global",scopeRef:"global"}].filter(r=>r.scope!==e.scope||r.scopeRef!==e.scopeRef),Er=(e,n="")=>{const a=[];for(const[r,o]of Object.entries(e))o&&typeof o=="object"&&!Array.isArray(o)?(a.push(`${n}${r}:`),a.push(...Er(o,n+" "))):a.push(`${n}${r}: ${String(o??"")}`);return a},Ki=({skill:e,accounts:n,projects:a,onDeleted:r,onCopied:o,onRun:l})=>{const[c,s]=b(null),[d,x]=b(!0),[g,v]=b("SKILL.md"),[k,S]=b(""),[y,w]=b({}),[p,h]=b(!1),m=`/api/skills/${Mi(e.scope,e.scopeRef)}/${encodeURIComponent(e.dirName)}`;F(()=>{let T=!1;return x(!0),v("SKILL.md"),fetch(m).then(R=>{if(!R.ok)throw new Error("fetch failed");return R.json()}).then(R=>{if(T)return;s(R);const $=Er(R.frontmatter);S($.length>0?`---
3
+ ${$.join(`
4
+ `)}
5
+ ---
6
+
7
+ ${R.body}`:R.body),w(Object.fromEntries(R.references.map(B=>[B.name,B.content])))}).catch(()=>{T||(s(null),A("Failed to load skill","error"))}).finally(()=>{T||x(!1)}),()=>{T=!0}},[m]);const u=async()=>{h(!0);const T=g==="SKILL.md";try{const $=await(await fetch(T?m:`${m}/references/${encodeURIComponent(g)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:T?k:y[g]??""})})).json();$.ok?A(T?"Skill saved":"Reference saved","success"):A($.error??"Failed to save","error")}catch{A("Failed to save","error")}finally{h(!1)}},z=async()=>{if(confirm(`Delete the skill "${e.name}" permanently?`))try{const R=await(await fetch(m,{method:"DELETE"})).json();R.ok?(A("Skill deleted","info"),r()):A(R.error??"Failed to delete","error")}catch{A("Failed to delete","error")}},f=async T=>{try{const $=await(await fetch("/api/skills/copy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:{scope:e.scope,scopeRef:e.scopeRef,name:e.dirName},to:T})})).json();$.ok?(A(`Copied to ${st(T)}`,"success"),o()):A($.error??"Failed to copy","error")}catch{A("Failed to copy","error")}},P=async()=>{const T=prompt("Reference filename (e.g. examples.md):");if(!(T!=null&&T.trim()))return;const R=T.trim(),$=`# ${R}
8
+ `;try{const j=await(await fetch(`${m}/references/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:$})})).json();j.ok?(w(D=>({...D,[R]:$})),s(D=>D&&{...D,references:[...D.references,{name:R,content:$}]}),v(R),A("Reference added","success")):A(j.error??"Failed to add reference","error")}catch{A("Failed to add reference","error")}},I=async T=>{if(confirm(`Delete reference "${T}"?`))try{const $=await(await fetch(`${m}/references/${encodeURIComponent(T)}`,{method:"DELETE"})).json();$.ok?(w(B=>{const{[T]:j,...D}=B;return D}),s(B=>B&&{...B,references:B.references.filter(j=>j.name!==T)}),g===T&&v("SKILL.md"),A("Reference deleted","info")):A($.error??"Failed to delete reference","error")}catch{A("Failed to delete reference","error")}},N=["SKILL.md",...(c==null?void 0:c.references.map(T=>T.name))??[]],M=_i(e,n,a);return i(J,{children:[i(Le,{title:e.name,sub:`${st(e)} · ${Fi(e)}`,children:[t(E,{label:"Delete",variant:"danger",size:"sm",onClick:z}),i("select",{class:"field","aria-label":"Copy to",style:{height:"30px",padding:"0 8px",fontSize:"12.5px",width:"auto"},value:"",disabled:!c,onChange:T=>{const R=T.target,$=M[Number(R.value)];R.value="",$&&f($)},children:[t("option",{value:"",disabled:!0,children:"Copy to…"}),M.map((T,R)=>t("option",{value:R,children:st(T)},`${T.scope}/${T.scopeRef}`))]}),t(E,{label:"Run in session",variant:"secondary",size:"sm",onClick:l}),t(E,{label:p?"Saving…":"Save",variant:"primary",size:"sm",loading:p,disabled:!c,onClick:u})]}),i("div",{class:"flex items-center flex-wrap shrink-0",style:{gap:"6px",padding:"10px 20px 0"},role:"tablist","aria-label":"Files",children:[N.map(T=>{const R=g===T;return i("span",{class:"inline-flex items-center",style:{gap:"4px",padding:R?"5px 8px 5px 11px":"5px 11px",borderRadius:"9px",background:R?"var(--card)":"transparent",border:`1px solid ${R?"var(--hair)":"transparent"}`,boxShadow:R?"var(--shadow-s)":"none"},children:[t("button",{type:"button",role:"tab","aria-selected":R,class:"mono cursor-pointer",style:{border:0,background:"none",padding:0,fontSize:"12px",fontWeight:R?600:400,color:R?"var(--ink)":"var(--ink-3)"},onClick:()=>v(T),children:T}),R&&T!=="SKILL.md"&&t("button",{type:"button","aria-label":`Delete ${T}`,class:"grid place-items-center cursor-pointer text-ink3 hover:text-red",style:{border:0,background:"none",padding:0},onClick:()=>I(T),children:t("span",{class:"i-lucide-x",style:{width:"12px",height:"12px"}})})]},T)}),t("span",{class:"flex-1"}),t("button",{type:"button",class:"cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px",style:{padding:"5px 10px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--blue)",fontSize:"12px",fontWeight:500},onClick:P,disabled:!c,children:"+ Reference"})]}),t("div",{class:"flex-1 min-h-0",style:{padding:"12px 20px 20px"},children:d?t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Loading skill…"}):c?t("textarea",{class:"field mono w-full h-full","aria-label":g,spellcheck:!1,style:{height:"100%",padding:"14px 16px",borderRadius:"14px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink)",fontSize:"12.5px",lineHeight:1.7,resize:"none",outline:"none",boxShadow:"var(--shadow-s)",minHeight:"240px"},value:g==="SKILL.md"?k:y[g]??"",onInput:T=>{const R=T.target.value;g==="SKILL.md"?S(R):w($=>({...$,[g]:R}))}}):t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Skill not found."})})]})},Ui=({query:e,accounts:n,projects:a,onInstalled:r})=>{const[o,l]=b(null),[c,s]=b(null),[d,x]=b(()=>Ir(n));F(()=>{let v=!1;return l(null),fetch(`/api/skills/explore?q=${encodeURIComponent(e)}`).then(k=>{if(!k.ok)throw new Error("search failed");return k.json()}).then(k=>{v||l(k.results)}).catch(()=>{v||(l([]),A("Failed to search skills","error"))}),()=>{v=!0}},[e]);const g=async v=>{s(v.slug);try{const S=await(await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:v.repo,skill:v.skillId,...d})})).json();S.ok?(A(`Installed in ${st(d)}`,"success"),r()):A(S.error??"Failed to install","error")}catch{A("Failed to install","error")}finally{s(null)}};return i(J,{children:[t(Le,{title:`skills.sh · “${e}”`,sub:`Installs into ${st(d)}`}),i("div",{class:"flex-1 min-h-0 overflow-auto flex flex-col",style:{padding:"14px 20px 20px",gap:"8px"},children:[t("div",{class:"flex flex-col",style:{gap:"10px",maxWidth:"560px",marginBottom:"6px"},children:t(Lr,{accounts:n,projects:a,value:d,onChange:x})}),o===null&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Searching…"}),(o==null?void 0:o.length)===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"No results on skills.sh."}),o==null?void 0:o.map((v,k)=>i("div",{class:"flex items-center",style:{gap:"12px",padding:"11px 15px",borderRadius:"13px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",animation:`riseIn .3s var(--ease) ${Math.min(k,8)*40}ms both`},children:[i("div",{class:"flex-1 min-w-0",children:[t("div",{class:"truncate",style:{fontSize:"13.5px",fontWeight:600},children:v.name}),i("div",{class:"mono truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[v.repo," · ",v.installs," installs"]})]}),t(E,{label:c===v.slug?"Installing…":"Install",variant:"secondary",size:"sm",loading:c===v.slug,disabled:!Ln(d),onClick:()=>g(v)})]},v.slug))]})]})},Hi=({accounts:e,projects:n,onCreated:a,onCreateWithAI:r})=>{const[o,l]=b(()=>Ir(e)),[c,s]=b(""),[d,x]=b(""),[g,v]=b(!1),{scope:k,scopeRef:S}=o,y=async()=>{if(!c.trim())return;v(!0);const w=`---
9
+ name: ${c.trim()}
10
+ description: ${d.trim()}
11
+ domain: general
12
+ ---
13
+
14
+ # ${c.trim()}
15
+
16
+ ${d.trim()}
17
+ `;try{const h=await(await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:k,scopeRef:S,name:c.trim(),content:w})})).json();h.ok?(A("Skill created","success"),a()):A(h.error??"Failed to create skill","error")}catch{A("Failed to create skill","error")}finally{v(!1)}};return i(J,{children:[t(Le,{title:"New skill",sub:"Write it yourself or let an agent draft it with skill-creator"}),t("div",{class:"flex-1 min-h-0 overflow-auto",children:i("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"14px",maxWidth:"560px"},children:[t(Lr,{accounts:e,projects:Object.keys(n),value:o,onChange:l}),t(U,{label:"Name",children:t("input",{class:"field",value:c,placeholder:"my-skill",onInput:w=>s(w.target.value)})}),t(U,{label:"Description",children:t("textarea",{class:"field",rows:3,value:d,placeholder:"What does this skill do?",onInput:w=>x(w.target.value)})}),i("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(E,{label:g?"Creating…":"Create",variant:"primary",loading:g,disabled:!c.trim()||!Ln(o),onClick:y}),r&&t(E,{label:"Create with AI",variant:"secondary",disabled:!d.trim()||!Ln(o),title:"Starts a session that drafts the skill",onClick:()=>r(k,S,d.trim())})]})]})})]})},qi=({accounts:e,projects:n,onCreateWithAI:a,onRunSkill:r,onProposeSkill:o})=>{const[l,c]=b(""),[s,d]=b({kind:"empty"}),[x,g]=b(it.value===null),v=Object.keys(n),k=V(async()=>{try{await Promise.all([Oa(),Yn()])}catch{A("Failed to load skills","error")}finally{g(!1)}},[]);F(()=>{(it.value===null||Gt.value===null)&&k()},[k]);const S=it.value??[],y=l.trim().toLowerCase(),w=y?S.filter(u=>u.name.toLowerCase().includes(y)||u.description.toLowerCase().includes(y)):S,p=Gt.value??[],h=s.kind==="plugin"||s.kind==="propose"?p.find(u=>u.id===s.id):void 0;F(()=>{s.kind==="empty"&&S.length>0&&d({kind:"editor",skill:S[0]})},[S.length]);const m=s.kind==="editor"?It(s.skill):null;return i("main",{class:"skills-page grid min-w-0",style:{gridTemplateColumns:"292px minmax(0,1fr)",height:"100vh"},children:[i("div",{class:"skills-rail flex flex-col min-h-0 overflow-hidden",style:{borderRight:"1px solid var(--hair)",background:"var(--bg-2)"},children:[i("div",{class:"flex flex-col shrink-0",style:{padding:"12px 14px",borderBottom:"1px solid var(--hair)",gap:"10px"},children:[i("div",{class:"flex items-center",style:{gap:"10px"},children:[t(Jn,{}),t("h1",{style:{fontSize:"18px",fontWeight:700,letterSpacing:"-0.02em"},children:"Skills"}),t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:S.length}),t("span",{class:"flex-1"}),t(E,{label:"New",variant:"primary",size:"sm",onClick:()=>d({kind:"create"})})]}),t("input",{class:"field",type:"search","aria-label":"Search skills",style:{height:"32px",padding:"0 11px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink)",fontSize:"13px",outline:"none"},placeholder:"Search installed or skills.sh",value:l,onInput:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&l.trim()&&d({kind:"explore",query:l.trim()})}})]}),i("div",{class:"overflow-auto min-h-0",style:{padding:"8px"},children:[x&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:"Loading skills…"}),!x&&w.length===0&&p.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:y?"No installed skill matches.":"No skills yet."}),w.map(u=>{const z=m===It(u);return i("button",{type:"button","aria-current":z?"true":void 0,class:"block w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",style:{padding:"9px 11px",marginBottom:"4px",borderRadius:"11px",border:`1px solid ${z?"var(--hair)":"transparent"}`,background:z?"var(--card)":"transparent",boxShadow:z?"var(--shadow-s)":"none",color:"var(--ink)"},onClick:()=>d({kind:"editor",skill:u}),children:[i("span",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{class:"shrink-0",style:{width:"7px",height:"7px",borderRadius:"50%",background:`var(${Wi[u.scope]})`}}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:u.name}),t("span",{class:"truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"90px"},children:u.scope==="global"?"global":u.scopeRef})]}),u.description&&t("span",{class:"block truncate",style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:u.description})]},It(u))}),t(Ai,{list:p,query:y,selected:s.kind==="plugin"||s.kind==="propose"?s.id:null,onSelect:u=>d({kind:"plugin",id:u})}),!y&&i("button",{type:"button","aria-current":s.kind==="plugins"?"true":void 0,class:"flex items-center w-full text-left cursor-pointer hover:bg-elev",style:{gap:"8px",padding:"9px 11px",marginTop:"6px",borderRadius:"11px",border:"1px dashed var(--hair-2)",background:"transparent",color:"var(--blue)",fontSize:"12.5px",fontWeight:500},onClick:()=>d({kind:"plugins"}),children:[t("span",{class:"i-lucide-plus shrink-0",style:{width:"13px",height:"13px"}}),t("span",{class:"truncate",children:"Add a plugin"})]}),y&&i("button",{type:"button",class:"flex items-center w-full text-left cursor-pointer hover:bg-elev",style:{gap:"8px",padding:"9px 11px",borderRadius:"11px",border:"1px dashed var(--hair-2)",background:"transparent",color:"var(--blue)",fontSize:"12.5px",fontWeight:500},onClick:()=>d({kind:"explore",query:l.trim()}),children:[t("span",{class:"i-lucide-search shrink-0",style:{width:"13px",height:"13px"}}),i("span",{class:"truncate",children:["Search skills.sh for “",l.trim(),"”"]})]})]})]}),i("div",{class:"flex flex-col min-h-0 min-w-0",children:[s.kind==="editor"&&t(Ki,{skill:s.skill,accounts:e,projects:v,onCopied:()=>{k()},onRun:()=>r(s.skill),onDeleted:()=>{d({kind:"empty"}),k()}},It(s.skill)),s.kind==="create"&&t(Hi,{accounts:e,projects:n,onCreateWithAI:a,onCreated:()=>{d({kind:"empty"}),k()}}),s.kind==="explore"&&t(Ui,{query:s.query,accounts:e,projects:v,onInstalled:()=>{k()}}),s.kind==="plugins"&&t(Oi,{accounts:e}),s.kind==="plugin"&&h&&!s.skill&&t(Ni,{plugin:h,accounts:e,query:y,onSelectSkill:u=>d({kind:"plugin",id:h.id,skill:u}),onPropose:()=>d({kind:"propose",id:h.id})}),s.kind==="plugin"&&h&&s.skill&&t(Ei,{plugin:h,name:s.skill,onBack:()=>d({kind:"plugin",id:h.id})},s.skill),s.kind==="propose"&&h&&t(Di,{plugin:h,accounts:e,onCancel:()=>d({kind:"plugin",id:h.id}),onSubmit:async(u,z,f)=>{await o(h,u,z,f)&&d({kind:"plugin",id:h.id})}}),s.kind==="empty"&&!x&&t("div",{class:"flex-1 grid place-items-center",style:{padding:"24px"},children:i("div",{class:"flex flex-col items-center text-center",style:{gap:"12px"},children:[t("p",{style:{fontSize:"13.5px",color:"var(--ink-2)"},children:"Pick a skill to edit it, or write a new one."}),t(E,{label:"New skill",variant:"primary",onClick:()=>d({kind:"create"})})]})})]})]})},hn={auto:"qa:auto",escalated:"qa:needs-human",blocked:"qa:blocked"},fa="<!-- qa-pilot:decision",Gi="-->",Vi=["auto","escalate","blocked"],Ji=["pass","fail","warn"],Yi=["journey","file","severity","artifact"],Re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),le=e=>typeof e=="string",ct=e=>typeof e=="number"&&Number.isFinite(e);function Qi(e){return Re(e)&&le(e.id)&&le(e.reason)}function Zi(e){return!Re(e)||!le(e.check)||!le(e.kind)||!le(e.message)?!1:Yi.every(n=>e[n]===void 0||le(e[n]))}function Xi(e){if(!Re(e)||e.version!==1||!le(e.decision)||!Vi.includes(e.decision)||!le(e.sha)||!Array.isArray(e.gates)||!e.gates.every(Qi))return!1;const n=e.diff;return!Re(n)||!ct(n.files)||!ct(n.added)||!ct(n.removed)||!Re(e.checks)||!Object.values(e.checks).every(a=>le(a)&&Ji.includes(a))?!1:Array.isArray(e.findings)&&e.findings.every(Zi)}function el(e){const n=e.lastIndexOf(fa);if(n===-1)return null;const a=n+fa.length,r=e.indexOf(Gi,a);if(r===-1)return null;try{const o=JSON.parse(e.slice(a,r));return Xi(o)?o:null}catch{return null}}const tl=["github-actions[bot]","github-actions"];function nl(e){var a;const n=(a=e.author)==null?void 0:a.login;return typeof n=="string"&&tl.includes(n)}function al(e){for(let n=e.length-1;n>=0;n--){if(!nl(e[n]))continue;const a=el(e[n].body);if(a)return a}return null}function rl(e){const n={total:e.length,auto:0,escalated:0,blocked:0};for(const a of e){const r=new Set((a.labels??[]).map(o=>o.name));r.has(hn.auto)&&n.auto++,r.has(hn.escalated)&&n.escalated++,r.has(hn.blocked)&&n.blocked++}return n}function ol(e,n){return e.sha!==n}const il=/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/raw\/([0-9a-f]{40})\/(pr-\d+\/[0-9a-f]{7}\/)$/,ll=/^artifacts\/[A-Za-z0-9._-]+\.png$/;function sl(e){const n=e.change;if(!Re(n)||!ct(n.pixels)||!ct(n.percent)||!le(n.zone))return;const a=`${n.percent<.1?"menos de 0,1 %":`${String(n.percent).replace(".",",")} %`} de la captura`;return`${Array.isArray(e.elements)&&e.elements.every(le)&&e.elements.length?`${e.elements.join(", ")} · `:""}${a} · ${n.zone}`}function cl(e){const n=il.exec(e.evidence??"");if(!n)return[];const[,a,r]=n,o=c=>le(c)&&ll.test(c)?{ref:a,path:r+c}:void 0,l=[];for(const c of e.findings)if(Array.isArray(c.images))for(const s of c.images){if(!Re(s)||!le(s.name))continue;const d={name:s.name};c.journey&&(d.journey=c.journey),le(s.ai)&&s.ai&&(d.ai=s.ai.slice(0,200));const x=sl(s);x&&(d.summary=x);const g=o(s.expected),v=o(s.marked)??o(s.actual),k=o(s.diff);g&&(d.before=g),v&&(d.after=v),k&&(d.diff=k),(g||v||k)&&l.push(d)}return l}function En(e){const n=Vt(e);if(!n.ok)return n;const a=n.data;try{return{ok:!0,data:JSON.parse(a)}}catch{return{ok:!1,message:a||"gh no devolvió JSON"}}}function Vt(e){if("error"in e)return{ok:!1,message:e.error};const n=e.output.trim();return e.timedOut?{ok:!1,message:"gh no respondió a tiempo"}:e.exitCode!==0?{ok:!1,message:n||`gh terminó con código ${e.exitCode}`}:{ok:!0,data:n}}function dl(e,n=Date.now()){const a=Date.parse(e);if(Number.isNaN(a))return"";const r=Math.floor((n-a)/6e4);if(r<1)return"ahora";if(r<60)return`hace ${r} min`;const o=Math.floor(r/60);return o<24?`hace ${o} h`:`hace ${Math.floor(o/24)} d`}const pl={pass:"✓",fail:"✗",warn:"!"};function ul(e){return pl[e]}const hl=/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/;function fl(e){const n=Vt(e);if(!n.ok){const a=n.message.split(`
18
+ `).find(r=>/HTTP \d{3}|gh: /.test(r));return{ok:!1,message:(a==null?void 0:a.trim())??n.message.split(`
19
+ `)[0]}}return hl.test(n.data)?{ok:!0,data:`data:image/png;base64,${n.data}`}:{ok:!1,message:"la imagen no es un PNG"}}const bt=(e,n=16)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,fe={background:"var(--card)",border:"1px solid var(--hair)",borderRadius:"12px"},gl={pass:"--green",fail:"--red",warn:"--orange"};function xl(e,n,a){return V(async(r,o)=>{try{return await(await fetch(`/api/actions/${e}/${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,...a?{cwProject:a}:{},params:o})})).json()}catch(l){return{error:l instanceof Error?l.message:"Forge no respondió"}}},[e,n,a])}function Nr({message:e,onRetry:n}){return i("div",{style:{...fe,padding:"18px 20px",borderColor:bt("--red",50)},children:[t("h3",{style:{fontSize:"15px",fontWeight:700,marginBottom:"6px"},children:"No se pudo leer GitHub"}),i("p",{style:{fontSize:"13px",color:"var(--ink-2)",marginBottom:"10px"},children:["Ejecuta ",t("code",{style:{fontFamily:"var(--mono)"},children:"gh auth login"})," en una terminal y comprueba que el proyecto es un repositorio de GitHub."]}),t("pre",{style:{fontFamily:"var(--mono)",fontSize:"11.5px",color:"var(--ink-3)",whiteSpace:"pre-wrap",marginBottom:"12px"},children:e}),t(E,{label:"Reintentar",variant:"secondary",size:"sm",onClick:n})]})}function ml({stats:e}){const n=r=>e.state==="ok"?String(r(e.data)):"–",a=[{label:"PRs esta semana",value:n(r=>r.total),tone:"--ink"},{label:"Aprobados solos",value:n(r=>r.auto),tone:"--green"},{label:"Escalados",value:n(r=>r.escalated),tone:"--orange"},{label:"Bloqueados",value:n(r=>r.blocked),tone:"--red"}];return t("div",{class:"grid gap-2.5 mb-3.5",style:{gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))"},children:a.map(r=>i("div",{style:{...fe,borderRadius:"10px",padding:"10px 12px",minWidth:0},children:[t("span",{style:{fontSize:"11.5px",color:"var(--ink-2)"},children:r.label}),t("b",{style:{display:"block",fontSize:"20px",fontVariantNumeric:"tabular-nums",color:`var(${r.tone})`},children:r.value})]},r.label))})}function ga({label:e,tone:n}){return t("span",{style:{fontSize:"11.5px",borderRadius:"6px",padding:"3px 8px",border:`1px solid ${n?`var(${n})`:"var(--hair)"}`,color:n?`var(${n})`:"var(--ink)",background:n?bt(n):"var(--elev)"},children:e})}function vl({decision:e}){return i(J,{children:[i("div",{class:"flex flex-wrap gap-1.5",children:[e.gates.map(n=>t(ga,{label:`${n.id} · ${n.reason}`,tone:"--orange"},n.id+n.reason)),Object.entries(e.checks).map(([n,a])=>t(ga,{label:`${n} ${ul(a)}`,tone:a==="pass"?void 0:gl[a]},n))]}),e.findings.length>0&&i("div",{children:[t("div",{style:{fontSize:"12px",fontWeight:600,color:"var(--ink-2)",marginBottom:"6px"},children:"Hallazgos"}),t("ul",{class:"flex flex-col gap-1.5",style:{listStyle:"none",padding:0,margin:0},children:e.findings.map((n,a)=>i("li",{style:{...fe,borderRadius:"8px",padding:"8px 10px",fontSize:"12.5px"},children:[i("div",{class:"flex flex-wrap gap-1.5 mb-1",style:{fontSize:"11px",color:"var(--ink-3)"},children:[t("span",{children:n.check}),i("span",{children:["· ",n.kind]}),n.journey&&i("span",{children:["· ",n.journey]}),n.severity&&i("span",{children:["· ",n.severity]})]}),t("div",{children:n.message}),(n.file||n.artifact)&&t("code",{style:{fontFamily:"var(--mono)",fontSize:"11px",color:"var(--ink-2)"},children:n.file??n.artifact})]},a))})]})]})}function fn({file:e,label:n,run:a,onOpen:r}){const[o,l]=b({state:"loading"});F(()=>{if(!e)return;let s=!0;return l({state:"loading"}),a("get-evidence",{REF:e.ref,PATH:e.path}).then(d=>{const x=fl(d);s&&l(x.ok?{state:"ok",data:x.data}:{state:"error",message:x.message})}),()=>{s=!1}},[e==null?void 0:e.ref,e==null?void 0:e.path,a]);const c={...fe,borderRadius:"8px",overflow:"hidden",aspectRatio:"4 / 3",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--elev)"};return i("figure",{style:{margin:0,minWidth:0},children:[t("figcaption",{style:{fontSize:"11.5px",color:"var(--ink-2)",marginBottom:"4px"},children:n}),e?o.state==="loading"?t("div",{style:c,class:"animate-pulse"}):o.state==="error"?t("div",{style:{...c,fontSize:"11.5px",color:"var(--ink-3)",padding:"8px",textAlign:"center"},children:o.message}):t("button",{type:"button",onClick:()=>r(o.data,n),class:"cursor-zoom-in",style:{...c,padding:0},title:"Ver en grande",children:t("img",{src:o.data,alt:n,style:{width:"100%",height:"100%",objectFit:"contain"}})}):t("div",{style:{...c,fontSize:"12px",color:"var(--ink-3)"},children:"—"})]})}function yl({changes:e,run:n}){const[a,r]=b(null);F(()=>{if(!a)return;const l=c=>{c.key==="Escape"&&r(null)};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[a]);const o=(l,c)=>r({src:l,label:c});return i("div",{children:[t("div",{style:{fontSize:"12px",fontWeight:600,color:"var(--ink-2)",marginBottom:"6px"},children:"Cambios visuales"}),t("ul",{class:"flex flex-col gap-2.5",style:{listStyle:"none",padding:0,margin:0},children:e.map(l=>i("li",{style:{...fe,borderRadius:"10px",padding:"10px 12px"},children:[i("div",{style:{fontSize:"12.5px",fontWeight:600},children:[l.name,l.journey?` · ${l.journey}`:""]}),l.ai&&i("p",{style:{fontSize:"13px",margin:"4px 0 0"},children:[l.ai," ",t("span",{title:"Descripción hecha por Claude mirando Antes y Después; puede equivocarse",style:{fontSize:"10.5px",padding:"1px 5px",borderRadius:"4px",background:bt("--purple"),color:"var(--purple)"},children:"IA"})]}),l.summary&&i("p",{style:{fontSize:"12px",color:"var(--ink-2)",margin:"3px 0 0"},children:["Cambió: ",l.summary]}),i("div",{class:"grid gap-2 mt-2",style:{gridTemplateColumns:"repeat(3, minmax(0, 1fr))"},children:[t(fn,{file:l.before,label:"Antes",run:n,onOpen:o}),t(fn,{file:l.after,label:"Después",run:n,onOpen:o}),t(fn,{file:l.diff,label:"Diferencia",run:n,onOpen:o})]})]},l.name))}),t("p",{style:{fontSize:"11.5px",color:"var(--ink-3)",marginTop:"6px"},children:"El recuadro rojo en Después marca la zona que cambió. En Diferencia, lo rojo son los píxeles distintos y lo amarillo, bordes suavizados que no cuentan."}),a&&t("div",{role:"dialog","aria-label":a.label,onClick:()=>r(null),class:"cursor-zoom-out",style:{position:"fixed",inset:0,zIndex:50,background:"color-mix(in srgb, black 70%, transparent)",display:"flex",alignItems:"center",justifyContent:"center",padding:"24px"},children:t("img",{src:a.src,alt:a.label,style:{maxWidth:"100%",maxHeight:"100%",borderRadius:"8px",background:"white"}})})]})}function bl({pr:e,run:n,onDone:a}){var z;const[r,o]=b({state:"loading"}),[l,c]=b(!1),[s,d]=b(""),[x,g]=b("Esperando tu decisión."),v=V(async()=>{o({state:"loading"});const f=En(await n("get-decision",{PR:String(e.number)}));o(f.ok?{state:"ok",data:f.data}:{state:"error",message:f.message})},[e.number,n]);if(F(()=>{c(!1),d(""),g("Esperando tu decisión."),v()},[v]),r.state==="loading")return t("div",{style:{...fe,height:"220px"},class:"animate-pulse"});if(r.state==="error")return t(Nr,{message:r.message,onRetry:v});const k=r.data,S=al(k.comments),y=S?ol(S,k.headRefOid):!1,w=S!==null&&S.decision==="escalate"&&!y,p=S?cl(S):[],h=(S==null?void 0:S.diff)??{files:k.changedFiles,added:k.additions,removed:k.deletions},m=async()=>{const f=Vt(await n("approve",{PR:String(e.number)}));g(f.ok?"Aprobado: qa-pilot pone el status en verde y activa el auto-merge.":`No se pudo aprobar: ${f.message}`),f.ok&&a()},u=async()=>{const f=Vt(await n("request-changes",{PR:String(e.number),MSG:s.trim()}));f.ok?(g("Comentario publicado en el PR."),c(!1),d("")):g(f.message.startsWith("Param MSG")?"El mensaje admite letras, números, espacios y puntuación básica, en una línea y sin < > $ ` \\ [ ].":`No se pudo comentar: ${f.message}`)};return i("div",{class:"flex flex-col gap-3.5",style:{...fe,padding:"16px 18px",minWidth:0},children:[i("div",{children:[i("h3",{style:{fontSize:"15px",fontWeight:700,letterSpacing:"-0.01em"},children:["#",k.number," · ",k.title]}),i("div",{style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:[(z=k.author)!=null&&z.login?`abierto por ${k.author.login} en `:"rama ",t("code",{style:{fontFamily:"var(--mono)"},children:k.headRefName}),` · ${h.files} archivos, +${h.added} −${h.removed}`]})]}),S===null?t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Este PR no tiene un comentario de decisión de qa-pilot legible. Revisa el workflow antes de aprobar."}):i(J,{children:[y&&i("p",{style:{fontSize:"12.5px",padding:"8px 10px",borderRadius:"8px",background:bt("--orange"),color:"var(--orange)"},children:["La decisión es del commit ",t("code",{children:S.sha.slice(0,7)})," y el PR ya está en ",t("code",{children:k.headRefOid.slice(0,7)}),". Espera la nueva corrida."]}),t(vl,{decision:S}),p.length>0&&t(yl,{changes:p,run:n})]}),l&&i("div",{class:"flex flex-col gap-2",children:[t("textarea",{value:s,maxLength:500,rows:3,placeholder:"Qué debe cambiar (una línea, sin < > $ ni comillas invertidas)",onInput:f=>d(f.target.value.replace(/\s*\n\s*/g," ")),style:{...fe,borderRadius:"8px",padding:"8px 10px",fontSize:"13px",color:"var(--ink)",fontFamily:"var(--font)",resize:"vertical"}}),i("div",{class:"flex gap-2",children:[t(E,{label:"Enviar comentario",size:"sm",disabled:s.trim()==="",onClick:u}),t(E,{label:"Cancelar",variant:"secondary",size:"sm",onClick:()=>c(!1)})]})]}),i("div",{class:"flex flex-wrap gap-2",children:[!l&&t(E,{label:"Pedir cambios",variant:"secondary",icon:"i-lucide-message-square",onClick:()=>c(!0)}),t(E,{label:"Aprobar",icon:"i-lucide-check",disabled:!w,title:w?"Añade qa:approved al PR":"Solo se aprueba una decisión escalada y vigente",onClick:m}),i("a",{href:k.url,target:"_blank",rel:"noreferrer",class:"inline-flex items-center gap-1.5",style:{...fe,borderRadius:"9px",padding:"7px 13px",fontSize:"13px",color:"var(--ink)",textDecoration:"none"},children:[t("span",{class:"i-lucide-external-link"})," Abrir PR"]})]}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},"aria-live":"polite",children:x})]})}function kl({moduleId:e,projectId:n,cwProject:a}){const r=xl(e,n,a),o=!!(n||a),[l,c]=b({state:"loading"}),[s,d]=b({state:"loading"}),[x,g]=b(null),v=V(async()=>{c({state:"loading"});const[S,y]=await Promise.all([r("list-escalations").then(w=>En(w)),r("week-stats").then(w=>En(w))]);c(S.ok?{state:"ok",data:S.data}:{state:"error",message:S.message}),d(y.ok?{state:"ok",data:rl(y.data)}:{state:"error",message:y.message}),S.ok&&g(w=>{var p;return S.data.some(h=>h.number===w)?w:((p=S.data[0])==null?void 0:p.number)??null})},[r]);if(F(()=>{o&&v()},[o,v]),!o)return t(je,{icon:"i-lucide-folder-search",title:"Elige un proyecto",description:"Los escalamientos se leen del repositorio de GitHub del proyecto."});const k=l.state==="ok"?l.data.find(S=>S.number===x):void 0;return i("div",{children:[i("div",{class:"flex items-center justify-between mb-3.5",children:[t("h2",{style:{fontSize:"15px",fontWeight:700},children:"Escalamientos"}),t(E,{label:"Actualizar",variant:"secondary",size:"sm",icon:"i-lucide-refresh-cw",loading:l.state==="loading",onClick:v})]}),t(ml,{stats:s}),l.state==="loading"?t("div",{style:{...fe,height:"160px"},class:"animate-pulse"}):l.state==="error"?t(Nr,{message:l.message,onRetry:v}):l.data.length===0?t(je,{icon:"i-lucide-inbox",title:"Nada te necesita",description:"No hay PRs abiertos con qa:needs-human. Lo que pasó los checks y las reglas se aprobó solo."}):i("div",{class:"grid gap-3.5",style:{gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 260px), 1fr))",alignItems:"start"},children:[t("div",{class:"flex flex-col gap-2",role:"listbox","aria-label":"PRs escalados",children:l.data.map(S=>{var y;return i("button",{type:"button",role:"option","aria-selected":S.number===x,onClick:()=>g(S.number),class:"text-left cursor-pointer",style:{...fe,borderRadius:"10px",padding:"10px 12px",color:"var(--ink)",borderColor:S.number===x?"var(--blue)":"var(--hair)",background:S.number===x?bt("--blue",10):"var(--card)"},children:[i("div",{class:"flex justify-between gap-2",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[i("span",{children:["#",S.number," · ",dl(S.updatedAt)]}),((y=S.author)==null?void 0:y.login)&&t("span",{children:S.author.login})]}),t("b",{style:{display:"block",fontSize:"13px",marginTop:"2px"},children:S.title})]},S.number)})}),k&&t(bl,{pr:k,run:r,onDone:v},k.number)]})]})}const wl=Vr({id:"escalations",title:"Escalamientos",component:kl}),Or="forge.qa.project",Sl="mod-qa";function xa(){try{return localStorage.getItem(Or)??""}catch{return""}}const Cl=({projects:e,preferred:n})=>{const a=Object.keys(e).sort(),r=d=>a.includes(d)?d:a[0]??"",[o,l]=b(()=>r(n||xa()));F(()=>{a.includes(o)||l(r(n||xa()))},[a.join(`
20
+ `),n]);const c=d=>{l(d);try{localStorage.setItem(Or,d)}catch{}},s=wl.component;return i("div",{class:"flex flex-col min-h-full",children:[t(Ge,{title:"QA",subtitle:"PRs que qa-pilot escaló a una persona, con la evidencia para decidir",children:a.length>0&&i("label",{class:"inline-flex items-center gap-2",style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Proyecto",t("select",{class:"field",value:o,onChange:d=>c(d.target.value),style:{minWidth:"160px"},children:a.map(d=>t("option",{value:d,children:d},d))})]})}),t("div",{style:{padding:"18px 22px",maxWidth:"1180px",width:"100%"},children:a.length===0?t(je,{icon:"i-lucide-folder-search",title:"No hay proyectos",description:"Agrega un proyecto de CW para ver sus PRs escalados."}):t(s,{moduleId:Sl,projectId:null,cwProject:o},o)})]})},Lt=e=>e.target.value,$l=({accounts:e,onOpenSession:n,onFramesChanged:a})=>{const[r,o]=b(null),[l,c]=b(null),[s,d]=b(""),[x,g]=b(""),[v,k]=b(""),[S,y]=b(null),[w,p]=b(""),h=V(async()=>{try{const T=await(await fetch("/api/liveframe/frames")).json();c(T),a(T.length)}catch{c([])}},[a]);F(()=>{h(),fetch("/api/liveframe/status").then(T=>T.json()).then(o).catch(()=>{})},[h]);const m=async T=>{if(r)try{const R=await ke("/api/cw/start",{type:"general",account:r.account,directory:T.dir,task:`Liveframe: ${T.project}/${T.frame}`});n(R.session)}catch(R){A(we(R),"error")}},u=async(T,R)=>{try{const $=await T;return A(R,"success"),h(),await m($),!0}catch($){return A(we($),"error"),!1}},z=async()=>{await u(ke("/api/liveframe/frames",{project:s,name:x}),`Frame "${x}" created`)&&g("")},f=async()=>{await u(ke("/api/liveframe/pull",{target:v}),`Pulled ${v}`)&&k("")},P=async()=>{if(S)try{const{url:T}=await ke(`/api/liveframe/frames/${S.project}/${S.frame}/push`,{note:w});A(`Published: ${T}`,"success"),y(null)}catch(T){A(we(T),"error")}},I=r!==null&&!e.includes(r.account),N=(r==null?void 0:r.installed)!==!1&&!I,M=(l??[]).reduce((T,R)=>{var $;return(T[$=R.project]??(T[$]=[])).push(R),T},{});return i(J,{children:[i(Ge,{title:"Prototypes",subtitle:r?`Liveframe frames in ${r.root} · agents run on ${r.account}`:"Liveframe frames",children:[r&&i("a",{class:Ue,style:Ie,href:r.api,target:"_blank",rel:"noopener noreferrer",children:["Liveframe gallery ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),t(E,{label:"Refresh",variant:"secondary",onClick:h})]}),i("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[r&&!r.installed&&i("p",{style:{...de,background:Z("--red")},children:["The Liveframe CLI is not installed. Run ",i("code",{children:["npm i -g ",r.api,"/cli.tgz"]}),", then ",t("code",{children:"lf login"}),"."]}),I&&i("p",{style:{...de,background:Z("--red")},children:["Liveframe agents run on the CW account ",t("code",{children:r==null?void 0:r.account}),", which does not exist here. Add it in Accounts or set ",t("code",{children:"FORGE_LIVEFRAME_ACCOUNT"}),"."]}),(r==null?void 0:r.installed)&&!r.signedIn&&i("p",{style:{...de,background:Z("--orange")},children:["Liveframe is not signed in on this machine. Run ",t("code",{children:"lf login"})," in a terminal."]}),i("section",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(300px, 1fr))",gap:"14px"},children:[i("div",{class:"flex flex-col",style:{...We,padding:"16px 18px",gap:"12px"},children:[i("div",{children:[t("h2",{style:{fontSize:"14.5px",fontWeight:600},children:"New prototype"}),i("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Scaffolds a frame with ",t("code",{children:"lf new"})," and opens an agent in it. The frame's CLAUDE.md teaches the agent Liveframe's conventions and ",t("code",{children:"lf push"}),"."]})]}),t(U,{label:"Liveframe project · created if missing",children:t("input",{type:"text",class:"field",value:s,placeholder:"Reservas",onInput:T=>d(Lt(T))})}),t(U,{label:"Frame name",children:t("input",{type:"text",class:"field",value:x,placeholder:"Checkout ideas",onInput:T=>g(Lt(T))})}),t("div",{class:"flex justify-end",children:t(E,{label:"Create and open agent",variant:"primary",size:"sm",disabled:!N||!s.trim()||!x.trim(),onClick:z})})]}),i("div",{class:"flex flex-col",style:{...We,padding:"16px 18px",gap:"12px"},children:[i("div",{children:[t("h2",{style:{fontSize:"14.5px",fontWeight:600},children:"Continue a frame"}),i("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Pulls an existing frame's latest source with ",t("code",{children:"lf pull"})," and opens an agent in it."]})]}),t(U,{label:"project/frame",children:t("input",{type:"text",class:"field",value:v,placeholder:"reservas/checkout-flow",onInput:T=>k(Lt(T))})}),t("div",{class:"flex justify-end",children:t(E,{label:"Pull and open agent",variant:"secondary",size:"sm",disabled:!N||!v.includes("/"),onClick:f})})]})]}),l&&l.length===0&&t(je,{icon:"i-lucide-frame",title:"No frames yet",description:"Frames you create or pull here live on this machine, one folder per frame."}),Object.entries(M).map(([T,R])=>i("section",{style:{...We,overflow:"hidden"},children:[t("h2",{style:{padding:"12px 18px",fontSize:"13px",fontWeight:600,borderBottom:"1px solid var(--hair)"},children:T}),R.map($=>i("div",{class:"flex items-center flex-wrap",style:{gap:"10px",padding:"12px 18px",borderBottom:"1px solid var(--hair)"},children:[i("div",{class:"min-w-0",style:{flex:"1 1 220px"},children:[t("p",{class:"truncate",style:{fontSize:"13.5px",fontWeight:500},children:$.frame}),i("p",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-3)"},children:[$.kind," · ",$.branch," · ",$.dir]})]}),i("a",{class:Ue,style:Ie,href:$.url,target:"_blank",rel:"noopener noreferrer",children:["Live ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),t(E,{label:"Push",variant:"secondary",size:"sm",disabled:!N,onClick:()=>{p(""),y($)}}),t(E,{label:"Open agent",variant:"primary",size:"sm",disabled:!r||I,onClick:()=>m($)})]},$.dir))]},T))]}),t(He,{open:S!==null,title:`Push ${S==null?void 0:S.project}/${S==null?void 0:S.frame}`,onClose:()=>y(null),children:i("div",{class:"space-y-4",children:[i("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:["Builds the frame and deploys it as a new version with ",t("code",{children:"lf push"}),"."]}),t(U,{label:"What changed · optional",children:t("input",{type:"text",class:"field",value:w,placeholder:"wallet-first layout",onInput:T=>p(Lt(T))})}),t("div",{class:"flex justify-end pt-1",children:t(E,{label:"Push",variant:"primary",onClick:P})})]})})]})},zl=[{id:"project",label:"Project"},{id:"team",label:"Team"},{id:"personal",label:"Personal"}],De="__new";async function Xt(e,n,a,r){try{await ke(e,n),A(a,"success"),Te(!0),r()}catch(o){A(we(o),"error")}}const Nn=e=>{var n;return(((n=xe.value)==null?void 0:n.brains)??[]).filter(a=>a.onDisk&&e.includes(a.tier??""))},Dr=()=>t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:"Kioku makes it on this machine only, with no repository. Publish on its card gives it one."}),Tl=({onClose:e})=>{const[n,a]=b(""),[r,o]=b("project"),[l,c]=b(""),[s,d]=b(""),x=Nn(["team"]);return i(xt,{title:"New brain",onClose:e,children:[t("div",{class:"flex",children:t(se,{size:"sm",label:"Tier",tabs:zl,active:r,onChange:o})}),t(U,{label:"Repository · owner/repo, the one it gets once published",children:t("input",{type:"text",class:"field",value:n,placeholder:"monoku/brain-shop",onInput:g=>a(re(g))})}),r==="project"&&x.length>0&&t(On,{label:"Team brain",brains:x,value:l,onValue:c}),t(U,{label:"Language of its pages · optional",children:t("input",{type:"text",class:"field",value:s,placeholder:"en",onInput:g=>d(re(g))})}),t(Dr,{}),i("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(E,{label:"Cancel",variant:"secondary",onClick:e}),t(E,{label:"Create",variant:"primary",disabled:!n.trim(),onClick:()=>Xt("/api/kioku/brains",{repo:n,tier:r,team:l,language:s},`Made ${n.trim()}`,e)})]})]})},On=({label:e,brains:n,value:a,onValue:r,repo:o,placeholder:l,onRepo:c})=>i(J,{children:[t(U,{label:e,children:i("select",{class:"field",value:a,onChange:s=>r(re(s)),children:[t("option",{value:"",children:"None"}),n.map(s=>t("option",{value:s.key,children:ae(s)},s.key)),c&&t("option",{value:De,children:"New brain…"})]})}),c&&a===De&&t("input",{type:"text",class:"field",value:o,placeholder:l,onInput:s=>c(re(s))})]}),Rl=({project:e,onClose:n})=>{const[a,r]=b(De),[o,l]=b(""),[c,s]=b(""),[d,x]=b(""),g=(k,S)=>k===De?S.trim():k,v={brain:g(a,o),team:g(c,d)};return i(xt,{title:`A brain for ${e}`,onClose:n,children:[t(On,{label:"Project brain",brains:Nn(["project","client"]),value:a,repo:o,placeholder:`monoku/brain-${e}`,onValue:r,onRepo:l}),t(On,{label:"Team brain",brains:Nn(["team"]),value:c,repo:d,placeholder:"monoku/brain",onValue:s,onRepo:x}),i("p",{style:{...de,background:Z("--orange")},children:["Kioku writes ",t("code",{children:"kioku.yaml"})," at the root of ",e,"'s repository, naming these brains. Commit it with the code so every clone loads them."]}),(a===De||c===De)&&t(Dr,{}),i("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(E,{label:"Cancel",variant:"secondary",onClick:n}),t(E,{label:"Link",variant:"primary",disabled:!v.brain&&!v.team,onClick:()=>Xt("/api/kioku/link",{project:e,...v},`Linked ${e}`,n)})]})]})},Wr=({brain:e,onClose:n})=>{const[a,r]=b(""),[o,l]=b("");return t(He,{open:!0,title:`New area in ${ae(e)}`,onClose:n,children:i("div",{class:"flex flex-col",style:{gap:"12px"},children:[t(U,{label:"Area · a path such as payments or payments/refunds",children:t("input",{type:"text",class:"field",value:a,placeholder:"payments",onInput:c=>r(re(c))})}),t(U,{label:"What it is for · the agent reads it to choose where a page goes",children:t("input",{type:"text",class:"field",value:o,placeholder:"How money comes in and goes out",onInput:c=>l(re(c))})}),e.namespaces.length>0&&i("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Areas now: ",e.namespaces.join(", ")]}),i("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(E,{label:"Cancel",variant:"secondary",onClick:n}),t(E,{label:"Add area",variant:"primary",disabled:!a.trim()||!o.trim(),onClick:()=>Xt("/api/kioku/areas",{brain:e.key,area:a,summary:o},`Added ${a.trim()} to ${ae(e)}`,n)})]})]})})},jl=({brain:e,onClose:n})=>{const[a,r]=b(""),[o,l]=b(!1),c=ae(e);return t(He,{open:!0,title:`Publish ${c}`,onClose:n,children:i("div",{class:"flex flex-col",style:{gap:"12px"},children:[i("div",{style:{...de,background:Z("--red")},children:[i("p",{style:{fontWeight:600,marginBottom:"4px"},children:["This puts every page of ",c," on a git host."]}),t("p",{children:"Publishing a brain may need approval first, from your team, a client or your company. Whether it does, and whether you have it, is your call and your responsibility; Forge and kioku do not check."})]}),t(U,{label:"Repository address · optional",children:t("input",{type:"text",class:"field",value:a,placeholder:"git@github.com:owner/repo.git",onInput:s=>r(re(s))})}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:a.trim()?"It must be an empty repository that already exists; kioku makes nothing there.":i(J,{children:["Left empty, kioku makes a private GitHub repository for ",t("code",{children:e.key})," with ",t("code",{children:"gh"}),", unless it exists."]})}),i("label",{class:"flex items-start cursor-pointer",style:{gap:"8px",fontSize:"12.5px"},children:[t("input",{type:"checkbox",checked:o,onChange:s=>l(s.target.checked),style:{marginTop:"2px"}}),i("span",{children:["I have the approval this needs, or it needs none. Publishing ",c," is my decision."]})]}),i("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(E,{label:"Cancel",variant:"secondary",onClick:n}),t(E,{label:"Publish",variant:"destructive",disabled:!o,onClick:()=>Xt("/api/kioku/publish",{brain:e.key,to:a,understood:o},`Published ${c}`,n)})]})]})})};function Pl(e,n){const r=(n?qn(n):[]).find(o=>o.tier==="project"||o.tier==="client")??e.find(o=>o.personal)??e[0];return(r==null?void 0:r.key)??""}const Al=({project:e,onClose:n})=>{var B;const a=(((B=xe.value)==null?void 0:B.brains)??[]).filter(j=>j.onDisk),[r,o]=b(()=>Pl(a,e)),[l,c]=b(Rt[0].id),[s,d]=b(""),[x,g]=b(""),[v,k]=b(""),[S,y]=b({}),[w,p]=b(null),[h,m]=b(!1),[u,z]=b(!1),f=a.find(j=>j.key===r),P=(f==null?void 0:f.namespaces)??[],I=P.length===1?P[0]:s,N=Rt.find(j=>j.id===l)??Rt[0],M=N.sections.length===0,T=M?["Text"]:N.sections,R=!!(f&&I&&x.trim()&&v.trim()&&T.every(j=>{var D;return(D=S[j])==null?void 0:D.trim()})),$=async(j=!1)=>{if(!f||!R||h)return;m(!0);const D=M?`${(S.Text??"").trim()}
21
+ `:N.sections.map(W=>`## ${W}
22
+
23
+ ${(S[W]??"").trim()}
24
+ `).join(`
25
+ `);try{const W=await ke("/api/kioku/pages",{brain:f.key,type:l,title:x,summary:v,body:D,namespace:I,create:j});W.status==="similar"?p(W.similar):W.status==="namespace"?A(`Pick an area of ${ae(f)}`,"error"):(A(`Saved to ${W.brain}: ${W.path}`,"success"),Te(!0),n())}catch(W){A(we(W),"error")}finally{m(!1)}};return i(xt,{title:"New memory",onClose:n,children:[t(U,{label:"Brain",children:t("select",{class:"field",value:r,onChange:j=>{o(re(j)),d(""),p(null)},children:a.map(j=>i("option",{value:j.key,children:[ae(j)," · ",j.tier]},j.key))})}),f&&P.length===0&&i("div",{class:"flex items-center",style:{...de,gap:"12px",background:Z("--orange")},children:[i("span",{class:"flex-1",children:[ae(f)," has no areas yet. Each page goes in one, and a person names them."]}),t(E,{label:"Add area",variant:"secondary",size:"sm",onClick:()=>z(!0)})]}),P.length>1&&t(U,{label:"Area",children:i("select",{class:"field",value:s,onChange:j=>d(re(j)),children:[t("option",{value:"",children:"Choose…"}),P.map(j=>t("option",{value:j,children:j},j))]})}),t("div",{class:"flex",children:t(se,{size:"sm",label:"Page type",tabs:Rt.map(j=>({id:j.id,label:j.label})),active:l,onChange:j=>{c(j),p(null)}})}),t(U,{label:"Title",children:t("input",{type:"text",class:"field",value:x,placeholder:"Payments retry at most three times",onInput:j=>{g(re(j)),p(null)}})}),t(U,{label:"Summary · one line the agent reads first",children:t("input",{type:"text",class:"field",value:v,onInput:j=>k(re(j))})}),T.map(j=>t(U,{label:j,children:t("textarea",{class:"field",rows:j==="Text"?8:3,value:S[j]??"",onInput:D=>y(W=>({...W,[j]:re(D)}))})},`${l}:${j}`)),w&&i("div",{style:{...de,background:Z("--orange")},children:[i("p",{style:{fontWeight:600,marginBottom:"6px"},children:[f?ae(f):"The brain"," already has pages on this:"]}),t("ul",{class:"flex flex-col",style:{gap:"4px",paddingLeft:"16px",listStyle:"disc"},children:w.map(j=>i("li",{children:[t("b",{children:j.title}),j.summary?` — ${j.summary}`:""]},j.path))}),t("p",{style:{marginTop:"6px",color:"var(--ink-2)"},children:"Save it anyway to keep both; kioku links them under See also."})]}),(f==null?void 0:f.remote)&&i("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Kioku commits to ",ae(f),"'s main branch and pushes it; it has no review step."]}),i("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(E,{label:"Cancel",variant:"secondary",onClick:n}),t(E,{label:w?"Save anyway":"Save",variant:"primary",disabled:!R||h,onClick:()=>$(w!==null)})]}),u&&f&&t(Wr,{brain:f,onClose:()=>z(!1)})]})},Il=[{label:"Personal",tiers:["personal"]},{label:"Projects",tiers:["project","client"]},{label:"Team",tiers:["team"]}],Ll={save:"--green",update:"--blue",supersede:"--blue",evolve:"--purple",link:"--teal",confirm:"--green",retire:"--red",forget:"--red"},El=({brain:e})=>{const n=Object.entries(e.kinds).filter(([,a])=>a>0).sort((a,r)=>r[1]-a[1]);return i(J,{children:[t("div",{class:"flex overflow-hidden",style:{height:"6px",borderRadius:"99px",background:"var(--elev)"},children:n.map(([a,r])=>t("span",{title:`${a} ${r}`,style:{width:`${r/e.pages*100}%`,background:`var(${na(a)})`}},a))}),t("div",{class:"flex flex-wrap",style:{gap:"3px 10px",fontSize:"11px",color:"var(--ink-2)"},children:n.slice(0,3).map(([a,r])=>i("span",{class:"inline-flex items-center",style:{gap:"4px"},children:[t(Se,{color:`var(${na(a)})`}),a," ",r]},a))})]})},ma={fontSize:"11.5px",fontWeight:500,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},va=({brain:e,usedBy:n,showTier:a,onDialog:r})=>{const o=Be(e.tier);return i("div",{class:"flex flex-col min-w-0",style:{...We,gap:"9px",padding:"14px 16px",borderTop:`3px solid var(${o})`},children:[i("div",{class:"flex items-center",style:{gap:"8px"},children:[a&&t("span",{style:{fontSize:"10.5px",fontWeight:700,letterSpacing:".04em",textTransform:"uppercase",color:`var(${o})`},children:e.tier}),t("span",{class:"truncate",style:{fontSize:"14.5px",fontWeight:600},title:e.folder,children:ae(e)}),t("span",{class:"flex-1"}),t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:e.onDisk?e.touched?Jt(e.touched):"quiet":"not on disk"})]}),i("div",{style:{fontSize:"26px",fontWeight:700,lineHeight:1},children:[e.pages," ",t("span",{style:{fontSize:"12px",fontWeight:400,color:"var(--ink-3)"},children:"pages"})]}),e.pages>0&&t(El,{brain:e}),n&&t("div",{class:"flex flex-wrap",style:{gap:"4px"},children:e.tier==="personal"?t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"loads in every session"}):n.length===0?t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"no CW project loads it"}):n.map(l=>t(Ta,{label:l,variant:"neutral"},l))}),e.onDisk&&i("div",{class:"flex items-center",style:{gap:"12px",paddingTop:"8px",marginTop:"auto",borderTop:"1px solid var(--hair)"},children:[t("button",{type:"button",style:ma,onClick:()=>r({kind:"area",brain:e}),children:"+ Area"}),t("span",{class:"flex-1"}),!e.remote&&i(J,{children:[t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"only on this machine"}),t("button",{type:"button",style:ma,onClick:()=>r({kind:"publish",brain:e}),children:"Publish…"})]})]})]})},Nl=({writes:e})=>i("section",{style:{...We,overflow:"hidden"},children:[t("h2",{style:{padding:"12px 16px 6px",fontSize:"11px",fontWeight:600,letterSpacing:".02em",color:"var(--ink-3)"},children:"RECENT ACTIVITY · LAST 2 WEEKS"}),e.length===0&&t("p",{style:{padding:"4px 16px 14px",fontSize:"12.5px",color:"var(--ink-3)"},children:"Nothing written lately."}),e.map(n=>i("div",{class:"flex items-center",style:{gap:"10px",padding:"9px 16px",borderTop:"1px solid var(--hair)",fontSize:"12.5px"},children:[t("span",{class:"shrink-0 flex justify-center",style:{width:"76px"},children:t(Ta,{label:n.verb,color:`var(${Ll[n.verb]??"--ink-2"})`})}),t("span",{class:"truncate flex-1",title:n.path,children:n.title}),i("span",{class:"shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[n.brain,n.author?` · ${n.author}`:""," · ",Jt(n.date)]})]},`${n.brain}:${n.path}:${n.date}:${n.verb}`))]}),Ol=({project:e,onProject:n})=>{const[a,r]=b(!1),[o,l]=b(null),c=()=>l(null);F(()=>cr(),[]);const s=xe.value,d=async()=>{const m=window.open("","_blank");r(!0);try{const{address:u}=await ke("/api/kioku/viewer",{});m?m.location.href=u:A(`Viewer running at ${u}`,"info"),Te()}catch(u){m==null||m.close(),A(we(u),"error")}finally{r(!1)}},x=async()=>{await fetch("/api/kioku/viewer",{method:"DELETE"}).catch(()=>{}),Te()},g=(s==null?void 0:s.brains)??[],v=(s==null?void 0:s.projects)??{},k=Object.keys(v).filter(m=>v[m].some(u=>u.tier!=="personal")).sort();e&&!k.includes(e)&&k.unshift(e);const S=e?qn(e):[],y=m=>Object.keys(v).filter(u=>v[u].some(z=>z.name===ae(m))).sort(),w=new Set(S.map(ae)),p=((s==null?void 0:s.activity)??[]).filter(m=>!e||w.has(m.brain)).slice(0,15),h=s!=null&&s.installed?e?`${e} · ${Ut(S)} pages its sessions can recall`:`Kioku ${s.version??""} · ${Ut(g)} pages in ${g.length} brain${g.length===1?"":"s"}`:"Kioku brains on this machine";return i(J,{children:[i(Ge,{title:"Memory",subtitle:h,children:[(s==null?void 0:s.viewer)&&t(E,{label:"Stop viewer",variant:"secondary",onClick:x}),t(E,{label:"Refresh",variant:"secondary",onClick:()=>Te(!0)}),t(E,{label:"New brain",variant:"secondary",disabled:!(s!=null&&s.installed),onClick:()=>l({kind:"brain"})}),t(E,{label:"New memory",variant:"secondary",disabled:!g.some(m=>m.onDisk),onClick:()=>l({kind:"memory"})}),t(E,{label:s!=null&&s.viewer?"Viewer open ↗":"Open viewer",variant:"primary",disabled:!(s!=null&&s.installed)||a,onClick:d})]}),i("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[s&&!s.installed&&i("p",{style:{...de,background:Z("--red")},children:["Kioku is not installed. Install it from ",t("code",{children:"monoku/kioku"})," with its ",t("code",{children:"install.sh"}),", which puts ",t("code",{children:"kioku"})," in ",t("code",{children:"~/.local/bin"}),"."]}),(s==null?void 0:s.installed)&&g.length===0&&t(je,{icon:"i-lucide-brain",title:"No brains yet",description:"New brain makes one on this machine: a personal one for what you learn anywhere, a project or team one to share."}),g.length>0&&k.length>0&&t("div",{class:"flex",children:t(se,{size:"sm",label:"Project",tabs:[{id:"",label:"All"},...k.map(m=>({id:m,label:m}))],active:e??"",onChange:m=>n(m||null)})}),g.length>0&&!e&&t("div",{class:"flex flex-wrap",style:{gap:"14px 12px"},children:Il.map(m=>{const u=g.filter(z=>m.tiers.includes(z.tier??""));return u.length===0?null:i("section",{class:"flex flex-col min-w-0",style:{gap:"8px",flex:`${u.length} 1 ${u.length*250}px`},children:[i("h2",{class:"flex items-center",style:{gap:"8px",fontSize:"11px",fontWeight:600,letterSpacing:".03em",color:`var(${Be(m.tiers[0])})`},children:["● ",m.label.toUpperCase(),u.length>1&&t("span",{style:{color:"var(--ink-3)"},children:u.length})]}),t("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:"12px"},children:u.map(z=>t(va,{brain:z,usedBy:y(z),onDialog:l},z.key))})]},m.label)})}),e&&S.length>0&&t("div",{class:"grid items-center",style:{gridTemplateColumns:S.map(()=>"minmax(0, 1fr)").join(" 24px ")},children:S.map((m,u)=>i(_r,{children:[u>0&&t("span",{style:{textAlign:"center",color:"var(--ink-3)",fontSize:"16px"},children:"→"}),t(va,{brain:m,showTier:!0,onDialog:l})]},m.key))}),e&&(s==null?void 0:s.installed)&&!S.some(m=>m.tier!=="personal")&&i("div",{class:"flex items-center",style:{...de,gap:"12px",background:"var(--elev)",color:"var(--ink-2)"},children:[i("span",{class:"flex-1",children:[e," has no project or team brain, so its sessions recall only yours."]}),t(E,{label:"Give it a brain",variant:"secondary",size:"sm",onClick:()=>l({kind:"link"})})]}),g.length>0&&t(Nl,{writes:p}),(s==null?void 0:s.installed)&&i("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Open viewer starts ",t("code",{children:"kioku web"}),": the graph of every page, each page with its history, lint and the latest changes. It opens in its own tab and stops with Forge."]})]}),(o==null?void 0:o.kind)==="memory"&&t(Al,{project:e,onClose:c}),(o==null?void 0:o.kind)==="brain"&&t(Tl,{onClose:c}),(o==null?void 0:o.kind)==="link"&&e&&t(Rl,{project:e,onClose:c}),(o==null?void 0:o.kind)==="area"&&t(Wr,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="publish"&&t(jl,{brain:o.brain,onClose:c})]})},gt=Y(null);function Dl(e,n){var a;return(a=gt.value)==null||a.resolve(!1),new Promise(r=>{gt.value={confirmation:e,module:n,resolve:r}})}const gn=e=>{const n=gt.value;gt.value=null,n==null||n.resolve(e)},Wl=()=>{var a;const e=gt.value;if(!e)return null;const{confirmation:n}=e;return i(He,{open:!0,title:n.title,onClose:()=>gn(!1),footer:i(J,{children:[i("span",{class:"flex-1",style:{fontSize:"12px",color:"var(--ink-3)"},children:[e.module," asks for this"]}),t(E,{label:"Cancel",variant:"secondary",onClick:()=>gn(!1)}),t(E,{label:n.confirmLabel,variant:"destructive",onClick:()=>gn(!0)})]}),children:[n.body&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)",whiteSpace:"pre-wrap",marginBottom:(a=n.items)!=null&&a.length?"12px":0},children:n.body}),n.items&&n.items.length>0&&t("ul",{class:"flex flex-col",style:{gap:"8px"},children:n.items.map((r,o)=>i("li",{style:{padding:"9px 11px",borderRadius:"10px",background:"var(--card)",border:"1px solid var(--hair)"},children:[t("div",{style:{fontSize:"13px",fontWeight:600},children:r.label}),r.detail&&t("div",{style:{marginTop:"4px",fontSize:"12.5px",color:"var(--ink-2)",whiteSpace:"pre-wrap"},children:r.detail})]},o))})]})},Et=e=>`/api/modules/${encodeURIComponent(e)}`;async function xn(e){const n=await e.json().catch(()=>({}));throw new Bt(n.code??`http_${e.status}`,n.message??n.error??`Request failed (${e.status})`)}const ya=(e,n)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});async function Ml(e,n){var l,c;const a=e.body.getReader(),r=new TextDecoder;let o="";for(;;){const{value:s,done:d}=await a.read();if(d)break;o+=r.decode(s,{stream:!0});let x;for(;(x=o.indexOf(`
26
+
27
+ `))>=0;){const g=o.slice(0,x);o=o.slice(x+2);const v=(l=/^event: (.*)$/m.exec(g))==null?void 0:l[1],k=JSON.parse(((c=/^data: (.*)$/m.exec(g))==null?void 0:c[1])??"null");if(v==="output"&&k.chunk&&n(k.chunk),v==="done")return k.result;if(v==="error")throw new Bt(k.code??"module_error",k.message??"action failed")}}throw new Bt("module_error","the action stream ended early")}function Fl(e,n,a){const r=Y({}),o=async()=>{const c=await fetch(`${Et(e)}/settings`);c.ok&&(r.value=await c.json())};o();const l=async(c,s,d,x)=>{const g=`${Et(e)}/actions/${encodeURIComponent(c)}${x?"/stream":""}`,v=await ya(g,{input:s,token:d});return v.status===409?{needsConfirmation:!0}:v.ok?x?{result:await Ml(v,x)}:{result:(await v.json()).result}:xn(v)};return{settings:r,status:$a(()=>$e.value.find(c=>c.id===e)),openSettings:a,reloadSettings:o,async route(c,s){const d=await fetch(`${Et(e)}${c.startsWith("/")?c:`/${c}`}`,{method:(s==null?void 0:s.method)??((s==null?void 0:s.body)===void 0?"GET":"POST"),headers:(s==null?void 0:s.body)===void 0?void 0:{"Content-Type":"application/json"},body:(s==null?void 0:s.body)===void 0?void 0:JSON.stringify(s.body)});return d.ok?await d.json():xn(d)},async action(c,s,d){var y,w,p;if(((p=(w=(y=$e.value.find(h=>h.id===e))==null?void 0:y.actions)==null?void 0:w.find(h=>h.id===c))==null?void 0:p.effect)!=="external"){const h=await l(c,s,void 0,d==null?void 0:d.onOutput);if(!("needsConfirmation"in h))return h.result}const g=await ya(`${Et(e)}/actions/${encodeURIComponent(c)}/prepare`,{input:s});if(!g.ok)return xn(g);const{confirmation:v,token:k}=await g.json();if(!await Dl(v,n()))return;const S=await l(c,s,k,d==null?void 0:d.onOutput);if("needsConfirmation"in S)throw new Bt("confirmation_required","The confirmation expired; try again");return S.result}}}const Dn=({value:e,onChange:n,initialPath:a,requireGit:r=!0})=>{const[o,l]=b(a??"~"),[c,s]=b(o),[d,x]=b([]),[g,v]=b(null),[k,S]=b(null),[y,w]=b(""),[p,h]=b(!1),[m,u]=b(!1),[z,f]=b(null);F(()=>{let j=!1;return(async()=>{u(!0),f(null);try{const H=await(await fetch(`/api/cw/browse-dirs?path=${encodeURIComponent(o)}`)).json();if(j)return;if(!H.ok){f(H.error??"Failed to load directory"),x([]);return}x(H.entries??[]),v(H.parent??null),S(H.home??null),w(H.path??o),h(!!H.isGitRepo)}catch{j||(f("Network error"),x([]))}finally{j||u(!1)}})(),()=>{j=!0}},[o]);const P=j=>{l(j),s(j)},I=e===y,N=r&&!p,M=y?k&&y===k?"~":k&&y.startsWith(k+"/")?"~"+y.slice(k.length):y:o,T={width:"24px",height:"24px",borderRadius:"7px",border:0,background:"var(--card)",color:"var(--ink-2)",boxShadow:"var(--shadow-s)"},R="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev disabled:cursor-not-allowed disabled:opacity-60",$={gap:"8px",padding:"7px 11px",border:0,borderBottom:"1px solid var(--hair)",background:"none",color:"var(--ink)",fontSize:"12.5px"},B={padding:"1px 7px",borderRadius:"99px",background:Z("--green"),color:"var(--green)",fontSize:"10.5px",fontWeight:600};return i("div",{style:{borderRadius:"12px",border:"1px solid var(--hair)",background:"var(--card)",boxShadow:"var(--shadow-s)",overflow:"hidden"},children:[i("div",{class:"flex items-center",style:{gap:"6px",padding:"7px 9px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},children:[t("button",{type:"button",class:"grid place-items-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:T,onClick:()=>g&&P(g),disabled:!g||m,title:"Parent folder","aria-label":"Parent folder",children:"←"}),t("button",{type:"button",class:"grid place-items-center cursor-pointer",style:T,onClick:()=>P("~"),title:"Home","aria-label":"Home",children:"~"}),t("input",{type:"text",value:c,"aria-label":"Path",onInput:j=>s(j.target.value),onBlur:()=>l(c),onKeyDown:j=>{j.key==="Enter"&&l(c)},class:"field mono flex-1 min-w-0",style:{height:"26px",padding:"0 9px",borderRadius:"7px",border:"1px solid var(--hair)",background:"var(--bg-2)",color:"var(--ink)",fontSize:"11.5px",outline:"none"},placeholder:"~/workspace"})]}),e&&i("div",{class:"flex items-center",style:{gap:"8px",padding:"7px 11px",borderBottom:"1px solid var(--hair)",background:Z("--blue",12),fontSize:"12px"},children:[t("span",{class:"i-lucide-check shrink-0",style:{width:"13px",height:"13px",color:"var(--blue)"}}),t("span",{class:"mono flex-1 truncate",children:e}),t("button",{type:"button",class:"grid place-items-center cursor-pointer text-ink3 hover:text-ink",style:{border:0,background:"none"},onClick:()=>n("",!1),title:"Clear selection","aria-label":"Clear selection",children:t("span",{class:"i-lucide-x",style:{width:"13px",height:"13px"}})})]}),t("div",{class:"overflow-y-auto",style:{maxHeight:"220px"},children:m?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:"Loading…"}):z?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--red)"},children:z}):i(J,{children:[i("button",{type:"button",class:R,style:{...$,background:I?"var(--elev)":"none",fontWeight:600},onClick:()=>n(y,p),disabled:N,title:N?"Not a git repository":"Pick this folder",children:[t("span",{class:"i-lucide-check shrink-0",style:{width:"12px",height:"12px",color:"var(--blue)"}}),i("span",{class:"flex-1 truncate",children:["Pick ",t("span",{class:"mono",children:M})]}),p?t("span",{style:B,children:"git"}):N?t("span",{style:{fontSize:"11px",color:"var(--ink-3)"},children:"no .git"}):null]}),d.length===0?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-3)"},children:"No subfolders"}):d.map(j=>i("button",{type:"button",class:R,style:$,onClick:()=>P(j.path),children:[t("span",{class:"i-lucide-chevron-right shrink-0",style:{width:"12px",height:"12px",color:"var(--ink-3)"}}),t("span",{class:"mono flex-1 truncate",children:j.name}),j.isGitRepo&&t("span",{style:B,children:"git"})]},j.path))]})})]})},Mr={fontSize:"11.5px",color:"var(--red)"},ba=e=>e.type==="boolean"||e.type==="string"&&e.format==="path",ka=({def:e,value:n,projects:a,onChange:r})=>e.type==="boolean"?t(Mn,{checked:n===!0,onChange:r,label:e.label}):e.type==="enum"?t("select",{class:"field",value:typeof n=="string"?n:"",onChange:o=>r(re(o)),children:e.values.map(o=>t("option",{value:o,children:o},o))}):e.type==="number"?t("input",{type:"number",class:"field",value:typeof n=="number"?n:"",min:e.min,max:e.max,onInput:o=>{const l=re(o);r(l===""?void 0:Number(l))}}):e.format==="cw-project"?i("select",{class:"field",value:typeof n=="string"?n:"",onChange:o=>r(re(o)||void 0),children:[t("option",{value:"",children:"None"}),a.map(o=>t("option",{value:o,children:o},o))]}):e.format==="path"?t(Dn,{value:typeof n=="string"?n:"",onChange:o=>r(o),requireGit:!1}):t("input",{type:e.format==="url"?"url":"text",class:"field",value:typeof n=="string"?n:"",onInput:o=>r(re(o))}),wa=({def:e,error:n,plain:a,children:r})=>i(U,{plain:a,label:i(J,{children:[e.label??"",e.required?" *":""]}),children:[r,e.help&&t("span",{style:Ce,children:e.help}),n&&t("span",{style:Mr,children:n})]}),Bl=({moduleId:e,displayName:n,schema:a,onClose:r,onSaved:o})=>{const[l,c]=b(null),[s,d]=b({}),[x,g]=b([]),[v,k]=b(!1),S=`/api/modules/${encodeURIComponent(e)}/settings`;F(()=>{fetch(S).then(h=>h.json()).then(c).catch(()=>c({})),fetch("/api/cw/projects").then(h=>h.json()).then(h=>g(Object.keys(h))).catch(()=>{})},[S]);const y=(h,m)=>c(u=>({...u,[h]:m})),w=(h,m,u,z)=>c(f=>{const P=[...(f==null?void 0:f[h])??[]];return P[m]={...P[m],[u]:z},{...f,[h]:P}}),p=async()=>{k(!0);try{const h=await fetch(S,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(h.status===400){const{errors:m}=await h.json();d(Object.fromEntries(m.map(u=>[u.path,u.message])));return}if(!h.ok)throw new Error(`Saving failed (${h.status})`);d({}),A(`${n} settings saved`,"success"),o(),r()}catch(h){A(we(h),"error")}finally{k(!1)}};return t(xt,{title:`${n} settings`,onClose:r,children:l?i("div",{class:"flex flex-col",style:{gap:"14px"},children:[Object.entries(a).map(([h,m])=>{if(m.type!=="list")return t(wa,{def:{...m,label:m.label??h},error:s[h],plain:ba(m),children:t(ka,{def:m,value:l[h],projects:x,onChange:z=>y(h,z)})},h);const u=l[h]??[];return i("div",{class:"flex flex-col",style:{gap:"10px"},children:[t("span",{style:{...Ce,fontWeight:600},children:m.label??h}),m.help&&t("span",{style:Ce,children:m.help}),s[h]&&t("span",{style:Mr,children:s[h]}),u.map((z,f)=>i("div",{class:"flex flex-col",style:{gap:"10px",padding:"12px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},children:[Object.entries(m.item).map(([P,I])=>t(wa,{def:{...I,label:I.label??P},error:s[`${h}[${f}].${P}`],plain:ba(I),children:t(ka,{def:I,value:z[P],projects:x,onChange:N=>w(h,f,P,N)})},P)),t("div",{children:t(E,{label:"Remove",variant:"danger",size:"sm",onClick:()=>c(P=>({...P,[h]:u.filter((I,N)=>N!==f)}))})})]},f)),t("div",{children:t(E,{label:`Add ${(m.label??h).replace(/s$/,"").toLowerCase()}`,icon:"i-lucide-plus",variant:"secondary",size:"sm",onClick:()=>y(h,[...u,{}])})})]},h)}),i("div",{class:"flex",style:{gap:"8px",marginTop:"6px"},children:[t("span",{class:"flex-1"}),t(E,{label:"Cancel",variant:"secondary",onClick:r}),t(E,{label:"Save",loading:v,onClick:p})]})]}):t("div",{class:"text-ink2",style:{fontSize:"13px"},children:"Loading…"})})};class _l extends Kr{constructor(){super(...arguments);Xn(this,"state",{error:null})}componentDidCatch(a){this.setState({error:a})}render(){const{error:a}=this.state;return a?t(Wn,{title:`${this.props.name}'s view crashed`,message:a.message,onReload:()=>{this.setState({error:null}),this.props.onReload()}}):this.props.children}}const Wn=({title:e,message:n,onReload:a})=>i("div",{style:{margin:"24px 22px",padding:"16px 18px",borderRadius:"14px",background:"var(--card)",border:"1px solid color-mix(in srgb, var(--red) 45%, var(--hair))"},children:[t("div",{style:{fontSize:"14px",fontWeight:600,color:"var(--red)"},children:e}),t("pre",{class:"mono",style:{marginTop:"8px",fontSize:"12px",color:"var(--ink-2)",whiteSpace:"pre-wrap"},children:n}),t("div",{style:{marginTop:"12px"},children:t(E,{label:"Reload view",variant:"secondary",size:"sm",onClick:a})})]}),mn=new Map;function Kl(e){const n=`${e.view.url}?v=${encodeURIComponent(e.view.version)}`;let a=mn.get(n);return a||(a=import(n).then(r=>{if(!r.default||typeof r.default.component!="function")throw new Error("view.js must default-export definePanel({...})");return r.default}),a.catch(()=>mn.delete(n)),mn.set(n,a)),a}const Ul=({moduleId:e,cwProject:n,onBack:a})=>{var u,z,f,P;const r=$e.value.find(I=>I.id===e),[o,l]=b(!1),[c,s]=b(null),[d,x]=b(0),g=oe(e);r&&(g.current=r.displayName);const v=g.current,k=ee(()=>Fl(e,()=>g.current,()=>l(!0)),[e]),S=(r==null?void 0:r.state)==="enabled"?(u=r.view)==null?void 0:u.version:void 0,y=((z=Ya.value[e])==null?void 0:z.attention)??0;F(()=>{y>0&&Po(e)},[e,y]),F(()=>{if(!r||!S)return;let I=!0;return Kl(r).then(N=>{I&&s({version:S,config:N})},N=>{I&&s({version:S,error:N.message})}),()=>{I=!1}},[e,S,d]);const w=r?Ja(r):null,p=i(Ge,{title:((f=r==null?void 0:r.view)==null?void 0:f.title)??v,subtitle:r?`${r.name} ${r.version}`:void 0,children:[w&&i("span",{class:"mono truncate",title:w,style:{maxWidth:"320px",fontSize:"11.5px",color:"var(--orange)"},children:["⚠ ",w]}),(r==null?void 0:r.settingsSchema)&&Object.keys(r.settingsSchema).length>0&&t(E,{label:"Settings",icon:"i-lucide-settings",variant:"secondary",size:"sm",onClick:()=>l(!0)})]});if(!r)return i("div",{children:[p,t("div",{style:{padding:"56px 22px"},children:t(je,{icon:"i-lucide-package-x",title:`${v} was removed`,description:"The module is no longer installed.",action:{label:"Back to Tasks",onClick:a}})})]});if(r.state!=="enabled")return i("div",{children:[p,t(Wn,{title:`${v} is disabled`,message:r.reason??"No reason given",onReload:()=>{pt()}})]});const h=c&&c.version===S?c:null,m=(P=h==null?void 0:h.config)==null?void 0:P.component;return i("div",{children:[p,h!=null&&h.error?t(Wn,{title:`${v}'s view did not load`,message:h.error,onReload:()=>x(I=>I+1)}):m?t(_l,{name:v,onReload:()=>x(I=>I+1),children:t(m,{moduleId:e,projectId:null,cwProject:n,forge:k})},`${S}-${d}`):i("div",{class:"py-20 text-center text-ink2",children:["Loading ",v,"…"]}),o&&r.settingsSchema&&t(Bl,{moduleId:e,displayName:v,schema:r.settingsSchema,onClose:()=>l(!1),onSaved:()=>{k.reloadSettings(),pt()}})]})},Hl=({open:e,accounts:n,onClose:a,onCreated:r})=>{const[o,l]=b("create"),[c,s]=b(""),[d,x]=b(""),[g,v]=b(""),[k,S]=b(""),[y,w]=b(""),[p,h]=b(""),[m,u]=b(!1),[z,f]=b(""),[P,I]=b(!1);F(()=>{e&&n.length>0&&!c&&s(n[0])},[e,n]),F(()=>{e||(l("create"),x(""),v(""),S(""),w(""),h(""),u(!1),f(""),I(!1))},[e]);const N=c.trim().length>0&&d.trim().length>0&&k.trim().length>0,M=c.trim().length>0&&p.length>0&&m,T=async()=>{if(N){I(!0);try{const W=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"create",project:d.trim(),task:d.trim(),description:k.trim(),account:c.trim()||void 0,directory:g.trim()||void 0,model:y||void 0})})).json();W.ok?(A("Project creation started in terminal","success"),r(W.session)):A(W.error??"Failed to create project","error")}catch{A("Failed to create project","error")}finally{I(!1)}}},R=async()=>{if(M){I(!0);try{const W=await(await fetch("/api/cw/register-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p,account:c.trim(),alias:z.trim()||void 0})})).json();W.ok?(A(`Project "${W.project}" registered`,"success"),r()):A(W.error??"Failed to register project","error")}catch{A("Failed to register project","error")}finally{I(!1)}}},$=o==="create";return t(He,{open:e,title:"Add a project",onClose:a,footer:i(J,{children:[t("span",{class:"mono flex-1 truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:$?"cw create":"cw project register"}),t(E,{label:"Cancel",variant:"secondary",onClick:a}),t(E,{label:$?P?"Creating…":"Create":P?"Registering…":"Register",variant:"primary",loading:P,disabled:!($?N:M),onClick:$?T:R})]}),children:i("div",{class:"flex flex-col",style:{gap:"13px"},children:[t(se,{fill:!0,label:"Mode",tabs:[{id:"create",label:"Create new"},{id:"existing",label:"Register existing"}],active:o,onChange:D=>l(D)}),i("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:"10px"},children:[t(U,{label:"Account",children:n.length>0?t("select",{class:"field",value:c,onChange:D=>s(D.target.value),children:n.map(D=>t("option",{value:D,children:D},D))}):t("input",{type:"text",class:"field",value:c,placeholder:"account-name",onInput:D=>s(D.target.value)})}),$?t(U,{label:"Project name",children:t("input",{type:"text",class:"field",value:d,placeholder:"my-new-project",onInput:D=>x(D.target.value)})}):t(U,{label:"Alias",children:t("input",{type:"text",class:"field",value:z,placeholder:"defaults to folder name",onInput:D=>f(D.target.value)})})]}),i("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:Ce,children:$?"Parent folder · optional":"Repository · must contain .git"}),$?t(Dn,{value:g,onChange:v,requireGit:!1},"dir-create"):t(Dn,{value:p,onChange:(D,W)=>{h(D),u(W)}},"dir-existing")]}),$&&i(J,{children:[t(U,{label:"Description",children:t("textarea",{rows:2,class:"field",value:k,placeholder:"A SaaS platform for…",onInput:D=>S(D.target.value)})}),i("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:Ce,children:"Model"}),t(se,{size:"sm",label:"Model",tabs:[{id:"",label:"Auto"},{id:"haiku",label:"Haiku"},{id:"sonnet",label:"Sonnet"},{id:"opus",label:"Opus"}],active:y,onChange:w})]})]})]})})},ql=(e,n)=>{if(n)return{kind:"connecting"};const a=typeof e.detail=="string"?e.detail:"",r=[e.provider,e.model].filter(Boolean).join(" · ");if(e.status==="not_installed")return{kind:"not_installed",detail:a};if(e.status==="error")return{kind:"error",detail:a};if(e.status==="local"){const o=e.detail&&typeof e.detail=="object"?e.detail:null;return{kind:"local",providerModel:r,reachable:(o==null?void 0:o.reachable)??null,pulled:(o==null?void 0:o.model_pulled)??null}}return e.status==="connected"&&(e.provider_kind==="api"||e.has_api_key)?{kind:"api_key",providerModel:e.provider!=="native"?r:null}:e.status==="connected"?{kind:"connected"}:{kind:"connect"}},Gl=(e,n,a,r)=>{const o=[];switch(e.kind){case"connecting":o.push("Waiting for the login to finish");break;case"not_installed":o.push(e.detail||"Not on PATH");break;case"error":o.push(e.detail||"cw doctor reported an error");break;case"local":{const l=[e.reachable===null?null:e.reachable?"reachable":"unreachable",e.pulled===null?null:e.pulled?"model pulled":"model not pulled"].filter(Boolean).join(", ");o.push(...[e.providerModel,l].filter(Boolean));break}case"api_key":o.push(...[e.providerModel,"stored by cw"].filter(l=>!!l));break;case"connected":o.push(...[r.model,n].filter(l=>!!l)),o.length===0&&o.push("Signed in");break;case"connect":o.push(a?"Not logged in — device code, no terminal needed":"Not logged in");break}return r.unofficial&&o.push("unofficial"),o.join(" · ")},Ne=({token:e,label:n})=>i("span",{class:"inline-flex items-center shrink-0 whitespace-nowrap",style:{gap:"6px",padding:"3px 10px",borderRadius:"99px",fontSize:"11.5px",fontWeight:600,background:e?Z(e):"var(--elev)",color:e?`var(${e})`:"var(--ink-3)"},children:[t("span",{style:{width:"6px",height:"6px",borderRadius:"50%",background:"currentColor"}}),n]}),Vl=({view:e,onConnect:n,onCancel:a})=>{switch(e.kind){case"connecting":return i("span",{class:"inline-flex items-center shrink-0",style:{gap:"8px"},children:[t(Ne,{token:"--blue",label:"Connecting…"}),t("button",{type:"button",class:"cursor-pointer hover:text-ink",style:{border:0,background:"none",color:"var(--ink-2)",fontSize:"12px"},onClick:a,children:"Cancel"})]});case"not_installed":return t(Ne,{token:null,label:"Not installed"});case"error":return t(Ne,{token:"--red",label:"Error"});case"local":return t(Ne,{token:"--orange",label:"Local"});case"api_key":return t(Ne,{token:"--green",label:"API key"});case"connected":return t(Ne,{token:"--green",label:"Connected"});case"connect":return t(E,{label:"Connect",size:"sm",onClick:n})}},vn=({children:e})=>i("div",{class:"flex",style:{padding:"0 15px 11px"},children:[t("span",{class:"shrink-0",style:{width:"144px"}}),t("span",{class:"flex flex-col flex-1",style:{gap:"5px",minWidth:0},children:e})]}),yn=({warn:e,children:n})=>t("span",{style:{fontSize:"11.5px",color:e?"var(--orange)":"var(--ink-3)"},children:n}),Jl=({account:e,harness:n})=>{const a=vo(e,n);return!a||a.state==="not_connected"?null:a.state==="expired"?t(vn,{children:t(yn,{warn:!0,children:"Reconnect to see usage limits"})}):a.state==="error"?t(vn,{children:i(yn,{children:["Limits unavailable — ",a.detail??"the request failed"]})}):a.windows.length===0?null:i(vn,{children:[t(za,{bars:Ea(a.windows)}),a.stale&&i(yn,{children:["Last known values — ",a.detail??"the refresh failed"]})]})},Yl=3e3,Ql=({account:e,harness:n,canUseApiKey:a,onConnected:r,onClose:o})=>{const[l,c]=b(null),[s,d]=b(!1),[x,g]=b(0),[v,k]=b(""),[S,y]=b(!1),w=ue(n).label,p=`/api/cw/accounts/${encodeURIComponent(e)}`,h=`${p}/login/${encodeURIComponent(n)}`,m=oe(!1),u=oe(!1);F(()=>{let I=!1,N=null;c(null),d(!1),m.current=!1,u.current=!1;const M=()=>{m.current||(m.current=!0,fetch(h,{method:"DELETE"}).catch(()=>{}),A(`${e} is connected to ${w}`,"success"),r())},T=async()=>{var D;const $=await fetch(h).catch(()=>null);if(!($!=null&&$.ok)||I)return;const{login:B}=await $.json();if(c(B),B.status!=="exited"||(u.current=!0,N&&(clearInterval(N),N=null),B.exitCode!==0))return;d(!0);const j=await ge(!0);I||(j.available&&((D=Pe(j.doctor,e,n))==null?void 0:D.status)==="connected"?M():d(!1))};fetch(`${p}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n})}).then($=>$.json()).then($=>{if(!I){if(!$.ok||!$.login){A($.error??"Could not start the login","error");return}c($.login),N=setInterval(T,Yl)}}).catch(()=>A("Could not start the login","error"));const R=Mo($=>{var B;return((B=Pe($,e,n))==null?void 0:B.status)==="connected"},{onDone:$=>{$&&M()}});return()=>{I=!0,N&&clearInterval(N),R(),u.current||fetch(h,{method:"DELETE"}).catch(()=>{})}},[e,n,x]);const z=()=>{fetch(h,{method:"DELETE"}).catch(()=>{}),o()},f=async()=>{const I=v.trim();if(I){y(!0);try{const M=await(await fetch(`${p}/api-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n,apiKey:I})})).json();M.ok?(k(""),A("API key saved","success"),ge(!0)):A(M.error??"Could not save the API key","error")}catch{A("Could not save the API key","error")}finally{y(!1)}}},P=(l==null?void 0:l.status)==="exited";return i("div",{class:"flex flex-col",style:{gap:"12px",padding:"14px 16px",borderRadius:"16px",background:"var(--bg-2)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",animation:"riseIn .3s var(--ease) both"},children:[i("div",{class:"flex items-center",style:{gap:"10px"},children:[i("h3",{style:{fontSize:"14px",fontWeight:650},children:["Connect ",e," on ",w]}),t("span",{class:"flex-1"}),t(E,{label:"Cancel",variant:"secondary",size:"sm",onClick:z})]}),!l&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Starting the login…"}),l&&!P&&i(J,{children:[i("div",{class:"flex flex-wrap items-center",style:{gap:"12px"},children:[l.url&&i("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",class:"inline-flex items-center gap-1 transition-all duration-180 ease-spring hover:-translate-y-px hover:brightness-106",style:{padding:"6px 14px",borderRadius:"9px",background:"linear-gradient(180deg, var(--blue-2), var(--blue))",color:"#fff",fontSize:"12.5px",fontWeight:600,boxShadow:"var(--shadow-m)"},children:["Open login ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),l.code&&i(J,{children:[t("span",{class:"mono",style:{fontSize:"19px",fontWeight:650,letterSpacing:".12em"},children:l.code}),t(E,{label:"Copy",variant:"secondary",size:"sm",onClick:()=>Hn(l.code??"","Code")})]})]}),l.code&&t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:"If the code is rejected, use the one shown in Output."}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:l.url||l.code?"Checks every 3 s. The status turns Connected on its own.":"Waiting for the login URL…"})]}),P&&s&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Checking the connection…"}),P&&!s&&i("div",{class:"flex items-center",style:{gap:"10px",fontSize:"12.5px"},children:[t("span",{style:{color:"var(--red)"},children:"The login ended before connecting."}),t(E,{label:"Retry",variant:"secondary",size:"sm",onClick:()=>g(I=>I+1)})]}),l&&l.output.length>0&&i("details",{style:{fontSize:"12.5px"},children:[t("summary",{class:"cursor-pointer",style:{color:"var(--ink-2)"},children:"Output"}),t("pre",{class:"overflow-x-auto",style:{marginTop:"8px",padding:"10px 12px",borderRadius:"11px",background:"var(--term)",color:"#e3e3e8",fontSize:"11.5px"},children:l.output.join(`
28
+ `)})]}),a&&i("div",{class:"flex flex-col",style:{gap:"8px",paddingTop:"12px",borderTop:"1px solid var(--hair)"},children:[t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:"Or with an API key"}),i("div",{class:"flex items-center",style:{gap:"8px"},children:[t("input",{type:"password",autocomplete:"off","aria-label":"API key",value:v,onInput:I=>k(I.target.value),placeholder:"sk-…",class:"field mono flex-1 min-w-0"}),t(E,{label:"Save",variant:"secondary",size:"sm",loading:S,disabled:!v.trim(),onClick:f})]}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:"Sent to cw over stdin. Forge never stores or shows it."})]})]})},Nt={display:"block",fontSize:"12px",color:"var(--ink-2)",marginBottom:"5px"},Zl=({response:e,onCancel:n,onCreated:a})=>{const[r,o]=b(""),[l,c]=b(""),[s,d]=b(""),[x,g]=b(""),[v,k]=b(!1),S=yt(),y=r.trim(),w=ro.test(y),p=e!=null&&e.available?e.doctor.harnesses.map(u=>u.name).filter(u=>u!=="claude"):[],h=!!l&&Me(e,l,"custom_provider"),m=async()=>{if(!(!w||v)){k(!0);try{const z=await(await fetch("/api/cw/accounts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:y,harness:l||void 0,provider:h&&s.trim()||void 0,model:h&&x.trim()||void 0})})).json();z.ok?(A(`Account "${y}" created`,"success"),a()):A(z.error??"Failed to create account","error")}catch{A("Failed to create account","error")}finally{k(!1)}}};return i("section",{class:"flex flex-col",style:{gap:"14px",padding:"16px 18px",borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",animation:"riseIn .3s var(--ease) both"},"aria-label":"Add account",children:[t("h2",{style:{fontSize:"17px",fontWeight:700,letterSpacing:"-0.02em"},children:"Add an account"}),i("div",{style:{maxWidth:"360px"},children:[t("label",{style:Nt,for:"new-account-name",children:"Account name"}),t("input",{id:"new-account-name",type:"text",value:r,onInput:u=>o(u.target.value),onKeyDown:u=>{u.key==="Enter"&&m()},placeholder:"my-account",class:"field",ref:S}),y&&!w&&t("p",{style:{fontSize:"12px",color:"var(--red)",marginTop:"5px"},children:"Must start with a letter or number. Only letters, numbers, hyphens, and underscores allowed."})]}),p.length>0&&i("div",{children:[t("span",{style:Nt,children:"Default harness"}),t(se,{label:"Default harness",tabs:[{id:"",label:"Claude Code"},...p.map(u=>({id:u,label:ue(u).label}))],active:l,onChange:c}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)",marginTop:"5px"},children:"The default harness cannot be changed later."})]}),h&&i("div",{class:"grid",style:{gridTemplateColumns:"1fr 1fr",gap:"10px",maxWidth:"520px"},children:[i("div",{children:[t("label",{style:Nt,children:"Provider · optional"}),t("input",{type:"text",value:s,onInput:u=>d(u.target.value),placeholder:"zai, ollama, openrouter",class:"field"})]}),i("div",{children:[t("label",{style:Nt,children:"Model · optional"}),t("input",{type:"text",value:x,onInput:u=>g(u.target.value),placeholder:"glm-5.1",class:"field"})]})]}),i("div",{class:"flex",style:{gap:"8px"},children:[t(E,{label:v?"Creating…":"Add account",variant:"primary",loading:v,disabled:!w,onClick:m}),t(E,{label:"Cancel",variant:"secondary",onClick:n})]})]})},Xl=new Set(["localhost","127.0.0.1","::1","[::1]"]),Sa={...We,overflow:"hidden"},es=({account:e,onRemoved:n})=>{const[a,r]=b(!1),o=async()=>{try{const c=await(await fetch(`/api/cw/accounts/${encodeURIComponent(e)}`,{method:"DELETE"})).json();c.ok?(A(`Account "${e}" removed`,"info"),n()):A(c.error??"Failed to remove account","error")}catch{A("Failed to remove account","error")}finally{r(!1)}};return a?i("span",{class:"flex items-center flex-wrap",style:{gap:"8px"},children:[t("span",{style:{fontSize:"12px",color:"var(--ink-2)"},children:"Deletes the profile and its harness config. Projects stay."}),t(E,{label:"Remove account",variant:"destructive",size:"sm",onClick:o}),t(E,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>r(!1)})]}):t(E,{label:"Remove",variant:"danger",size:"sm",onClick:()=>r(!0)})},ts=({projects:e,onOpenSession:n,onAccountsChanged:a})=>{const[r,o]=b(null),[l,c]=b(!1);F(()=>{ge()},[]),F(()=>Ka(),[]);const s=Qt.value,d=!Xl.has(window.location.hostname),x=s!=null&&s.available?s.doctor:null,g=()=>{r&&(fetch(`/api/cw/accounts/${encodeURIComponent(r.account)}/login/${encodeURIComponent(r.harness)}`,{method:"DELETE"}).catch(()=>{}),o(null))},v=async(p,h)=>{if(Me(s,h,"headless_login")){o({account:p,harness:h});return}try{const u=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"login",account:p,harness:h})})).json();u.ok&&u.session?n(u.session):A(u.error??"Could not open the login","error")}catch{A("Could not open the login","error")}},k=x?x.accounts.reduce((p,h)=>p+h.harnesses.filter(m=>m.status==="not_logged_in").length,0):0,S=x?`${x.accounts.length} account${x.accounts.length===1?"":"s"} · ${x.harnesses.length} harnesses · ${k} need${k===1?"s":""} connecting`:"Reading cw doctor…",y=p=>Object.values(e).filter(h=>h.account===p).length,w=(p,h)=>{if(!x)return null;const[m,u]=Pa(h),z=y(p.name),f=Pe(x,p.name,p.default_harness),P=[ue(p.default_harness).label,f&&f.provider!=="native"?f.provider:null].filter(Boolean).join(" · ");return i("section",{style:{...Sa,animation:`riseIn .36s var(--ease) ${h*90}ms both`},"aria-label":p.name,children:[i("div",{class:"flex items-center flex-wrap",style:{gap:"11px",padding:"12px 15px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"28px",height:"28px",borderRadius:"9px",background:`linear-gradient(160deg, var(${m}), var(${u}))`,boxShadow:"var(--shadow-s)",color:"#fff",fontSize:"12px",fontWeight:700},children:p.name.charAt(0).toUpperCase()}),t("span",{style:{fontSize:"15px",fontWeight:650,letterSpacing:"-0.01em"},children:p.name}),i("span",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Default ",P," · ",z," project",z===1?"":"s"]}),t("span",{class:"flex-1"}),t(es,{account:p.name,onRemoved:()=>{ge(!0),a()}})]}),x.harnesses.map(I=>{const N=Pe(x,p.name,I.name),M=(r==null?void 0:r.account)===p.name&&r.harness===I.name,T=ue(I.name),R=N?ql(N,M):null;return i("div",{style:{borderBottom:"1px solid var(--hair)"},children:[i("div",{class:"flex items-center flex-wrap",style:{gap:"12px",padding:"11px 15px"},children:[i("span",{class:"inline-flex items-center shrink-0",style:{gap:"6px",width:"132px",fontSize:"13px",fontWeight:600},children:[t("span",{style:{width:"8px",height:"8px",borderRadius:"50%",background:T.color}}),T.label]}),t("span",{class:"flex-1",style:{minWidth:"140px",fontSize:"12.5px",color:"var(--ink-2)"},children:N&&R?Gl(R,I.version,Me(s,I.name,"headless_login"),N):"Not configured for this account"}),R&&t(Vl,{view:R,onConnect:()=>{v(p.name,I.name)},onCancel:g})]}),N&&t(Jl,{account:p.name,harness:I.name}),M&&t("div",{style:{padding:"0 15px 13px"},children:t(Ql,{account:p.name,harness:I.name,canUseApiKey:Me(s,I.name,"api_key_login"),onConnected:()=>o(null),onClose:()=>o(null)},`${p.name}::${I.name}`)})]},I.name)})]},p.name)};return i(J,{children:[i(Ge,{title:"Accounts",subtitle:S,children:[t(E,{label:"Refresh",variant:"secondary",onClick:()=>{ge(!0)}}),t(E,{label:"Add account",variant:"primary",onClick:()=>c(!0)})]}),i("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[l&&t(Zl,{response:s,onCancel:()=>c(!1),onCreated:()=>{c(!1),ge(!0),a()}}),s&&!s.available&&i("section",{style:{...Sa,padding:"16px 18px"},children:[i("p",{style:{fontSize:"13.5px",marginBottom:"4px"},children:["Harness status is unavailable: ",s.reason]}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",marginBottom:"12px"},children:"The account view needs CW 0.3.0 or newer. You can still add an account by name."}),t(E,{label:"Retry",variant:"secondary",size:"sm",onClick:()=>{ge(!0)}})]}),x&&d&&t("p",{style:{...de,background:Z("--orange")},children:"Forge is not opened on localhost. Browser logins redirect to localhost on the machine running the harness, so only device-code logins work from here."}),x&&x.issues.map(p=>t("p",{style:{...de,background:Z("--red"),color:"var(--ink)"},children:p.message},p.code)),x&&x.warnings.map(p=>t("p",{style:{...de,background:"var(--elev)",color:"var(--ink-2)"},children:p.message},p.code)),x==null?void 0:x.accounts.map(w)]})]})},Ca="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev",ns=({sessions:e,openTabKeys:n,onOpenSession:a,onNewTask:r,onClose:o,position:l})=>{const c=oe(null);F(()=>{const d=g=>{c.current&&!c.current.contains(g.target)&&o()},x=g=>{g.key==="Escape"&&o()};return document.addEventListener("mousedown",d),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",x)}},[o]);const s=e.filter(d=>!n.has(q(d)));return i("div",{ref:c,class:"popover fixed z-[60] flex flex-col",style:{top:`${l.top}px`,left:`${l.left}px`,width:"min(320px, calc(100vw - 16px))",maxHeight:"420px",overflowY:"auto",padding:"6px",borderRadius:"14px"},children:[t("div",{style:{padding:"7px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:"New"}),qe.map(d=>i("button",{type:"button",class:Ca,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{r(d.key),o()},children:[t(Rn,{type:d.sessionType,size:22,radius:7,font:10}),t("span",{class:"flex-1",children:Bn(d.key)})]},d.key)),s.length>0&&i(J,{children:[t("div",{style:{padding:"9px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:"Resume"}),s.map(d=>i("button",{type:"button",class:Ca,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{a(d),o()},children:[t(Rn,{type:d.type,size:22,radius:7,font:10}),t("span",{class:"flex-1 truncate",children:pe(d)}),t("span",{class:"mono truncate",style:{fontSize:"10.5px",color:"var(--ink-3)",maxWidth:"110px"},children:ie(d)})]},q(d)))]})]})},as=({tabs:e,activeIndex:n,onActivate:a,onClose:r,onBack:o,allSessions:l,openTabKeys:c,onOpenSession:s,onNewTask:d})=>{const[x,g]=b(!1),v=oe(null),[k,S]=b({top:0,left:0}),y=V(()=>g(!1),[]),w=()=>{if(!x&&v.current){const p=v.current.getBoundingClientRect();S({top:p.bottom+6,left:Math.max(8,Math.min(p.left,window.innerWidth-328))})}g(!x)};return i(J,{children:[i("div",{class:"glass flex items-center shrink-0 overflow-x-auto",role:"tablist","aria-label":"Open sessions",style:{gap:"8px",padding:"9px 16px",borderBottom:"1px solid var(--hair)"},children:[t(Jn,{}),t(di,{onClick:o}),e.map((p,h)=>{const m=h===n,u=Ae.value[q(p)],z=!m&&_e(u);return i("div",{role:"tab",tabIndex:0,"aria-selected":m,title:[z?_t(u):null,h<5?`⌘${h+1}`:null].filter(Boolean).join(" · ")||void 0,class:"flex items-center shrink-0 whitespace-nowrap cursor-pointer transition-all duration-200 ease-spring",style:{gap:"8px",padding:"6px 11px",borderRadius:"10px",fontSize:"12.5px",background:m?"var(--card)":"transparent",border:`1px solid ${m?"var(--hair)":"transparent"}`,boxShadow:m?"var(--shadow-s)":"none"},onClick:()=>a(h),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),a(h))},children:[t(Se,{size:6,live:p.status==="active",color:z?`var(${Ot(u)})`:void 0}),t("span",{style:{fontWeight:600,color:m?"var(--ink)":"var(--ink-2)"},children:pe(p)}),t("span",{class:"mono truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"110px"},children:ie(p)}),t("button",{type:"button",class:"grid place-items-center cursor-pointer text-ink3 hover:text-red",style:{border:0,background:"none",padding:"0 1px"},onClick:f=>{f.stopPropagation(),r(h)},title:"Close tab (⌘W)","aria-label":`Close ${pe(p)}`,children:t("span",{class:"i-lucide-x",style:{width:"13px",height:"13px"}})})]},q(p))}),t("button",{ref:v,type:"button",class:"grid place-items-center shrink-0 cursor-pointer text-ink2 hover:text-ink",style:{width:"26px",height:"26px",borderRadius:"8px",border:"1px solid var(--hair)",background:"var(--card)"},onClick:w,"aria-expanded":x,title:"Open or create a tab","aria-label":"Open or create a tab",children:t("span",{class:"i-lucide-plus",style:{width:"14px",height:"14px"}})})]}),x&&t(ns,{sessions:l,openTabKeys:c,onOpenSession:s,onNewTask:d,onClose:y,position:k})]})};function rs(e,n){switch(e){case"uncommitted":{const a=(n==null?void 0:n.uncommitted)??0;return`${a} file${a===1?" has":"s have"} uncommitted changes. Closing deletes them.`}case"unpushed":{const a=n?ft(n):0;return`${a} commit${a===1?" is":"s are"} not pushed. They stay on ${(n==null?void 0:n.branch)??"the task branch"} on this machine only.`}case"pr-open":return`PR #${(n==null?void 0:n.pr.status)==="found"?n.pr.number:""} is still open. If changes are requested, reopening starts the agent without this conversation.`;case"state-unknown":return"Forge could not read this task's changes."}}const os=({request:e,onCancel:n,onConfirm:a})=>{if(!e)return null;const r=e.state?e.state.closeWarnings:["state-unknown"],o=r.includes("uncommitted");return i(He,{open:!0,title:"Close this task?",onClose:n,footer:i(J,{children:[t("span",{class:"flex-1"}),t(E,{label:"Cancel",variant:"secondary",onClick:n}),t(E,{label:"Close task",variant:o?"destructive":"primary",onClick:a})]}),width:460,children:[t("ul",{class:"flex flex-col",style:{gap:"8px",fontSize:"13.5px",paddingLeft:"18px"},children:r.map(c=>t("li",{children:rs(c,e.state)},c))}),e.error&&t("p",{style:{marginTop:"10px",fontSize:"12.5px",color:"var(--ink-2)"},children:e.error})]})},bn="forge-open-tabs";function is({spaces:e,loading:n,onFetchData:a}){const[r,o]=b([]),[l,c]=b(0),[s,d]=b(!0),x=oe(!1),g=oe(r);g.current=r,F(()=>{if(!(n||e.length===0||x.current)){x.current=!0;try{const p=sessionStorage.getItem(bn);if(!p)return;const{keys:h,activeIndex:m}=JSON.parse(p),u=[];for(const z of h){const f=e.find(P=>q(P)===z);f&&u.push(f)}u.length>0&&(o(u),c(Math.min(m,u.length-1)))}catch{}}},[n,e]),F(()=>{if(x.current)if(r.length>0){const p=r.map(q);sessionStorage.setItem(bn,JSON.stringify({keys:p,activeIndex:l}))}else sessionStorage.removeItem(bn)},[r,l]);const v=V(p=>{const h=q(p),m=r.findIndex(u=>q(u)===h);m>=0?c(m):(o(u=>[...u,p]),c(r.length)),d(!1)},[r]),k=V(async p=>{const h=g.current.find(f=>q(f)===p);if(!h)return;const m=h.sessionDir??(h.type==="review"?`review-pr-${h.pr}`:`task-${h.task}`);try{await fetch("/api/cw/terminal/kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:h.project,sessionDir:m})})}catch{}const u=g.current.findIndex(f=>q(f)===p);if(u<0)return;xo(p);const z=g.current.length-1;o(f=>f.filter(P=>q(P)!==p)),z===0?(d(!0),c(0),a()):c(f=>f>u?f-1:Math.min(f,z-1))},[a]),S=V(p=>{const h=r[p];return h?k(q(h)):Promise.resolve()},[r,k]),y=V(()=>{d(!0),a()},[a]);F(()=>{const p=h=>{if(r.length===0||s)return;const m=h.metaKey||h.ctrlKey;if(m&&h.key>="1"&&h.key<="5"){const u=parseInt(h.key)-1;u<r.length&&(h.preventDefault(),c(u));return}if(m&&(h.key==="ArrowLeft"||h.key==="ArrowRight")){h.preventDefault(),c(u=>h.key==="ArrowLeft"?u>0?u-1:r.length-1:u<r.length-1?u+1:0);return}if(m&&h.key==="w"){h.preventDefault(),S(l);return}m&&h.key==="l"&&(h.preventDefault(),y())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,s,l,S,y]);const w=ee(()=>new Set(r.map(q)),[r]);return{openTabs:r,activeTabIndex:l,setActiveTabIndex:c,showList:s,openTab:v,closeTab:S,closeTabByKey:k,goToList:y,openTabKeys:w}}function ls({spaces:e,accounts:n,projects:a}){const[r,o]=b(null),[l,c]=b(null),[s,d]=b(null),[x,g]=b(null),[v,k]=b(!1),S=ee(()=>Array.from(new Set(e.map(m=>m.harness??"claude"))).sort(),[e]),y=ee(()=>{if(n.length>0)return n;const m=new Set;for(const u of e)u.account&&m.add(u.account);return Array.from(m).sort()},[n,e]),w=ee(()=>{const m=new Set;for(const u of e)r&&u.account!==r||ie(u)&&m.add(u.project);for(const[u,z]of Object.entries(a))r&&z.account!==r||m.add(u);return Array.from(m).sort()},[e,a,r]),p=m=>{if(o(m),m&&l){const u=a[l];u&&u.account!==m&&c(null)}},h=ee(()=>e.filter(m=>!(r&&m.account!==r||l&&m.project!==l||x&&(m.harness??"claude")!==x||s&&m.type!==eo(s)||!v&&m.status==="done")),[e,r,l,s,x,v]);return{filterAccount:r,setFilterAccount:p,filterProject:l,setFilterProject:c,filterType:s,setFilterType:d,filterHarness:x,setFilterHarness:g,showDone:v,setShowDone:k,accountNames:y,projectNames:w,harnessNames:S,filteredSpaces:h}}function ss(){const[e,n]=b([]),[a,r]=b({}),[o,l]=b([]),[c,s]=b(!0),[d,x]=b("list"),[g,v]=b(!1),[k,S]=b(null),[y,w]=b(!1);F(()=>{ge(),lr(),fetch("/api/liveframe/frames").then(C=>C.json()).then(C=>S(C.length)).catch(()=>{})},[]);const p=V(async()=>{try{const[C,O,K]=await Promise.all([fetch("/api/cw/spaces"),fetch("/api/cw/projects"),fetch("/api/cw/accounts")]);n(await C.json()),r(await O.json()),l(await K.json()),Jo()}catch{A("Failed to connect to server","error")}finally{s(!1)}},[]),h=V(()=>{setTimeout(p,500),setTimeout(p,2500)},[p]);F(()=>{p()},[p]);const m=is({spaces:e,loading:c,onFetchData:p}),u=ls({spaces:e,accounts:o,projects:a}),z=Object.keys(a).length>0,f=C=>{const O=qe.find(K=>K.key===C);O&&(Ke.value=O.key),v(!0)},[P,I]=b(null),N=V(async(C,O)=>{try{const G=await(await fetch("/api/cw/done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:C.project,task:C.type==="review"?C.pr:C.task,type:C.type,sessionDir:C.sessionDir})})).json();if(G.ok)A("Task closed","info"),O==null||O(),h();else{const ne=G.error??"cw --done failed";console.error(`[forge] closing ${C.project}/${C.task??C.pr} failed:
29
+ ${ne}`),A(ne.split(`
30
+ `)[0],"error")}}catch{A("Failed to close the task","error")}},[h]),M=V(async(C,O)=>{const K=await Tn(C,!0);if(K.state&&K.state.closeWarnings.length===0){await N(C,O);return}I({session:C,state:K.state,error:K.error,onClosed:O})},[N]),T=t(os,{request:P,onCancel:()=>I(null),onConfirm:async()=>{const C=P;if(C)try{await N(C.session,C.onClosed)}finally{I(null)}}}),R=V(C=>{ze.value=!1,m.showList||m.goToList(),v(!1),x(C)},[m.showList,m.goToList]),$=V(()=>R("list"),[R]),B=V(()=>v(!1),[]),j=V(C=>{u.setFilterProject(u.filterProject===C?null:C),R(d==="memory"?"memory":"list")},[u.filterProject,u.setFilterProject,R,d]),D=V(C=>{u.setFilterProject(C),R("memory")},[u.setFilterProject,R]),W=V(C=>{ze.value=!1,v(!1),m.openTab(C)},[m.openTab]),[H,ce]=b(!1),L=V(()=>ce(!1),[]),Q=V(()=>ce(!0),[]);F(()=>{const C=O=>{const K=O.metaKey||O.ctrlKey,G=O.key.toLowerCase();if(K&&G==="j"){O.preventDefault(),ea();return}if(K&&G==="k"){O.preventDefault(),H?ce(!1):Q();return}const ne=O.target;ne!=null&&ne.closest('input, textarea, select, [contenteditable="true"]')||K||O.altKey||H||g||y||(O.key==="/"?(O.preventDefault(),Q()):G==="n"?(O.preventDefault(),v(!0)):G==="p"&&(O.preventDefault(),w(!0)))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[H,g,y,Q]);const te=V(async(C,O,K,G)=>{try{const X=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"general",account:O,project:K,description:C})})).json();X.ok&&X.session?(W(X.session),h(),A(G,"success")):A(X.error??"Failed to start session","error")}catch{A("Failed to start session","error")}},[W,h]),ve=V((C,O)=>{const K=C==="project"&&a[O]?O:void 0;return{account:C==="account"?O:K?a[K].account:o[0]||"default",project:K}},[o,a]),kt=V((C,O,K)=>{const{account:G,project:ne}=ve(C,O),X=C==="global"?"~/.claude/skills/":C==="account"?`~/.cw/accounts/${O}/skills/`:`${ne?a[ne].path:"<project>"}/.claude/skills/`,Je=["Use the skill-creator skill to create a new Claude Code skill.","",`The user wants: ${K}`,`Target scope: ${C}${C!=="global"?` (${O})`:""}`,`Save location: ${X}`,"","Before creating from scratch, search for existing similar skills:","1. Search skills.sh for related skills (WebSearch or WebFetch https://skills.sh/api/search?q=<keywords>)","2. Search GitHub for claude-code skill repos","3. Present what you find — let the user pick a base or start fresh","","Then use skill-creator to build/customize the skill and save it."].join(`
31
+ `);te(Je,G,ne,"AI skill creation session started")},[a,ve,te]),ye=V(C=>{const{account:O,project:K}=ve(C.scope,C.scopeRef);te(`Use the ${C.name} skill.`,O,K,`Session started with ${C.name}`)},[ve,te]),wt=V(async(C,O,K,G)=>{if(!C.project)return!1;try{const X=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"task",project:C.project,task:ji(O),description:Pi(C,O,K),account:G,harness:"claude"})})).json();if(X.ok&&X.session)return W(X.session),h(),A(`Proposing a skill in ${C.project}`,"success"),!0;A(X.error??"Failed to start session","error")}catch{A("Failed to start session","error")}return!1},[W,h]);F(()=>{c||Oa().catch(()=>{})},[c]);const be=ee(()=>e.filter(C=>C.status==="active"),[e]),Ee=ee(()=>m.openTabs.filter(C=>C.status==="active"&&C.type!=="login").map(C=>({key:q(C),session:C})),[m.openTabs]),he=!m.showList&&m.openTabs.length>0;F(()=>{const C=he?m.openTabs[m.activeTabIndex]:void 0;ra.value=C?q(C):null},[he,m.openTabs,m.activeTabIndex]);const St=oe({openTabs:m.openTabs,spaces:e,openSession:W});St.current={openTabs:m.openTabs,spaces:e,openSession:W},F(()=>wo((C,O)=>{if(document.visibilityState==="visible"&&C===ra.value)return;const{openTabs:K,spaces:G,openSession:ne}=St.current,X=K.find(Je=>q(Je)===C)??G.find(Je=>q(Je)===C);X&&oa(`${pe(X)}: ${_t(O).toLowerCase()}`,ie(X)||X.account,C,()=>ne(X))}),[]),F(()=>zo(),[]);const Ct=oe(R);Ct.current=R,F(()=>jo(C=>{var K;const O=((K=$e.value.find(G=>G.id===C.moduleId))==null?void 0:K.displayName)??C.moduleId;oa(`${O}: ${C.title}`,C.body??"",`module:${C.moduleId}:${C.key}`,()=>Ct.current(`module:${C.moduleId}`))}),[]);const Ve=Object.values(Ae.value).filter(_e).length;F(()=>{document.title=Ve>0?`(${Ve}) Forge Console`:"Forge Console"},[Ve]);const Zn=ee(()=>{const C=new Map(Object.entries(a).map(([O,K])=>[O,K.account]));for(const O of e)ie(O)&&!C.has(O.project)&&C.set(O.project,O.account);return Array.from(C,([O,K])=>({name:O,account:K||"unassigned",count:be.filter(G=>G.project===O).length,live:Ee.some(G=>G.session.project===O)}))},[a,e,be,Ee]);F(()=>{u.filterProject&&(Fe.value=u.filterProject)},[u.filterProject]);const $t=ee(()=>Object.keys(a),[a]),zt=V(C=>{u.setFilterProject(C),R("list")},[u.setFilterProject,R]),en=he?"list":d,tn=ee(()=>[{id:"new-task",label:"New task",hint:"N",glyph:"+",token:"--blue",run:()=>f()},{id:"add-project",label:"Add project",hint:"P",glyph:"P",token:"--green",run:()=>w(!0)},...er.map(C=>({id:C.view,label:C.label,hint:C.view==="list"?"⌘L":"",glyph:C.glyph,token:C.token,run:()=>R(C.view)})),...Va($e.value).map(C=>({id:`module:${C.id}`,label:C.displayName,hint:"",glyph:C.displayName.charAt(0).toUpperCase(),token:null,run:()=>R(`module:${C.id}`)})),{id:"appearance",label:"Toggle appearance",hint:"⌘J",glyph:"◐",token:null,run:ea}],[R,$e.value]),Tt=t(No,{view:en,counts:{list:be.length,accounts:u.accountNames.length,prototypes:k},projects:Zn,accounts:u.accountNames,selectedProject:u.filterProject,live:Ee,onNavigate:R,onSelectProject:j,onAddProject:()=>{ze.value=!1,w(!0)},onOpenLive:W,onSearch:Q}),_=c?t("div",{class:"py-20 text-center text-ink2",children:"Loading…"}):d==="list"&&!z?t("div",{style:{padding:"56px 22px"},children:t(je,{icon:"i-lucide-folder",title:"Welcome to Forge",description:"No projects found in CW. Register a project with 'cw open <project>' or create one with 'cw create' first.",action:{label:"Add project",onClick:()=>w(!0)}})}):d==="list"?t(fi,{spaces:u.filteredSpaces,allSpaces:e,projects:a,accountNames:u.accountNames,filterAccount:u.filterAccount,filterProject:u.filterProject,onFilterProject:u.setFilterProject,filterType:u.filterType,onFilterType:u.setFilterType,harnessNames:u.harnessNames,filterHarness:u.filterHarness,onFilterHarness:u.setFilterHarness,showDone:u.showDone,onShowDone:u.setShowDone,openTabKeys:m.openTabKeys,onSelectTask:W,onMarkDone:M,onNewTask:()=>f(),onCreateProject:()=>w(!0),onRefresh:()=>p(),onStarted:C=>{C&&W(C),h()}}):d.startsWith("module:")?t(Ul,{moduleId:d.slice(7),cwProject:u.filterProject,onBack:$},d):d==="qa"?t(Cl,{projects:a,preferred:u.filterProject??void 0}):d==="memory"?t(Ol,{project:u.filterProject,onProject:u.setFilterProject}):d==="prototypes"?t($l,{accounts:u.accountNames,onOpenSession:W,onFramesChanged:S}):d==="accounts"?t(ts,{projects:a,onOpenSession:W,onAccountsChanged:()=>{p()}}):t(qi,{accounts:u.accountNames,projects:a,onCreateWithAI:kt,onRunSkill:ye,onProposeSkill:wt});return i(Yr,{sidebar:Tt,children:[!he&&_,m.openTabs.length>0&&i("div",{class:"flex flex-col","aria-hidden":!he,style:he?{height:"100vh"}:{position:"absolute",top:0,left:0,right:0,height:"100vh",visibility:"hidden",pointerEvents:"none",zIndex:-1},children:[t(as,{tabs:m.openTabs,activeIndex:m.activeTabIndex,onActivate:m.setActiveTabIndex,onClose:m.closeTab,onBack:$,allSessions:be,openTabKeys:m.openTabKeys,onOpenSession:W,onNewTask:C=>{$(),f(C)}}),t("div",{class:"flex-1 min-h-0 relative",children:m.openTabs.map((C,O)=>{const K=O===m.activeTabIndex,G=K&&he;return t("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",visibility:G?"visible":"hidden",zIndex:K?1:0,pointerEvents:G?"auto":"none"},children:t(ki,{session:C,active:G,onDone:()=>M(C,()=>{m.closeTabByKey(q(C))}),onOpenMemory:D})},q(C))})})]}),g&&t(Ti,{projects:a,accounts:u.accountNames,initialAccount:u.filterAccount??(Ht.value||void 0),initialProject:Fe.value||void 0,onClose:B,onCreated:C=>{v(!1),C&&W(C),h()},onOpenAccounts:()=>R("accounts")}),H&&t(Oo,{openTabs:m.openTabs,sessions:e,projects:$t,commands:tn,onOpenSession:W,onSelectProject:zt,onClose:L}),t(Hl,{open:y,accounts:u.accountNames,onClose:()=>w(!1),onCreated:C=>{w(!1),C&&W(C),h()}}),T,t(Wl,{})]})}Ur(t(ss,{}),document.getElementById("app"));