forge-cw 0.1.14 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- var Kr=Object.defineProperty;var Ur=(e,n,a)=>n in e?Kr(e,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[n]=a;var aa=(e,n,a)=>Ur(e,typeof n!="symbol"?n+"":n,a);import{jsxs as l,jsx as t,Fragment as V}from"preact/jsx-runtime";import{Fragment as Hr,Component as qr,render as Gr}from"preact";import{useState as y,useMemo as ee,useEffect as F,useRef as oe,useCallback as J}from"preact/hooks";import{signal as Y,computed as ja}from"@preact/signals";import{ToastContainer as Vr,Tabs as se,UsageMeter as Pa,ToggleSwitch as Kn,showToast as P,ActionButton as I,ForgeTerminal as Jr,Drawer as qe,EmptyState as je,Modal as Ee,Badge as Aa}from"@forge-dev/ui";import{createPortal as Yr}from"preact/compat";import{definePanel as Qr,ModuleRequestError as _t}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 i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function a(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=a(o);fetch(o.href,i)}})();const Ia="forge-theme",Zr=()=>{try{return localStorage.getItem(Ia)==="light"?"light":"dark"}catch{return"dark"}},mt=Y(Zr());document.documentElement.setAttribute("data-theme",mt.value);const Ea=e=>{mt.value=e,document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(Ia,e)}catch{}},ze=Y(!1),ra=()=>Ea(mt.value==="dark"?"light":"dark"),Xr=({sidebar:e,children:n})=>l("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(Vr,{})]}),oa=[["--blue","--purple"],["--teal","--blue"],["--orange","--red"],["--green","--teal"]],La=e=>oa[e%oa.length],Z=(e,n=18)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,Me={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)"},de={padding:"10px 14px",borderRadius:"12px",fontSize:"12.5px"},eo={personal:"--blue",project:"--green",client:"--green",team:"--purple"},_e=e=>eo[e??""]??"--ink-2",to={decision:"--purple",context:"--teal",playbook:"--green",memory:"--orange",instinct:"--red",rule:"--blue",skill:"--ink-2"},la=e=>to[e]??"--ink-3",Tt=[{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:[]}],De=(e,n,a)=>({label:e,glyph:n,token:a,ink:`var(${a})`,fill:Z(a)}),Sn={task:De("Dev","D","--orange"),review:De("Review","R","--blue"),loop:De("Loop","L","--purple"),general:De("General","G","--green")},no={create:De("Create","C","--teal"),login:De("Login","A","--ink-2")},Un=e=>Sn[e]??no[e]??Sn.task,Ge=[{key:"dev",sessionType:"task"},{key:"review",sessionType:"review"},{key:"loop",sessionType:"loop"},{key:"general",sessionType:"general"}],Hn=e=>{var n;return Sn[((n=Ge.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"].label},ao=e=>{var n;return((n=Ge.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"},qn={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}},Ke=e=>!!(e&&(qn[e.state].attention||e.state==="exited"&&(e.exitCode??0)!==0)),Kt=e=>e.state==="exited"&&e.exitCode?`Exited with code ${e.exitCode}`:qn[e.state].label,Ot=e=>e.state==="exited"&&e.exitCode?"--red":qn[e.state].token,q=e=>e.sessionDir?`${e.project}::${e.sessionDir}`:`${e.project}::${e.task??e.pr}`,le=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}`),ue=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} · ${he(e.harness).label}`:e.task??"unknown",ro={linear:"Linear",notion:"Notion"},Gn=e=>{var a;const n=e.source?ro[e.source]:void 0;return n&&((a=e.source_url)!=null&&a.startsWith("https://"))?{label:n,url:e.source_url}:null},Yt=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}`)}),oo={claude:jt("Claude Code","claude"),codex:jt("Codex","codex"),pi:jt("Pi","pi"),opencode:jt("OpenCode","opencode")},he=e=>oo[e??"claude"]??{label:e??"claude",color:"var(--ink-3)",bg:"var(--elev)"},Na=e=>{const n=he(e.harness).label;return e.provider&&e.provider!=="native"?`${n} · ${e.model||e.provider}`:n},lo=[{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"}],Oa=(e,n,a,r)=>{var o,i;return(e?(o=a[e])==null?void 0:o.harness:void 0)??((i=r.accounts.find(c=>c.name===n))==null?void 0:i.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)},io=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,so=new Intl.DateTimeFormat(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}),Da=(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 ${so.format(Math.round(a/6e4)*6e4)}`;const i=r%60;return`resets in ${o} h${i?` ${i} m`:""}`},Wa=e=>e.map(n=>({label:n.label,percent:n.percent,severity:n.severity,scope:n.scope,reset:Da(n.resetsAt)})),Ma=Y(null);async function co(){const e=await fetch("/api/health");Ma.value=(await e.json()).version??null}const it=Y(null);async function Fa(){const e=await fetch("/api/skills");if(!e.ok)throw new Error("fetch failed");it.value=await e.json()}const $e=({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"}})},an=5,Ba="forge-sidebar-collapsed",po=()=>{try{const e=localStorage.getItem(Ba);return e?JSON.parse(e):[]}catch{return[]}},uo=(e,n)=>Number(n.live)-Number(e.live)||n.count-e.count||e.name.localeCompare(n.name),ho=({projects:e,accounts:n,selected:a,onSelect:r,onAdd:o})=>{const[i,c]=y(""),[s,d]=y(po),[x,f]=y([]),b=i.trim().toLowerCase(),m=ee(()=>{const k=[...n,...e.map(w=>w.account).filter(w=>!n.includes(w))];return Array.from(new Set(k)).map((w,u)=>({account:w,index:u,items:e.filter(h=>h.account===w&&(!b||h.name.toLowerCase().includes(b))).sort(uo),active:e.filter(h=>h.account===w).reduce((h,v)=>h+v.count,0)})).filter(w=>w.items.length>0)},[e,n,b]),S=k=>{const w=s.includes(k)?s.filter(u=>u!==k):[...s,k];d(w);try{localStorage.setItem(Ba,JSON.stringify(w))}catch{}};return l("div",{class:"flex flex-col sb-section min-h-0",style:{gap:"6px",flex:"0 1 auto",minHeight:"120px"},children:[l("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"}})})]}),l("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:i,style:{height:"28px",padding:"0 8px 0 27px",borderRadius:"8px",fontSize:"12.5px",background:"var(--elev)"},onInput:k=>c(k.target.value),onKeyDown:k=>{k.key==="Escape"&&c("")}})]}),l("div",{class:"flex flex-col overflow-y-auto min-h-0",style:{gap:"8px",overscrollBehavior:"contain"},children:[m.length===0&&l("p",{style:{padding:"4px 9px",fontSize:"12px",color:"var(--ink-3)"},children:["No project matches “",i.trim(),"”."]}),m.map(k=>{const w=b!==""||!s.includes(k.account),u=b!==""||x.includes(k.account)||k.items.some((g,A)=>A>=an&&g.name===a),h=u?k.items:k.items.slice(0,an),[v,p]=La(k.index),z=k.items.some(g=>g.live);return l("div",{class:"flex flex-col shrink-0",style:{gap:"1px"},children:[l("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(k.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(${v}), var(${p}))`,color:"#fff",fontSize:"9px",fontWeight:700},children:k.account.charAt(0).toUpperCase()}),t("span",{class:"flex-1 truncate",style:{fontSize:"12px",fontWeight:600},children:k.account}),z&&t($e,{size:5,live:!0,glow:!1}),t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},title:`${k.items.length} projects · ${k.active} active tasks`,children:k.items.length})]}),w&&l("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(g=>{const A=a===g.name;return l("button",{type:"button","aria-pressed":A,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 ${A?"var(--hair)":"transparent"}`,background:A?"var(--card)":"transparent",boxShadow:A?"var(--shadow-s)":"none"},onClick:()=>r(g.name),children:[t($e,{size:6,live:g.live}),t("span",{class:"flex-1 truncate",style:{fontWeight:A?600:450,opacity:g.count>0||g.live||A?1:.62},children:g.name}),g.count>0&&t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:g.count})]},g.name)}),k.items.length>an&&b===""&&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:()=>f(u?x.filter(g=>g!==k.account):[...x,k.account]),children:u?"Show less":`Show all ${k.items.length}`})]})]},k.account)})]})]})},_a={context:null,tokens:null,cost:null},fo=250,Ut=new Map,go=/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g,Qe=(e,n)=>{let a=null;for(const r of e.matchAll(n))a=r;return a},rn=e=>{const n=parseFloat(e),a=e.slice(-1).toLowerCase();return a==="k"?n*1e3:a==="m"?n*1e6:n};function xo(e){const n={},a=Qe(e,/(?:ctx|context)[:\s]*(\d{1,3}(?:\.\d+)?)\s*%/gi)??Qe(e,/[▓█▒░]+\s*(\d{1,3}(?:\.\d+)?)\s*%/g);a&&(n.context=Math.min(100,parseFloat(a[1])));const r=Qe(e,/(\d+(?:\.\d+)?[kKmM]?)\s*↑\s*(\d+(?:\.\d+)?[kKmM]?)\s*↓/g),o=Qe(e,/\((\d+(?:\.\d+)?[kKmM])\s*\/\s*\d+(?:\.\d+)?[kKmM]\)/g);r?n.tokens=rn(r[1])+rn(r[2]):o&&(n.tokens=rn(o[1]));const i=Qe(e,/\$(\d+\.\d{2})\b/g);return i&&(n.cost=parseFloat(i[1])),n}const Ka=e=>{let n=Ut.get(e);return n||(n={tail:"",timer:null,metrics:Y(_a)},Ut.set(e,n)),n},Ua=e=>Ka(e).metrics,mo=e=>{e.timer=null;const n=e.metrics.value,a={...n,...xo(e.tail)};(a.context!==n.context||a.tokens!==n.tokens||a.cost!==n.cost)&&(e.metrics.value=a)};function vo(e,n){const a=Ka(e);a.tail=(a.tail+n.slice(-4e3*2).replace(go,"")).slice(-4e3),a.timer||(a.timer=setTimeout(()=>mo(a),fo))}function yo(e){const n=Ut.get(e);n&&(n.timer&&clearTimeout(n.timer),n.metrics.value=_a,Ut.delete(e))}const Ha=e=>e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e),qa=e=>`$${e.toFixed(2)}`,pt=Y(null),bo=6e4;let Ze=null,Xe=null,on=0;function ia(e=!1){return Ze||(Ze=fetch(`/api/cw/usage${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(pt.value=n,Ze=null,n)),Ze)}function Ga(){return on+=1,ia(),Xe||(Xe=setInterval(()=>{document.visibilityState==="visible"&&ia()},bo)),()=>{on-=1,on===0&&Xe&&(clearInterval(Xe),Xe=null)}}const ko=(e,n)=>{var a;return((a=pt.value)!=null&&a.available?pt.value.usage.find(r=>r.account===e&&r.harness===n):null)??null},Ae=Y({}),sa=Y(null),Va=2e3,wo=15e3;let et=null,Ja=0,ln=!1;const Dt=new Set,So=(e,n)=>!!e&&Ke(n)&&(e.state!==n.state||e.since!==n.since);async function Ya(){if(!ln){ln=!0,Ja=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(So(a[r],o))for(const i of Dt)i(r,o)}catch{}finally{ln=!1}}}const Co=()=>{const e=document.visibilityState==="visible"?Va:wo;Date.now()-Ja>=e-100&&Ya()};function $o(e){return Dt.add(e),et||(Ya(),et=setInterval(Co,Va)),()=>{Dt.delete(e),Dt.size===0&&et&&(clearInterval(et),et=null)}}const Qa="forge.notify-sessions",Qt=typeof window<"u"&&"Notification"in window,zo=()=>{try{return Qt&&Notification.permission==="granted"&&localStorage.getItem(Qa)==="1"}catch{return!1}},Vn=Y(zo());async function Ro(e){if(e&&(!Qt||(Notification.permission==="default"?await Notification.requestPermission():Notification.permission)!=="granted"))return!1;Vn.value=e;try{localStorage.setItem(Qa,e?"1":"0")}catch{}return!0}function ca(e,n,a,r){if(!Vn.value||!Qt||Notification.permission!=="granted")return;const o=new Notification(e,{body:n,tag:a});o.onclick=()=>{window.focus(),r(),o.close()}}const be=Y([]),Wt=Y(!1),To=1e4;let tt=null,sn=0;async function ut(){try{const e=await fetch("/api/modules");e.ok&&(be.value=await e.json())}catch{}}const da=()=>{ut()};function jo(){return sn++,tt||(ut(),tt=setInterval(()=>{ut()},To),window.addEventListener("focus",da)),()=>{sn--,sn===0&&tt&&(clearInterval(tt),tt=null,window.removeEventListener("focus",da))}}const Za=e=>e.filter(n=>n.state!=="legacy"&&(n.view||n.state==="disabled")),Xa=e=>e.lastDenial?`Denied ${e.lastDenial.permission}: ${e.lastDenial.value}`:e.lastJobError??e.lastEventError??null,ht=Y([]),er=ja(()=>{var n;const e={};for(const a of ht.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}),tr=5e3,Po=15e3;let nt=null,nr=0,pa=!1,cn=!1;const Mt=new Set,ua=e=>`${e.moduleId}\0${e.key}\0${e.createdAt}`;async function ar(){if(!cn){cn=!0,nr=Date.now();try{const e=await fetch("/api/modules/notifications");if(!e.ok)return;const{items:n}=await e.json(),a=new Set(ht.value.map(ua));if(ht.value=n,pa){for(const r of n)if(r.kind==="attention"&&!r.seen&&!a.has(ua(r)))for(const o of Mt)o(r)}pa=!0}catch{}finally{cn=!1}}}const Ao=()=>{const e=document.visibilityState==="visible"?tr:Po;Date.now()-nr>=e-100&&ar()};function Io(e){return Mt.add(e),nt||(ar(),nt=setInterval(Ao,tr)),()=>{Mt.delete(e),Mt.size===0&&nt&&(clearInterval(nt),nt=null)}}async function Eo(e){ht.value=ht.value.map(n=>n.moduleId===e?{...n,seen:!0}:n),await fetch(`/api/modules/${encodeURIComponent(e)}/notifications/seen`,{method:"POST"}).catch(()=>{})}const rr=[{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"}],Cn="flex items-center w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",$n=e=>({borderRadius:"9px",border:`1px solid ${e?"var(--hair)":"transparent"}`,background:e?"var(--card)":"transparent",boxShadow:e?"var(--shadow-s)":"none",color:"var(--ink)"}),or="flex flex-col text-left cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m",zn={gap:"6px",padding:"9px 10px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",color:"var(--ink)"},Rn={fontSize:"10.5px",color:"var(--ink-3)"},Tn=({children:e})=>t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)",letterSpacing:".02em"},children:e}),Lo=({id:e,session:n,index:a,onOpen:r})=>{const o=Ua(e).value,i=Ae.value[e],c=Ke(i),s=n.type==="loop",d=(o==null?void 0:o.context)??null,[x,f]=a%2===0?["var(--blue)","var(--purple)"]:["var(--purple)","var(--blue)"],b=c?Kt(i):s?n.loop_interval?`every ${n.loop_interval}`:"self-paced":o&&(o.tokens!==null||o.cost!==null)?[o.tokens!==null?`${Ha(o.tokens)} tokens`:null,o.cost!==null?qa(o.cost):null].filter(Boolean).join(" · "):le(n)||n.account;return l("button",{type:"button",class:or,style:c?{...zn,borderColor:`var(${Ot(i)})`}:zn,onClick:r,title:i?Kt(i):void 0,children:[l("span",{class:"flex items-center w-full",style:{gap:"6px"},children:[t($e,{size:6,color:i?`var(${Ot(i)})`:x,live:!i||i.state==="working"||c}),t("span",{class:"truncate",style:{fontSize:"12.5px",fontWeight:600},children:ue(n)}),t("span",{class:"flex-1"}),t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-2)"},children:d!==null?`${Math.round(d)}%`:"—"})]}),l("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}, ${f})`,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?{...Rn,color:`var(${Ot(i)})`,fontWeight:600}:Rn,children:b})]})},No=({view:e,onNavigate:n})=>{const a=Za(be.value),r=er.value,o=()=>{ze.value=!1,Wt.value=!0};return l("nav",{class:"flex flex-col sb-section",style:{gap:"2px"},"aria-label":"Modules",children:[l("div",{class:"flex items-center justify-between",style:{padding:"0 9px 4px"},children:[t(Tn,{children:"Modules"}),t("button",{type:"button","aria-label":"Add a module",title:"Add a module",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"}})})]}),a.length===0&&l("button",{type:"button",class:Cn,style:{...$n(!1),gap:"9px",height:"30px",padding:"0 9px",fontSize:"12.5px",color:"var(--ink-3)"},onClick:o,children:[t("span",{class:"i-lucide-package-plus shrink-0",style:{width:"15px",height:"15px"}}),t("span",{class:"flex-1 sb-label truncate",children:"Add a module"})]}),a.map(i=>{const c=`module:${i.id}`,s=e===c,d=i.state!=="enabled",x=d?null:Xa(i),f=r[i.id],b=i.color??"var(--ink-3)";return l("button",{type:"button","aria-current":s?"page":void 0,title:d?`${i.displayName} is disabled: ${i.reason??""}`:x??i.displayName,class:Cn,style:{...$n(s),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:s?600:450,opacity:d?.5:1},onClick:()=>n(c),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"18px",height:"18px",borderRadius:"5px",fontSize:"10px",fontWeight:600,background:s?`color-mix(in srgb, ${b} 18%, transparent)`:"var(--elev)",color:s?b:"var(--ink-3)"},children:i.displayName.charAt(0).toUpperCase()}),t("span",{class:"flex-1 sb-label truncate",children:i.displayName}),x&&t("span",{class:"sb-label","aria-label":"Has a warning",style:{width:"6px",height:"6px",borderRadius:"50%",background:"var(--orange)"}}),f&&f.attention>0&&t("span",{class:"mono sb-label","aria-label":`${f.attention} need you`,style:{fontSize:"10.5px",fontWeight:700,padding:"0 6px",borderRadius:"99px",color:"#fff",background:"var(--red)"},children:f.attention}),f&&f.badge>0&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:f.badge})]},`${i.id}-${i.source}`)})]})},Oo=()=>l("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(Kn,{checked:Vn.value,label:"Notify me when a session or module needs me",onChange:e=>{Ro(e).then(n=>{n||P("The browser blocked notifications for Forge","error")})}})]}),Do=({account:e,harness:n,windows:a,stale:r,onOpen:o})=>{const i=a.reduce((s,d)=>d.percent>s.percent?d:s),c=he(n).label;return l("button",{type:"button",class:or,style:zn,onClick:o,title:`Usage limits for ${e} on ${c}`,children:[l("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(Pa,{bars:Wa(a),size:"sm"}),t("span",{class:"mono truncate w-full",style:Rn,children:r?"last known values":Da(i.resetsAt)})]})},Wo=({view:e,counts:n,projects:a,accounts:r,selectedProject:o,live:i,onNavigate:c,onSelectProject:s,onAddProject:d,onOpenLive:x,onSearch:f})=>{var w;const b=Ma.value,m=rr.map(u=>{var h;return{...u,count:u.view==="skills"?((h=it.value)==null?void 0:h.length)??null:n[u.view]??null}});F(()=>Ga(),[]),F(()=>{co().catch(()=>{})},[]);const S=[...i].sort((u,h)=>Number(Ke(Ae.value[h.key]))-Number(Ke(Ae.value[u.key]))),k=(w=pt.value)!=null&&w.available?pt.value.usage.filter(u=>u.state==="ok"&&u.windows.some(h=>!h.scope)):[];return l("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:[l("div",{role:"button",tabIndex:0,class:"flex items-center cursor-pointer",style:{gap:"9px",padding:"2px 8px"},onClick:()=>c("list"),onKeyDown:u=>{(u.key==="Enter"||u.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"}),b&&t("span",{class:"mono sb-label",style:{fontSize:"10px",color:"var(--ink-3)"},title:"Forge version",children:b})]}),f&&l("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:f,"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:m.map(u=>{const h=e===u.view;return l("button",{type:"button","aria-current":h?"page":void 0,title:u.label,class:Cn,style:{...$n(h),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:h?600:450},onClick:()=>c(u.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(u.token):"var(--elev)",color:h?`var(${u.token})`:"var(--ink-3)"},children:u.glyph}),t("span",{class:"flex-1 sb-label",children:u.label}),u.count!==null&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:u.count})]},u.view)})}),t(No,{view:e,onNavigate:c}),t(ho,{projects:a,accounts:r,selected:o,onSelect:s,onAdd:d}),l("div",{class:"flex flex-col",style:{marginTop:"auto",flex:"none",gap:"8px"},children:[i.length>0&&l("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Tn,{children:"Live now"})}),S.map((u,h)=>t(Lo,{id:u.key,session:u.session,index:h,onOpen:()=>x(u.session)},u.key))]}),k.length>0&&l("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Tn,{children:"Limits"})}),k.map(u=>t(Do,{account:u.account,harness:u.harness,windows:u.windows.filter(h=>!h.scope),stale:u.stale,onOpen:()=>c("accounts")},`${u.account}/${u.harness}`))]}),Qt&&t("div",{class:"sb-section",children:t(Oo,{})}),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:u=>Ea(u==="light"?"light":"dark")})})]})]})};function yt(){const e=oe(null);return F(()=>{var n;(n=e.current)==null||n.focus()},[]),e}const ha=(e,n,a)=>{const r=Un(e.type);return{id:q(e),label:le(e)?`${ue(e)} · ${le(e)}`:ue(e),hint:n,glyph:r.glyph,token:r.token,run:()=>a(e)}},Mo=({openTabs:e,sessions:n,projects:a,commands:r,onOpenSession:o,onSelectProject:i,onClose:c})=>{const[s,d]=y(""),[x,f]=y(0),b=oe(null),m=yt(),S=ee(()=>{const p=s.trim().toLowerCase(),z=O=>!p||O.label.toLowerCase().includes(p),g=new Set(e.map(q)),A=e.map((O,R)=>ha(O,R<5?`⌘${R+1}`:"open",o)),L=n.filter(O=>O.status==="active"&&!g.has(q(O))).map(O=>ha(O,"resume",o)),N=p?a.map(O=>({id:`project:${O}`,label:O,hint:"project",glyph:"P",token:"--green",run:()=>i(O)})):[];return[{name:"Live now",items:A.filter(z)},{name:"Tasks",items:L.filter(z).slice(0,p?12:6)},{name:"Projects",items:N.filter(z).slice(0,6)},{name:"Commands",items:r.filter(z)}].filter(O=>O.items.length>0)},[s,e,n,a,r,o,i]),k=S.flatMap(p=>p.items),w=Math.min(x,k.length-1);F(()=>{var p,z;(z=(p=b.current)==null?void 0:p.querySelector('[data-active="true"]'))==null||z.scrollIntoView({block:"nearest"})},[w]);const u=p=>{p&&(c(),p.run())},h=oe({flat:k,current:w,activate:u});h.current={flat:k,current:w,activate:u},F(()=>{const p=z=>{const{flat:g,current:A,activate:L}=h.current,N=g.length;z.key==="ArrowDown"?(z.preventDefault(),f(O=>N?(Math.min(O,N-1)+1)%N:0)):z.key==="ArrowUp"?(z.preventDefault(),f(O=>N?(Math.min(O,N-1)-1+N)%N:0)):z.key==="Enter"?(z.preventDefault(),L(g[A])):z.key==="Escape"&&(z.preventDefault(),c())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[c]);let v=-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:l("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:p=>p.stopPropagation(),children:[t("input",{ref:m,role:"combobox","aria-expanded":"true","aria-controls":"palette-list","aria-activedescendant":k[w]?`palette-${k[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:p=>{d(p.target.value),f(0)}}),l("div",{id:"palette-list",role:"listbox",ref:b,class:"overflow-auto",style:{padding:"6px"},children:[k.length===0&&l("p",{style:{padding:"14px 10px",fontSize:"13px",color:"var(--ink-2)"},children:["Nothing matches “",s,"”."]}),S.map(p=>l("div",{role:"group","aria-label":p.name,children:[t("div",{style:{padding:"7px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:p.name}),p.items.map(z=>{v+=1;const g=v,A=g===w;return l("button",{id:`palette-${z.id}`,type:"button",role:"option","aria-selected":A,"data-active":A,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"10px",padding:"8px 10px",borderRadius:"10px",border:0,background:A?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px",transition:"background .14s"},onMouseMove:()=>{A||f(g)},onClick:()=>u(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)})]},p.name))]}),t("div",{class:"flex shrink-0",style:{gap:"14px",padding:"8px 14px",borderTop:"1px solid var(--hair)"},children:["↑↓ move","↵ open","esc close"].map(p=>t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:p},p))})]})})},Zt=Y(null),Fo=3e3;let at=null;function ve(e=!1){return at||(at=fetch(`/api/cw/harnesses${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(Zt.value=n,at=null,n)),at)}const ft=new Set;let st=null;const lr=()=>{ft.size===0&&st&&(clearInterval(st),st=null)},Bo=async()=>{const e=await ve(!0),n=Date.now();for(const a of ft){const r=e.available&&a.check(e.doctor);(r||n>a.deadline)&&(ft.delete(a),a.onDone(r))}lr()};function _o(e,{timeoutMs:n=6e5,onDone:a=()=>{}}={}){const r={check:e,deadline:Date.now()+n,onDone:a};return ft.add(r),st||(st=setInterval(Bo,Fo)),()=>{ft.delete(r),lr()}}const Fe=(e,n,a)=>{var r;return!!(e!=null&&e.available&&((r=e.capabilities[n])!=null&&r.includes(a)))},ir=e=>/linear\.app/.test(e)?"linear":/notion\.(so|site)/.test(e)?"notion":null,sr=(e,n,a)=>{const r=ir(a);return!!(e!=null&&e.available&&r&&!Fe(e,n,"mcp")&&!e.contextTokens[r])},jn=Y(null);let dn=null;function cr(){return dn||(dn=fetch("/api/cw/editors").then(e=>e.json()).then(e=>{jn.value=e}).catch(()=>{jn.value={enabled:!1,editors:[]}})),dn}async function Ko(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 gt=e=>e.unpushed??e.commits??0,dr={OPEN:"open",MERGED:"merged",CLOSED:"closed"},Uo={passing:"✓",failing:"✗",pending:"…",none:""};function Ho(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=gt(e);if(a>0&&n.push(`${a} unpushed`),e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":dr[e.pr.state];n.push(`PR #${e.pr.number} ${r}`),e.pr.checks!=="none"&&n.push(`checks ${Uo[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 qo={passing:"checks pass",failing:"checks failing",pending:"checks running",none:""},fa=(e,n)=>`${e} ${n}${e===1?"":"s"}`;function Go(e){if(e.workspace==="missing")return"not created yet";if(e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":dr[e.pr.state];return[`PR #${e.pr.number} ${r}`,qo[e.pr.checks]].filter(Boolean).join(" · ")}const n=[];e.diff&&e.diff.files>0&&n.push(fa(e.diff.files,"file")),e.commits&&n.push(fa(e.commits,"commit"));const a=gt(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 pr(e,n,a){const r=await fetch(n,a===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),o=await r.json().catch(()=>({})),i=r.ok?o.error:o.error??o.message??`Request failed (${r.status})`;if(i)throw new Error(i);return o}const ge=(e,n)=>pr("POST",e,n),pe=e=>e instanceof Error?e.message:String(e);function Jn(e,n){navigator.clipboard.writeText(e).then(()=>P(`${n} copied`,"info"),()=>P(`Could not copy the ${n.toLowerCase()}`,"error"))}const Vo=({session:e,muted:n})=>{const a=he(e.harness);return l("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}}),Na(e)]})},ye=Y(null),Jo=6e4;let rt=null,ot=null,pn=0;function Re(e=!1){return rt&&!e||(rt=fetch(`/api/kioku/status${e?"?fresh=1":""}`).then(n=>n.json()).then(n=>{JSON.stringify(n)!==JSON.stringify(ye.value)&&(ye.value=n)}).catch(()=>{ye.value??(ye.value={installed:!1,version:null,brains:[],projects:{},activity:[],viewer:null})}).finally(()=>{rt=null})),rt}function ur(){return pn+=1,ye.value||Re(),ot||(ot=setInterval(()=>{document.visibilityState==="visible"&&Re()},Jo)),()=>{pn-=1,pn===0&&ot&&(clearInterval(ot),ot=null)}}const re=e=>e.name??e.key,Ht=e=>e.reduce((n,a)=>n+a.pages,0);function Yn(e){const n=ye.value;return n!=null&&n.installed?(n.projects[e]??[]).flatMap(a=>n.brains.find(r=>re(r)===a.name)??[]):[]}function hr(e){return F(()=>ur(),[]),Yn(e)}const Yo=({project:e})=>{const[n,a]=y(null),r=hr(e);return r.length===0?null:l("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(re).join(", ")}`,onMouseEnter:o=>a(o.currentTarget.getBoundingClientRect()),onMouseLeave:()=>a(null),children:[t("span",{class:"inline-flex",children:r.map((o,i)=>t("span",{style:{width:"9px",height:"9px",borderRadius:"50%",background:`var(${_e(o.tier)})`,border:"2px solid var(--card)",marginLeft:i===0?0:"-4px"}},o.key))}),t("span",{class:"mono",children:Ht(r)}),n&&Yr(l("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=>l("span",{class:"flex items-center",style:{gap:"7px",fontSize:"12px",color:"var(--ink)",fontWeight:500},children:[t($e,{color:`var(${_e(o.tier)})`}),re(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)]})},Pn=Y({}),fr=Y(0),Qo=6e4,Pt=new Map,gr=e=>`${e.project}::${vt(e)}`;function An(e,n=!1){const a=gr(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":""}`,i=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=>(Pn.value={...Pn.value,[a]:c},Pt.get(a)===i&&Pt.delete(a),c));return Pt.set(a,i),i}function Zo(){fr.value++}function xr(e,{poll:n=!1}={}){const a=gr(e),r=fr.value;return F(()=>{if(An(e),!n)return;const o=setInterval(()=>{An(e,!0)},Qo);return()=>clearInterval(o)},[a,n,r]),Pn.value[a]??null}const In=({type:e,size:n=28,radius:a=9,font:r=11})=>{const o=Un(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})},Xo=()=>l("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($e,{size:5,color:"var(--green)",live:!0,glow:!1}),"live"]}),mr=({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?l("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})},vr=({session:e})=>{const n=Gn(e);return n&&t(mr,{label:n.label,href:n.url})},el=({session:e})=>Gn(e)?t(vr,{session:e}):e.source?t("span",{class:"task-chip contents",children:t(mr,{label:e.source,href:e.source_url})}):null,yr=e=>e.type==="review"?`review/pr-${e.pr}`:e.type==="loop"?`loop/${e.task??"loop"}`:e.type==="task"?`task/${e.task}`:null,tl=({session:e,project:n})=>{var i;const a=xr(e),r=((i=a==null?void 0:a.state)==null?void 0:i.branch)??yr(e),o=a?a.error!==null?"changes unknown":Go(a.state):"checking…";return t(br,{branch:r,status:o,project:n})},br=({branch:e,status:n,project:a})=>l("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(),Jn(e,"Branch")},onKeyDown:r=>r.stopPropagation(),children:e}),t("span",{class:"whitespace-nowrap truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:n})]}),nl=e=>e.type==="loop"?e.loop_interval?`every ${e.loop_interval}`:"self-paced":`${e.opens} session${e.opens===1?"":"s"}`,kr=({session:e,isOpenInTab:n,onSelect:a,onMarkDone:r,showProject:o})=>{const i=o?le(e)||"no project":void 0,[c,s]=y(!1),d=e.type==="task"||e.type==="review",x=async()=>{if(!(!r||c)){s(!0);try{await r()}finally{s(!1)}}};return l("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"} ${ue(e)}`,onKeyDown:f=>{f.target===f.currentTarget&&(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),a())},children:[t(In,{type:e.type}),l("div",{class:"flex-1 min-w-0",children:[l("div",{class:"flex items-center min-w-0",style:{gap:"8px"},children:[t("span",{class:"truncate",style:{fontSize:"14px",fontWeight:600},children:ue(e)}),n&&e.status==="active"&&t(Xo,{}),t(el,{session:e})]}),d?t(tl,{session:e,project:i}):t(br,{branch:yr(e),status:nl(e),project:i})]}),t(Yo,{project:le(e)}),t(Vo,{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:Yt(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:f=>{f.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"})]})},al=({session:e,onSelect:n})=>l("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"}})}),l("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px"},children:[ue(e)," ",t("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:le(e)})]}),t(vr,{session:e}),t("span",{class:"mono shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:Yt(e.closed??e.last_opened)})]}),rl=({project:e,account:n,accounts:a,onDeleted:r,onMoved:o})=>{const[i,c]=y(null),[s,d]=y(null),[x,f]=y(!1),[b,m]=y(!1),[S,k]=y(""),[w,u]=y(!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 v=i?Object.keys(i.global):[],p=(i==null?void 0:i.project)??[],z=(i==null?void 0:i.cw)??[],g=(i==null?void 0:i.plugins)??[],A=[...p.map($=>`${$} (project)`),...v,...z.map($=>`${$} (CW)`)],L=$=>{d(s===$?null:$),k(""),f(!1)},N=async()=>{m(!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&&(P(`Project "${e}" deleted${x?" (files removed)":""}`,"info"),r==null||r())}catch{P("Failed to delete project","error")}finally{m(!1),d(null)}},O=async()=>{if(S){u(!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?(P(`Project "${e}" moved to "${S}"`,"success"),d(null),k(""),o==null||o()):P(B.error??"Failed to move project","error")}catch{P("Failed to move project","error")}finally{u(!1)}}};if(!i)return null;const R={padding:"12px 15px",borderTop:"1px solid var(--hair)",display:"flex",flexDirection:"column",gap:"10px"},T=($,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 l("section",{style:{borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",overflow:"hidden"},"aria-label":"Project settings",children:[l("div",{class:"flex items-center flex-wrap",style:{padding:"10px 15px",gap:"8px 12px"},children:[l("div",{class:"flex-1 min-w-0 flex flex-col",style:{gap:"2px",fontSize:"12.5px",color:"var(--ink-2)"},children:[A.length>0&&l("span",{class:"truncate",title:A.join(", "),children:["MCP · ",A.join(", ")]}),g.length>0&&l("span",{class:"truncate",title:g.join(", "),children:["Plugins · ",g.join(", ")]}),A.length===0&&g.length===0&&t("span",{children:"No MCPs or plugins for this project"})]}),h.length>0&&t("button",{type:"button",class:"cursor-pointer",style:T("ink",s==="move"),"aria-expanded":s==="move",onClick:()=>L("move"),children:"Move to account"}),t("button",{type:"button",class:"cursor-pointer",style:T("red",s==="delete"),"aria-expanded":s==="delete",onClick:()=>L("delete"),children:"Delete project"})]}),s==="move"&&l("div",{style:R,children:[l("p",{style:{fontSize:"13px"},children:['Move "',e,'" to a different account.']}),l("select",{class:"field",value:S,onChange:$=>k($.target.value),children:[t("option",{value:"",children:"Select account…"}),h.map($=>t("option",{value:$,children:$},$))]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:w?"Moving…":"Move project",variant:"primary",size:"sm",loading:w,disabled:!S,onClick:O}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),k("")}})]})]}),s==="delete"&&l("div",{style:R,children:[l("p",{style:{fontSize:"13px"},children:['This unregisters "',e,'" from CW.']}),l("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:$=>f($.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."}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:b?"Deleting…":x?"Delete project and files":"Unregister project",variant:"destructive",size:"sm",loading:b,onClick:N}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),f(!1)}})]})]})]})},wr=e=>e.trim().replace(/\s+/g,"-").toLowerCase();function Xt(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:wr(n)}:null}const ol="A PR link becomes a review. A Linear or Notion link becomes a dev task with its notes.";function ll(e,n){const a=Xt(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:ol,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 Qn=(e,n)=>{var a;return n??((a=Xt(e))==null?void 0:a.type)??"dev"},ke=Y(""),Ue=Y(null),Be=Y(""),qt=Y(""),Gt=e=>{ke.value=e,Ue.value=null},Zn=(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,il=(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 i=(s=e.harnesses.find(d=>d.name===n))==null?void 0:s.version,c=a==null?void 0:a.model;return[r?"Default":i,c].filter(Boolean).join(" · ")||(r?"Default":"")},sl=({doctor:e,account:n,value:a,defaultHarness:r,isLoop:o,onChange:i,onOpenAccounts:c})=>l("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=Zn(s.name,d,o),f=he(s.name),b=a===s.name,m=(d==null?void 0:d.status)==="not_logged_in",S=il(e,s.name,d,s.name===r,x);return l("div",{role:"radio","aria-checked":b,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 ${b?"var(--blue)":"var(--hair)"}`,background:b?Z("--blue"):"var(--card)",boxShadow:b?"var(--shadow-s)":"none",opacity:x?.45:1},onClick:()=>{x||i(s.name)},onKeyDown:k=>{!x&&(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),i(s.name))},children:[t("span",{class:"shrink-0",style:{width:"8px",height:"8px",borderRadius:"50%",marginTop:"5px",background:f.color,boxShadow:b?`0 0 8px ${f.color}`:"none"}}),l("span",{class:"flex flex-col min-w-0",children:[t("span",{style:{fontSize:"12.5px",fontWeight:600},children:f.label}),t("span",{class:"truncate",style:{fontSize:"11.5px",color:"var(--ink-2)"},title:S,children:S}),m&&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:k=>{k.stopPropagation(),c()},onKeyDown:k=>k.stopPropagation(),children:"Connect"})]})]},s.name)})})]}),cl=({options:e,value:n,label:a,onPick:r,onClose:o})=>{const[i,c]=y(""),[s,d]=y(0),x=yt(),f=oe(null),b=i.trim().toLowerCase(),m=ee(()=>e.filter(w=>{var u;return!b||w.label.toLowerCase().includes(b)||((u=w.group)==null?void 0:u.toLowerCase().includes(b))}),[e,b]);F(()=>{const w=m.findIndex(u=>u.value===n);d(w>=0&&!b?w:0)},[b]),F(()=>{var w,u;(u=(w=f.current)==null?void 0:w.querySelector('[data-active="true"]'))==null||u.scrollIntoView({block:"nearest"})},[s]);const S=w=>{if(w.key==="ArrowDown")w.preventDefault(),d(u=>Math.min(u+1,m.length-1));else if(w.key==="ArrowUp")w.preventDefault(),d(u=>Math.max(u-1,0));else if(w.key==="Enter"){w.preventDefault();const u=m[s];u&&r(u.value)}else w.key==="Escape"&&(w.preventDefault(),w.stopPropagation(),o())};let k;return l("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:[l("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:i,style:{height:"30px",padding:"0 8px 0 27px",borderRadius:"8px",fontSize:"12.5px",background:"var(--elev)"},onInput:w=>c(w.target.value)})]}),l("div",{ref:f,role:"listbox","aria-label":a,class:"overflow-y-auto min-h-0",style:{marginTop:"6px"},children:[m.length===0&&l("p",{style:{padding:"8px 10px",fontSize:"12.5px",color:"var(--ink-3)"},children:["No match for “",i.trim(),"”."]}),m.map((w,u)=>{const h=w.group&&w.group!==k?w.group:null;k=w.group;const v=u===s,p=w.value===n;return l("div",{children:[h&&t("div",{style:{padding:"7px 9px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:h}),l("button",{type:"button",role:"option","aria-selected":p,"data-active":v,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"8px",padding:"6px 9px",borderRadius:"8px",border:0,background:v?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px"},onMouseMove:()=>{v||d(u)},onClick:()=>r(w.value),children:[t("span",{class:"flex-1 truncate",style:{fontWeight:p?600:400,color:w.value?"var(--ink)":"var(--ink-2)"},children:w.label}),p&&t("span",{class:"i-lucide-check shrink-0",style:{width:"13px",height:"13px",color:"var(--blue)"}})]})]},w.value||"__empty")})]})]})},Sr=({label:e,value:n,options:a,onChange:r,placeholder:o="Choose…",size:i="sm",width:c})=>{const[s,d]=y(!1),x=oe(null),f=a.find(m=>m.value===n);return F(()=>{if(!s)return;const m=S=>{x.current&&!x.current.contains(S.target)&&d(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[s]),l("div",{ref:x,class:"relative",style:{width:c},children:[l("button",{type:"button","aria-haspopup":"listbox","aria-expanded":s,"aria-label":e,class:"field flex items-center text-left cursor-pointer",style:i==="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(m=>!m),onKeyDown:m=>{m.key==="ArrowDown"&&(m.preventDefault(),d(!0))},children:[t("span",{class:"flex-1 truncate",style:{color:f&&f.value?"var(--ink)":"var(--ink-2)"},children:(f==null?void 0:f.label)??o}),t("span",{class:"i-lucide-chevrons-up-down shrink-0",style:{width:"12px",height:"12px",color:"var(--ink-3)"}})]}),s&&t(cl,{options:a,value:n,label:e,onPick:m=>{r(m),d(!1)},onClose:()=>d(!1)})]})},En=(e,n,a=Object.keys(e))=>{const r=o=>{const i=n.indexOf(o);return i<0?n.length:i};return[...a].sort((o,i)=>r(e[o].account)-r(e[i].account)||o.localeCompare(i)).map(o=>({value:o,label:o,group:e[o].account}))},Cr=({ctx:e,size:n="md"})=>{const{text:a,ready:r}=ll(ke.value,{...e,harness:he(e.harness).label}),o=r&&(e.type==="general"||Xt(ke.value)!==null);return l("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})]})},$r=({fill:e})=>t(se,{fill:e,label:"Task type",tabs:Ge.map(n=>({id:n.key,label:Hn(n.key)})),active:Qn(ke.value,Ue.value),onChange:n=>{Ue.value=n}}),dl={width:"auto",maxWidth:"180px",height:"30px",padding:"0 26px 0 10px",borderRadius:"9px",fontSize:"12.5px",background:"var(--bg-2)"},pl=({label:e,value:n,onChange:a,options:r})=>l("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:dl,value:n,onChange:o=>a(o.target.value),children:r.map(o=>t("option",{value:o.value,children:o.label},o.value))})]}),ul=({projects:e,accounts:n,onStarted:a,onOpenDrawer:r})=>{var p,z;const[o,i]=y(!1),c=Zt.value,s=c!=null&&c.available?c.doctor:null,d=Qn(ke.value,Ue.value),x=d==="general",f=Be.value,b=Object.keys(e).sort(),m=x?qt.value||((p=e[f])==null?void 0:p.account)||n[0]||"":((z=e[f])==null?void 0:z.account)??"",S=b.filter(g=>e[g].account===m),k=d==="loop"?"claude":s?Oa(f||void 0,m,e,s):"claude",w=ke.value.trim(),u=o||(x?!m:!w||!f),h=async()=>{if(u)return;const g=s?Pe(s,m,k):void 0,A=s?Zn(k,g,d==="loop"):null,L=!x&&sr(c,k,w);if(d==="loop"||A||L||(g==null?void 0:g.status)==="not_logged_in"){r();return}i(!0);try{const R=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x?{type:d,account:m,project:f||void 0,harness:s?k:void 0}:{type:d,project:f,task:w,account:m||void 0,harness:s?k:void 0})})).json();R.ok?(P(x?"Session started":d==="review"?"Review started":"Task started","success"),x||Gt(""),a(R.session)):P(R.error??"Failed to start","error")}catch{P("Failed to start","error")}finally{i(!1)}},v=g=>{var A;qt.value=g,f&&((A=e[f])==null?void 0:A.account)!==g&&(Be.value="")};return l("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:[l("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:ke.value,onInput:g=>Gt(g.target.value),onKeyDown:g=>{g.key==="Enter"&&h()}}),t($r,{}),t("button",{type:"button",disabled:u,class:u?"":"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:u&&!o?"var(--elev)":"linear-gradient(180deg, var(--blue-2), var(--blue))",color:u&&!o?"var(--ink-3)":"#fff",boxShadow:u&&!o?"none":"var(--shadow-m)",opacity:u&&!o?.8:1,cursor:u?"not-allowed":"pointer"},onClick:()=>void h(),children:o?"Starting…":x?"Launch":"Start"})]}),l("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(Cr,{ctx:{type:d,project:f,account:m,harness:k}})}),x&&t(pl,{label:"Account",value:m,onChange:v,options:n.map(g=>({value:g,label:g}))}),l("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(Sr,{label:"Project",value:f,onChange:g=>{Be.value=g},placeholder:x?"No project":"Choose…",options:x?[{value:"",label:"No project"},...En(e,n,S)]:En(e,n,b)})]})]})]})},Ve=({title:e,subtitle:n,leading:a,children:r,sticky:o=!0,size:i="lg"})=>l("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(Xn,{}),a,l("div",{class:"min-w-0",children:[t("h1",{class:"truncate",style:{fontSize:i==="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})]}),hl=({label:e="Tasks",onClick:n})=>l("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]}),Xn=()=>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"}})}),Ln=Y({}),ga=new Set;function fl(e){!e||ga.has(e)||(ga.add(e),fetch(`/api/cw/detect/${encodeURIComponent(e)}`).then(n=>n.ok?n.json():null).catch(()=>null).then(n=>{Ln.value={...Ln.value,[e]:n}}))}const zr=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 Rr(e){return F(()=>{fl(e)},[e]),Ln.value[e]}const xa=10,Tr="forge-task-layout",gl=()=>{try{return localStorage.getItem(Tr)==="project"?"project":"recent"}catch{return"recent"}},Ft={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",overflow:"hidden"},Bt={padding:"11px 15px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},xl=({project:e,account:n,sessions:a,index:r,openTabKeys:o,onSelectTask:i,onMarkDone:c})=>{const s=zr(Rr(e)),d=a.some(x=>o.has(q(x)));return l("section",{style:{...Ft,animation:`riseIn .4s var(--ease) ${r*70}ms both`},"aria-label":e||"No project",children:[l("div",{class:"flex items-center flex-wrap",style:{...Bt,gap:"10px"},children:[t($e,{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"}),l("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[a.length," task",a.length===1?"":"s"]})]}),a.map(x=>t(kr,{session:x,isOpenInTab:o.has(q(x)),onSelect:()=>i(x),onMarkDone:x.type==="login"?void 0:()=>c(x)},q(x)))]})},ml=({spaces:e,allSpaces:n,projects:a,accountNames:r,filterAccount:o,filterProject:i,onFilterProject:c,filterType:s,onFilterType:d,harnessNames:x,filterHarness:f,onFilterHarness:b,showDone:m,onShowDone:S,openTabKeys:k,onSelectTask:w,onMarkDone:u,onNewTask:h,onCreateProject:v,onRefresh:p,onStarted:z})=>{var H,ce;const[g,A]=y(gl),L=E=>{A(E);try{localStorage.setItem(Tr,E)}catch{}},N=ee(()=>e.filter(E=>E.status==="active"),[e]),O=ee(()=>e.filter(E=>E.status==="done"),[e]),R=ee(()=>n.filter(E=>E.status==="active").length,[n]),T=ee(()=>n.filter(E=>E.status==="done").length,[n]),$=ee(()=>n.filter(E=>E.status==="active"&&k.has(q(E))).length,[n,k]),B=ee(()=>n.filter(E=>E.status==="active"&&(!o||E.account===o)&&(!i||E.project===i)&&(!f||(E.harness??"claude")===f)),[n,o,i,f]),j=ee(()=>{const E=new Map;for(const Q of N){const te=le(Q),we=E.get(te)??[];we.push(Q),E.set(te,we)}return Array.from(E,([Q,te])=>({project:Q,sessions:te}))},[N]),W=i?((H=a[i])==null?void 0:H.account)??((ce=N[0])==null?void 0:ce.account):void 0,M=i?`${W?`${W} · `:""}${B.length} active`:`${R} active · ${T} done · ${$} agent${$===1?"":"s"} working`;return l(V,{children:[l(Ve,{title:i??"Tasks",subtitle:M,children:[t(I,{label:"Add project",variant:"secondary",onClick:v}),t(I,{label:"New task",variant:"primary",onClick:h})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"16px",maxWidth:"1180px"},children:[t(ul,{projects:a,accounts:r,onStarted:z,onOpenDrawer:h}),l("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},...Ge.map(E=>({id:E.key,label:Hn(E.key),count:B.filter(Q=>Q.type===E.sessionType).length}))],active:s??"all",onChange:E=>d(E==="all"?null:E)}),x.length>1&&t(se,{label:"Filter by harness",tabs:[{id:"all",label:"Any harness"},...x.map(E=>({id:E,label:he(E).label}))],active:f??"all",onChange:E=>b(E==="all"?null:E)}),t("span",{class:"flex-1"}),!i&&t(se,{size:"sm",label:"Order tasks",tabs:[{id:"recent",label:"Recent"},{id:"project",label:"By project"}],active:g,onChange:E=>L(E==="project"?"project":"recent")}),t("button",{type:"button","aria-pressed":m,class:"cursor-pointer transition-all duration-180 ease-spring",style:{padding:"6px 12px",borderRadius:"9px",border:"1px solid var(--hair)",background:m?"var(--card)":"transparent",color:m?"var(--ink)":"var(--ink-2)",fontSize:"12.5px",fontWeight:500,boxShadow:m?"var(--shadow-s)":"none"},onClick:()=>S(!m),children:m?"Hide done":"Show done"})]}),i&&t(rl,{project:i,account:W,accounts:r,onDeleted:()=>{c(null),p()},onMoved:p}),g==="recent"&&!i&&N.length>0&&l("section",{style:{...Ft,animation:"riseIn .4s var(--ease) both"},"aria-label":"Recently opened",children:[l("div",{class:"flex items-center",style:{...Bt,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"}),l("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[N.length," task",N.length===1?"":"s"]})]}),N.map(E=>t(kr,{session:E,showProject:!0,isOpenInTab:k.has(q(E)),onSelect:()=>w(E),onMarkDone:E.type==="login"?void 0:()=>u(E)},q(E)))]}),(g==="project"||i)&&j.map((E,Q)=>{var te;return t(xl,{project:E.project,account:((te=a[E.project])==null?void 0:te.account)??E.sessions[0].account,sessions:E.sessions,index:Q,openTabKeys:k,onSelectTask:w,onMarkDone:u},E.project)}),j.length===0&&l("section",{style:{...Ft,animation:"riseIn .4s var(--ease) both"},children:[i&&l("div",{class:"flex items-center",style:{...Bt,gap:"10px"},children:[t($e,{size:9}),t("span",{style:{fontSize:"14px",fontWeight:650,letterSpacing:"-0.01em"},children:i})]}),l("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||f?"No active tasks match these filters.":i?`No active tasks on ${i}.`:"No active tasks. Start something new."}),t(I,{label:"New task",variant:"primary",onClick:h})]})]}),m&&O.length>0&&l("section",{style:{...Ft,boxShadow:"var(--shadow-s)"},"aria-label":"Done",children:[l("div",{style:{...Bt,padding:"10px 15px",fontSize:"13px",fontWeight:600,color:"var(--ink-2)"},children:["Done · last ",Math.min(xa,O.length)," of ",O.length]}),O.slice(0,xa).map(E=>t(al,{session:E,onSelect:()=>w(E)},q(E)))]})]})]})},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"},He="inline-flex items-center gap-1 cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m hover:text-ink",jr={...Ie,color:"var(--ink-3)",boxShadow:"none"},Pr=({href:e,title:n,children:a})=>l("a",{class:He,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"}})]}),vl=({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 l("button",{type:"button",class:"inline-flex items-center gap-1 cursor-not-allowed",style:jr,disabled:!0,title:r,children:["GitHub ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]})}return t(Pr,{href:n.url,title:n.label,children:"GitHub"})},yl=({session:e})=>{const n=Gn(e);return n&&t(Pr,{href:n.url,title:n.url,children:n.label})},bl=({session:e,entry:n})=>{var x;const[a,r]=y(!1),o=oe(null);F(()=>{cr()},[]),F(()=>{if(!a)return;const f=b=>{o.current&&!o.current.contains(b.target)&&r(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[a]);const i=jn.value,c=i!=null&&i.enabled?i.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 l("button",{type:"button",class:"cursor-not-allowed",style:jr,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 f=>{r(!1);try{await Ko(e,f)}catch(b){P(b.message,"error")}};return c.length===1?l("button",{type:"button",class:He,style:Ie,onClick:()=>d(c[0].id),children:["Open in ",c[0].label]}):l("div",{class:"relative",ref:o,children:[l("button",{type:"button",class:He,style:Ie,"aria-expanded":a,onClick:()=>r(f=>!f),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(f=>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(f.id),children:f.label},f.id))})]})},kl={"--orange":"--red","--blue":"--purple","--purple":"--blue","--green":"--teal"},lt=({label:e,index:n,color:a="var(--ink)",bar:r,title:o,children:i})=>l("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:i}),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)"}})})]}),wl=({value:e,onChange:n,onSend:a,onCancel:r})=>{const o=yt();return l("form",{class:"flex items-center",style:{gap:"6px",marginTop:"6px"},onSubmit:i=>{i.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:i=>n(i.target.value),onKeyDown:i=>{i.key==="Escape"&&r()}}),t(I,{label:"Send",variant:"primary",size:"sm",disabled:!e.trim(),onClick:a})]})},Sl=({session:e,onOpen:n})=>{const a=le(e),r=hr(a),[o,i]=y(null);if(r.length===0)return null;const c=e.harness==="claude"&&e.status==="active",s=async()=>{if(o!=null&&o.trim())try{await ge("/api/kioku/remember",{project:a,sessionDir:vt(e),text:o}),P("Sent to the agent to remember","success"),i(null)}catch(d){P(pe(d),"error")}};return l("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:[l("div",{class:"flex items-center",style:{fontSize:"11.5px",color:"var(--ink-2)"},children:["Memory · ",Ht(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:()=>i(""),children:"Remember…"})]}),o!==null&&t(wl,{value:o,onChange:i,onSend:s,onCancel:()=>i(null)}),t("div",{class:"flex items-center flex-wrap",style:{gap:"4px",marginTop:"6px"},children:r.map((d,x)=>l("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(_e(d.tier)),color:`var(${_e(d.tier)})`},title:`${d.tier??"brain"} · ${d.pages} pages`,onClick:()=>n==null?void 0:n(a),children:re(d)})]},d.key))})]})},un=({title:e,items:n,tone:a,empty:r})=>l("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}),l("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))]})]}),Cl=({session:e,active:n,onDone:a,onOpenMemory:r})=>{const[o,i]=y(""),[c,s]=y(!1),[d,x]=y(!1),[f,b]=y(0),[m,S]=y(null),[k,w]=y(!1),u=q(e),h=vt(e),v=e.type==="task"||e.type==="review",p=xr(e,{poll:n&&e.type==="task"}),z=Un(e.type),g=e.type==="login",A=zr(Rr(g?"":le(e))),L=Ua(u).value,N=encodeURIComponent(e.project),O=encodeURIComponent(h),T=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal/${N}/${O}?k=${f}`;F(()=>{if(g)return;let E=!1;return Promise.all([fetch(`/api/cw/tools?project=${N}`).then(Q=>Q.json()).catch(()=>null),fetch(`/api/cw/git/branch/${N}/${O}`).then(Q=>Q.json()).catch(()=>null)]).then(([Q,te])=>{E||(Q&&S(Q),i((te==null?void 0:te.branch)||e.task||e.pr||""))}),()=>{E=!0}},[u]);const $=()=>{s(!1),b(E=>E+1)},B=(m==null?void 0:m.mcps)??[],j=(m==null?void 0:m.plugins)??[],W=(p==null?void 0:p.state)??null,M=(W==null?void 0:W.branch)??o,H=p?p.error!==null?"Changes unknown":Ho(p.state):"Checking changes…",ce=[le(e)||"no project",e.account,[Na(e),e.provider&&e.provider!=="native"?null:e.model].filter(Boolean).join(", "),`${e.opens} session${e.opens===1?"":"s"}`].filter(Boolean).join(" · ");return l("div",{class:"flex flex-col h-full min-w-0",children:[l("div",{class:"flex flex-col shrink-0",style:{padding:"14px 20px",gap:"12px"},children:[l("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(${kl[z.token]??z.token}))`,boxShadow:"var(--shadow-m)",color:"#fff",fontSize:"13px",fontWeight:700},"aria-hidden":"true",children:z.glyph}),l("div",{class:"min-w-0",children:[t("h1",{class:"truncate",style:{fontSize:"19px",fontWeight:700,letterSpacing:"-0.02em"},children:ue(e)}),t("p",{class:"truncate",style:{marginTop:"1px",fontSize:"12.5px",color:"var(--ink-2)"},children:ce}),!g&&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"}}),l("div",{class:"flex flex-wrap items-center",style:{gap:"7px"},children:[!g&&t("button",{type:"button",class:He,style:Ie,"aria-expanded":k,onClick:()=>w(E=>!E),children:k?"Hide context":`Context · ${B.length} MCP, ${j.length} plugins`}),!g&&t(yl,{session:e}),!g&&t(vl,{entry:p}),!g&&t(bl,{session:e,entry:p}),c&&t(I,{label:"Restart",variant:"secondary",size:"sm",onClick:$}),e.status==="active"&&!g&&t(I,{label:"Mark done",variant:"primary",size:"sm",onClick:a})]})]}),!g&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(138px, 1fr))",gap:"9px"},children:[t(lt,{index:0,label:"Context used",color:"var(--blue)",bar:(L==null?void 0:L.context)??null,title:"Read from the harness status line",children:(L==null?void 0:L.context)!=null?`${Math.round(L.context)}%`:"—"}),t(lt,{index:1,label:"Tokens",children:(L==null?void 0:L.tokens)!=null?Ha(L.tokens):"—"}),t(lt,{index:2,label:"Cost",color:"var(--green)",children:(L==null?void 0:L.cost)!=null?qa(L.cost):"—"}),v&&t(lt,{index:3,label:"Commits",children:(W==null?void 0:W.commits)??"—"}),v&&t(lt,{index:4,label:"Unpushed",color:W&&gt(W)>0?"var(--orange)":"var(--ink)",children:W?gt(W):"—"}),t(Sl,{session:e,onOpen:r}),M&&l("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:()=>Jn(M,"Branch"),children:[l("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:M})]})]}),k&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:"9px",animation:"riseIn .3s var(--ease) both"},children:[t(un,{title:`MCP · ${B.length}`,tone:"--blue",empty:"No MCP servers",items:B.map(E=>({name:E.name,title:`${E.type} · ${E.source}`}))}),t(un,{title:`Plugins · ${j.length}`,tone:"--green",empty:"No plugins",items:j.map(E=>({name:E.name,muted:!E.enabled,title:`${E.enabled?"enabled":"disabled"} · ${E.marketplace}${E.hasMcp?` · MCP ${E.mcpName??""}`:""}`}))}),t(un,{title:"Stack",tone:null,empty:"Nothing detected",items:A.map(E=>({name:E}))})]})]}),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:l("div",{class:"absolute inset-0 flex flex-col",children:[l("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"}}),l("span",{class:"mono truncate",style:{fontSize:"11px",color:"#8a8a92",marginLeft:"6px"},children:[M||ue(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"})]}),l("div",{class:"relative flex-1 min-h-0",style:{padding:"12px 6px 6px 14px"},children:[t(Jr,{wsUrl:T,theme:mt.value,focused:n,onOutput:E=>vo(u,E),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…"})})]})]})})]})},me={fontSize:"12px",color:"var(--ink-2)"},ne=e=>e.target.value,U=({label:e,plain:n,children:a})=>l(n?"div":"label",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:me,children:e}),a]}),$l={dev:"New dev task",review:"Review a pull request",loop:"New loop",general:"New session"},zl={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."},Rl={dev:"Task name or ticket URL",review:"Pull request number or URL",loop:"Loop prompt",general:""},Tl={dev:"fix-auth or https://linear.app/…",review:"42 or https://github.com/…/pull/42",loop:"Babysit my open PRs…",general:""},jl=[{id:"",label:"Auto"},{id:"feature",label:"feature"},{id:"bugfix",label:"bugfix"},{id:"refactor",label:"refactor"}],hn={boxShadow:"var(--shadow-s)"},At=e=>/^[\w./:#-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Pl=({projects:e,accounts:n,initialAccount:a,initialProject:r,onClose:o,onCreated:i,onOpenAccounts:c})=>{var Rt;const s=Qn(ke.value,Ue.value),[d,x]=y(""),[f,b]=y(""),[m,S]=y(""),[k,w]=y(""),[u,h]=y(""),[v,p]=y(!1),[z,g]=y(!1),[A,L]=y(""),[N,O]=y("claude"),R=yt();F(()=>{ve()},[]);const T=Zt.value,$=T!=null&&T.available?T.doctor:null,B=Object.keys(e),j=s==="general",W=s==="review",M=s==="loop",H=ke.value,ce=!A.trim()||/^\d+[smh]$/.test(A.trim()),E=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??_,D=C&&E.includes(C)?C:E[0]??"";x(D);const K=D?B.filter(ae=>{var X;return((X=e[ae])==null?void 0:X.account)===D}):B,G=r&&K.includes(r)?r:!j&&K.length>0?K[0]:"";G&&b(G)},[]);const te=oe(!1);F(()=>{if(!te.current){te.current=!0;return}!j&&!f&&Q.length>0&&b(Q[0])},[j]);const we=_=>{x(_);const C=B.filter(D=>{var K;return((K=e[D])==null?void 0:K.account)===_});!j&&C.length>0&&!C.includes(f)?b(C[0]):j&&f&&!C.includes(f)&&b("")},kt=$?Oa(f||void 0,d,e,$):"claude";F(()=>{!$||!d||O(M?"claude":kt)},[T==null?void 0:T.available,d,f,M]);const Se=$?Pe($,d,N):void 0,wt=!$||Fe(T,N,"skip_permissions"),Ce=!$||N==="claude",Ne=Ce||!j,fe=$?Zn(N,Se,M):null,St=he(N).label;F(()=>{wt||p(!1),h(Ce?"":(Se==null?void 0:Se.model)??"")},[N]),F(()=>{Ce||h((Se==null?void 0:Se.model)??"")},[d]);const Ct=ir(H),Je=sr(T,N,H),$t=!j&&!H.trim()||M&&!ce||!j&&!f||!!fe,zt=async()=>{if(!$t){g(!0);try{const _={type:s,account:d||void 0,skipPermissions:v||void 0};$&&(_.harness=N),M?(_.project=f,_.loopPrompt=H.trim(),_.loopInterval=A.trim()||void 0):j?f&&(_.project=f):(_.project=f,_.task=H.trim(),_.description=m.trim()||void 0,_.workflow=k||void 0),_.model=Ne&&u||void 0;const D=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)})).json();D.ok?(P(j?"Session started":M?"Loop started":"Task started","success"),j||Gt(""),i(D.session)):P(D.error??"Failed to start","error")}catch{P("Failed to start","error")}finally{g(!1)}}},tn=d||E[0]||"default",nn=j?`cw launch ${At(tn)}`:M?`cw loop ${f||"<project>"} ${At(H.trim()||"<prompt>")}${A.trim()?` --every ${A.trim()}`:""}`:W?`cw review ${f||"<project>"} ${At(H.trim()||"<pr>")}`:`cw work ${f||"<project>"} ${H.trim()?At(((Rt=Xt(H))==null?void 0:Rt.kind)==="name"?wr(H):H.trim()):"<task>"}`;return l(qe,{title:$l[s],onClose:o,children:[t($r,{fill:!0}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",lineHeight:1.5},children:zl[s]}),!j&&l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t(U,{label:Rl[s],children:t("input",{class:"field",style:{...hn,fontSize:"14px"},placeholder:Tl[s],value:H,ref:R,onInput:_=>{const C=_.target.value;M?ke.value=C:Gt(C)},onKeyDown:_=>{_.key==="Enter"&&zt()}})}),!M&&t(Cr,{ctx:{type:s,project:f,account:d,harness:N},size:"sm"})]}),l("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;we(C),qt.value=C},children:E.map(_=>t("option",{value:_,children:_},_))})}),t(U,{plain:!0,label:j?"Project · optional":"Project",children:t(Sr,{label:"Project",size:"md",width:"100%",value:f,placeholder:j?"No project":"Choose…",onChange:_=>{b(_),Be.value=_},options:[...j?[{value:"",label:"No project"}]:[],...En(e,E,Q)]})})]}),M&&l(U,{label:"Interval · optional",children:[t("input",{class:"field mono",style:{...hn,borderColor:ce?void 0:"var(--red)"},value:A,placeholder:"auto — Claude decides the pace",onInput:_=>L(_.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"||W)&&t(U,{label:"Description (optional)",children:t("textarea",{class:"field",rows:3,style:hn,placeholder:"Context the agent reads first…",value:m,onInput:_=>S(_.target.value)})}),$&&t(sl,{doctor:$,account:d,value:N,defaultHarness:kt,isLoop:M,onChange:O,onOpenAccounts:c}),Ne&&l("div",{class:"grid",style:{gridTemplateColumns:s==="dev"?"1fr 1fr":"1fr",gap:"10px"},children:[l("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:me,children:"Model"}),Ce?t(se,{fill:!0,size:"sm",label:"Model",tabs:lo.map(_=>({id:_.id,label:_.label})),active:u,onChange:h}):t("input",{class:"field mono",style:{height:"32px",fontSize:"12.5px"},value:u,placeholder:"the account's model","aria-label":"Model",onInput:_=>h(_.target.value)})]}),s==="dev"&&l("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:me,children:"Workflow"}),t(se,{fill:!0,size:"sm",label:"Workflow",tabs:jl,active:k,onChange:w})]})]}),wt&&l("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:[l("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(Kn,{checked:v,onChange:p,label:"Bypass permissions"})]}),Je&&l("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(I,{label:z?"Starting…":j?"Launch session":M?"Start loop":W?"Start review":"Start task",variant:"primary",size:"lg",block:!0,loading:z,disabled:$t,onClick:zt}),fe&&t("p",{style:{fontSize:"12px",color:"var(--red)",textAlign:"center"},children:fe}),t("p",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)",textAlign:"center",overflowWrap:"anywhere"},children:nn})]})},Vt=Y(null),Nn=Y(null);async function ea(){const e=await fetch("/api/skills/plugins");if(!e.ok)throw new Error("fetch failed");Vt.value=await e.json()}async function On(){const e=await fetch("/api/skills/marketplaces");if(!e.ok)throw new Error("fetch failed");Nn.value=await e.json()}const Le=({title:e,sub:n,children:a})=>l("div",{class:"glass flex items-center flex-wrap shrink-0",style:{gap:"10px",padding:"12px 20px",borderBottom:"1px solid var(--hair)"},children:[l("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 Al(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 Il(e){return`add-skill-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,30).replace(/-+$/,"")||Date.now()}`}function El(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 Ar=e=>`/api/skills/plugins/${encodeURIComponent(e)}`;async function ta(e,n){try{return await ge(e,n)}catch(a){return P(pe(a),"error"),null}}async function Ir(e,n,a){await ta("/api/skills/plugins/install",{id:e,account:a})&&(P(`${n} installed in ${a} · applies to new sessions`,"success"),await Promise.all([ea(),On()]).catch(()=>{}))}const Er=(e,n)=>n?e.skills.filter(a=>a.name.toLowerCase().includes(n)||a.description.toLowerCase().includes(n)):e.skills,Ll=({list:e,query:n,selected:a,onSelect:r})=>{const o=e.flatMap(i=>{const c=Er(i,n).length;return!n||c>0||i.name.toLowerCase().includes(n)?[{p:i,count:c}]:[]});return o.length===0?null:l("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:i,count:c})=>{const s=a===i.id;return l("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(i.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:i.name}),t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:c})]},i.id)})]})},ma={fontSize:"12px",fontWeight:600,color:"var(--ink-2)",margin:"0 0 8px"},Lr={gap:"10px",padding:"9px 12px",borderRadius:"11px",border:"1px solid var(--hair)",background:"var(--card)"},Nl=({plugin:e,install:n})=>{const[a,r]=y(!1),o=n.scope==="global"?"global":n.scopeRef,i=async()=>{r(!0);const c=await ta(`${Ar(e.id)}/update`,{scope:n.scope,scopeRef:n.scopeRef});r(!1),c&&(P(`${e.name} ${c.version??""} · applies to new sessions`,"success"),ea().catch(()=>{}))};return l("div",{class:"flex items-center",style:Lr,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(I,{label:a?"Updating…":"Update",variant:"secondary",size:"sm",loading:a,onClick:i})]})},Ol=({plugin:e,account:n})=>{const[a,r]=y(!1);return l("div",{class:"flex items-center",style:Lr,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(I,{label:a?"Installing…":"Install",variant:"secondary",size:"sm",loading:a,onClick:async()=>{r(!0),await Ir(e.id,e.name,n),r(!1)}})]})},Dl=({plugin:e,name:n,onBack:a})=>{const[r,o]=y(null),[i,c]=y(!1);return F(()=>{let s=!1;return o(null),c(!1),fetch(`${Ar(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]),l(V,{children:[t(Le,{title:n,sub:`${e.name} · read-only`,children:t(I,{label:"Back",variant:"secondary",size:"sm",onClick:a})}),l("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."}),i?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})]})]})},Wl=({plugin:e,accounts:n,query:a,onSelectSkill:r,onPropose:o})=>{const i=new Set(e.installs.map(s=>s.scopeRef)),c=n.filter(s=>!i.has(s));return l(V,{children:[l(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(I,{label:"Propose a skill",variant:"primary",size:"sm",onClick:o})]}),t("div",{class:"flex-1 min-h-0 overflow-auto",children:l("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&&l("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."]}),l("section",{children:[t("h3",{style:ma,children:"Accounts"}),l("div",{class:"flex flex-col",style:{gap:"6px"},children:[e.installs.map(s=>t(Nl,{plugin:e,install:s},`${s.scope}/${s.scopeRef}`)),c.map(s=>t(Ol,{plugin:e,account:s},s))]})]}),l("section",{children:[l("h3",{style:ma,children:["Skills (",e.skills.length,")"]}),t("div",{class:"flex flex-col",style:{gap:"4px"},children:Er(e,a).map(s=>l("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))})]})]})})]})},Ml=({accounts:e})=>{const[n,a]=y(""),r=e.includes(n)?n:e[0]??"",[o,i]=y(""),[c,s]=y(""),[d,x]=y(""),[f,b]=y(!1),[m,S]=y(null);F(()=>{Nn.value===null&&On().catch(()=>P("Failed to load marketplaces","error"))},[]);const k=Nn.value,w=(k==null?void 0:k.find(g=>g.name===o))??(k==null?void 0:k[0]),u=new Set((Vt.value??[]).flatMap(g=>g.installs.some(A=>A.scope==="account"&&A.scopeRef===r)?[g.id]:[])),h=c.trim().toLowerCase(),v=((w==null?void 0:w.plugins)??[]).filter(g=>!h||g.name.toLowerCase().includes(h)||g.description.toLowerCase().includes(h)),p=async()=>{b(!0);const g=await ta("/api/skills/marketplaces",{source:d.trim(),account:r});b(!1),g&&(P(`Marketplace added to ${r}`,"success"),x(""),await On().catch(()=>{}))},z=async(g,A)=>{S(g),await Ir(g,A,r),S(null)};return l(V,{children:[t(Le,{title:"Add a plugin",sub:r?`Claude Code only · installs into ${r}`:"Claude Code only"}),l("div",{class:"flex-1 min-h-0 overflow-auto flex flex-col",style:{padding:"14px 20px 20px",gap:"8px"},children:[l("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:g=>a(g.target.value),children:e.map(g=>t("option",{value:g,children:g},g))})}),k&&k.length>0&&t(U,{label:"Marketplace",children:t("select",{class:"field",value:w==null?void 0:w.name,onChange:g=>i(g.target.value),children:k.map(g=>l("option",{value:g.name,children:[g.name," · ",g.source]},g.name))})}),t(U,{label:"Add a marketplace",children:l("div",{class:"flex",style:{gap:"8px"},children:[t("input",{class:"field flex-1",value:d,placeholder:"owner/repo, git URL or path",onInput:g=>x(g.target.value),onKeyDown:g=>{g.key==="Enter"&&d.trim()&&p()}}),t(I,{label:f?"Adding…":"Add",variant:"secondary",size:"sm",loading:f,disabled:!d.trim()||!r,onClick:p})]})}),w&&w.plugins.length>0&&t("input",{class:"field",type:"search","aria-label":"Filter plugins",value:c,placeholder:`Filter ${w.plugins.length} plugins`,onInput:g=>s(g.target.value)})]}),k===null&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Loading marketplaces…"}),(k==null?void 0:k.length)===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"No marketplace yet. Add one above."}),w&&v.length===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:h?"No plugin matches.":"This marketplace lists no plugins."}),v.map((g,A)=>l("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(A,8)*40}ms both`},children:[l("div",{class:"flex-1 min-w-0",children:[l("div",{class:"flex items-center min-w-0",style:{gap:"8px"},children:[t("span",{class:"truncate",style:{fontSize:"13.5px",fontWeight:600},children:g.name}),g.category&&t("span",{class:"mono shrink-0",style:{fontSize:"11px",color:"var(--ink-3)"},children:g.category})]}),g.description&&t("div",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-2)"},title:g.description,children:g.description})]}),u.has(g.id)?t("span",{style:{fontSize:"12px",color:"var(--green)"},children:"Installed"}):t(I,{label:m===g.id?"Installing…":"Install",variant:"secondary",size:"sm",loading:m===g.id,disabled:m!==null||!r,onClick:()=>z(g.id,g.name)})]},g.id))]})]})},Fl=({plugin:e,accounts:n,onSubmit:a,onCancel:r})=>{const o=Al(e),i=e.installs.filter(u=>u.scope==="account").map(u=>u.scopeRef),c=n.find(u=>i.includes(u))??n[0]??"",[s,d]=y(""),[x,f]=y(o[0]??""),[b,m]=y(c),[S,k]=y(!1),w=async()=>{k(!0);try{await a(s.trim(),o.length>1?x:void 0,b)}finally{k(!1)}};return l(V,{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:l("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"14px",maxWidth:"560px"},children:[l("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:u=>d(u.target.value)})}),o.length>1&&t(U,{label:"Area",children:t("select",{class:"field",value:x,onChange:u=>f(u.target.value),children:o.map(u=>t("option",{value:u,children:u},u))})}),n.length>0&&t(U,{label:"Account",children:t("select",{class:"field",value:b,onChange:u=>m(u.target.value),children:n.map(u=>t("option",{value:u,children:u},u))})}),l("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(I,{label:S?"Starting…":"Start task",variant:"primary",loading:S,disabled:!s.trim()||!b,onClick:w}),t(I,{label:"Cancel",variant:"secondary",onClick:r})]})]})})]})},Bl={global:"--blue",account:"--orange",project:"--green"},It=e=>`${e.scope}/${e.scopeRef}/${e.dirName}`;function _l(e,n){return e==="global"?"global":e==="account"?`account/${encodeURIComponent(n)}`:`project/${encodeURIComponent(n)}`}const ct=e=>e.scope==="global"?"Global":`${e.scope==="account"?"Account":"Project"} · ${e.scopeRef}`,Kl=e=>e.scope==="global"?`~/.claude/skills/${e.dirName}`:e.scope==="account"?`~/.cw/accounts/${e.scopeRef}/skills/${e.dirName}`:`<${e.scopeRef}>/.claude/skills/${e.dirName}`,Ul={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."},Nr=e=>e[0]?{scope:"account",scopeRef:e[0]}:{scope:"global",scopeRef:"global"},Dn=e=>e.scope==="global"||e.scopeRef!=="",Or=({accounts:e,projects:n,value:a,onChange:r})=>{const o=i=>{const c=i==="account"?e:n;r({scope:i,scopeRef:i==="global"?"global":c.includes(a.scopeRef)?a.scopeRef:c[0]??""})};return l(V,{children:[l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:me,children:"Scope"}),t(se,{label:"Scope",tabs:[{id:"account",label:"Account"},{id:"project",label:"Project"},{id:"global",label:"Global"}],active:a.scope,onChange:i=>o(i)}),t("span",{style:{fontSize:"12px",color:"var(--ink-3)"},children:Ul[a.scope]})]}),a.scope!=="global"&&t(U,{label:a.scope==="account"?"Account":"Project",children:t("select",{class:"field",value:a.scopeRef,onChange:i=>r({...a,scopeRef:i.target.value}),children:(a.scope==="account"?e:n).map(i=>t("option",{value:i,children:i},i))})})]})},Hl=(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),Dr=(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(...Dr(o,n+" "))):a.push(`${n}${r}: ${String(o??"")}`);return a},ql=({skill:e,accounts:n,projects:a,onDeleted:r,onCopied:o,onRun:i})=>{const[c,s]=y(null),[d,x]=y(!0),[f,b]=y("SKILL.md"),[m,S]=y(""),[k,w]=y({}),[u,h]=y(!1),v=`/api/skills/${_l(e.scope,e.scopeRef)}/${encodeURIComponent(e.dirName)}`;F(()=>{let R=!1;return x(!0),b("SKILL.md"),fetch(v).then(T=>{if(!T.ok)throw new Error("fetch failed");return T.json()}).then(T=>{if(R)return;s(T);const $=Dr(T.frontmatter);S($.length>0?`---
3
- ${$.join(`
1
+ var Kr=Object.defineProperty;var Ur=(e,n,a)=>n in e?Kr(e,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[n]=a;var aa=(e,n,a)=>Ur(e,typeof n!="symbol"?n+"":n,a);import{jsxs as l,jsx as t,Fragment as G}from"preact/jsx-runtime";import{Fragment as Hr,Component as qr,render as Gr}from"preact";import{useState as b,useMemo as ee,useEffect as F,useRef as oe,useCallback as J}from"preact/hooks";import{signal as Y,computed as ja}from"@preact/signals";import{ToastContainer as Vr,Tabs as le,UsageMeter as Pa,ToggleSwitch as Kn,showToast as I,ActionButton as L,ForgeTerminal as Jr,Drawer as qe,EmptyState as je,Modal as Le,Badge as Aa}from"@forge-dev/ui";import{createPortal as Yr}from"preact/compat";import{definePanel as Qr,ModuleRequestError as Kt}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 i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function a(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=a(o);fetch(o.href,i)}})();const Ia="forge-theme",Zr=()=>{try{return localStorage.getItem(Ia)==="light"?"light":"dark"}catch{return"dark"}},vt=Y(Zr());document.documentElement.setAttribute("data-theme",vt.value);const La=e=>{vt.value=e,document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(Ia,e)}catch{}},ze=Y(!1),ra=()=>La(vt.value==="dark"?"light":"dark"),Xr=({sidebar:e,children:n})=>l("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(Vr,{})]}),oa=[["--blue","--purple"],["--teal","--blue"],["--orange","--red"],["--green","--teal"]],Ea=e=>oa[e%oa.length],Z=(e,n=18)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,Me={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)"},de={padding:"10px 14px",borderRadius:"12px",fontSize:"12.5px"},eo={personal:"--blue",project:"--green",client:"--green",team:"--purple"},_e=e=>eo[e??""]??"--ink-2",to={decision:"--purple",context:"--teal",playbook:"--green",memory:"--orange",instinct:"--red",rule:"--blue",skill:"--ink-2"},la=e=>to[e]??"--ink-3",jt=[{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:[]}],We=(e,n,a)=>({label:e,glyph:n,token:a,ink:`var(${a})`,fill:Z(a)}),Sn={task:We("Dev","D","--orange"),review:We("Review","R","--blue"),loop:We("Loop","L","--purple"),general:We("General","G","--green")},no={create:We("Create","C","--teal"),login:We("Login","A","--ink-2")},Un=e=>Sn[e]??no[e]??Sn.task,Ge=[{key:"dev",sessionType:"task"},{key:"review",sessionType:"review"},{key:"loop",sessionType:"loop"},{key:"general",sessionType:"general"}],Hn=e=>{var n;return Sn[((n=Ge.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"].label},ao=e=>{var n;return((n=Ge.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"},qn={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}},Ke=e=>!!(e&&(qn[e.state].attention||e.state==="exited"&&(e.exitCode??0)!==0)),Ut=e=>e.state==="exited"&&e.exitCode?`Exited with code ${e.exitCode}`:qn[e.state].label,Wt=e=>e.state==="exited"&&e.exitCode?"--red":qn[e.state].token,q=e=>e.sessionDir?`${e.project}::${e.sessionDir}`:`${e.project}::${e.task??e.pr}`,ie=e=>e.project==="__general"?"":e.project,yt=e=>e.sessionDir??(e.type==="review"?`review-pr-${e.pr}`:e.type==="loop"?`loop-${e.task}`:`task-${e.task}`),ue=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} · ${he(e.harness).label}`:e.task??"unknown",ro={linear:"Linear",notion:"Notion"},Gn=e=>{var a;const n=e.source?ro[e.source]:void 0;return n&&((a=e.source_url)!=null&&a.startsWith("https://"))?{label:n,url:e.source_url}:null},Yt=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`},Pt=(e,n)=>({label:e,color:`var(--forge-harness-${n})`,bg:Z(`--forge-harness-${n}`)}),oo={claude:Pt("Claude Code","claude"),codex:Pt("Codex","codex"),pi:Pt("Pi","pi"),opencode:Pt("OpenCode","opencode")},he=e=>oo[e??"claude"]??{label:e??"claude",color:"var(--ink-3)",bg:"var(--elev)"},Na=e=>{const n=he(e.harness).label;return e.provider&&e.provider!=="native"?`${n} · ${e.model||e.provider}`:n},lo=[{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"}],Oa=(e,n,a,r)=>{var o,i;return(e?(o=a[e])==null?void 0:o.harness:void 0)??((i=r.accounts.find(c=>c.name===n))==null?void 0:i.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)},io=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,so=new Intl.DateTimeFormat(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}),Wa=(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 ${so.format(Math.round(a/6e4)*6e4)}`;const i=r%60;return`resets in ${o} h${i?` ${i} m`:""}`},Da=e=>e.map(n=>({label:n.label,percent:n.percent,severity:n.severity,scope:n.scope,reset:Wa(n.resetsAt)})),Ma=Y(null);async function co(){const e=await fetch("/api/health");Ma.value=(await e.json()).version??null}const it=Y(null);async function Fa(){const e=await fetch("/api/skills");if(!e.ok)throw new Error("fetch failed");it.value=await e.json()}const $e=({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"}})},an=5,Ba="forge-sidebar-collapsed",po=()=>{try{const e=localStorage.getItem(Ba);return e?JSON.parse(e):[]}catch{return[]}},uo=(e,n)=>Number(n.live)-Number(e.live)||n.count-e.count||e.name.localeCompare(n.name),ho=({projects:e,accounts:n,selected:a,onSelect:r,onAdd:o})=>{const[i,c]=b(""),[s,d]=b(po),[x,h]=b([]),y=i.trim().toLowerCase(),v=ee(()=>{const w=[...n,...e.map(k=>k.account).filter(k=>!n.includes(k))];return Array.from(new Set(w)).map((k,p)=>({account:k,index:p,items:e.filter(f=>f.account===k&&(!y||f.name.toLowerCase().includes(y))).sort(uo),active:e.filter(f=>f.account===k).reduce((f,m)=>f+m.count,0)})).filter(k=>k.items.length>0)},[e,n,y]),S=w=>{const k=s.includes(w)?s.filter(p=>p!==w):[...s,w];d(k);try{localStorage.setItem(Ba,JSON.stringify(k))}catch{}};return l("div",{class:"flex flex-col sb-section min-h-0",style:{gap:"6px",flex:"0 1 auto",minHeight:"120px"},children:[l("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"}})})]}),l("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:i,style:{height:"28px",padding:"0 8px 0 27px",borderRadius:"8px",fontSize:"12.5px",background:"var(--elev)"},onInput:w=>c(w.target.value),onKeyDown:w=>{w.key==="Escape"&&c("")}})]}),l("div",{class:"flex flex-col overflow-y-auto min-h-0",style:{gap:"8px",overscrollBehavior:"contain"},children:[v.length===0&&l("p",{style:{padding:"4px 9px",fontSize:"12px",color:"var(--ink-3)"},children:["No project matches “",i.trim(),"”."]}),v.map(w=>{const k=y!==""||!s.includes(w.account),p=y!==""||x.includes(w.account)||w.items.some((g,$)=>$>=an&&g.name===a),f=p?w.items:w.items.slice(0,an),[m,u]=Ea(w.index),T=w.items.some(g=>g.live);return l("div",{class:"flex flex-col shrink-0",style:{gap:"1px"},children:[l("button",{type:"button","aria-expanded":k,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(w.account),children:[t("span",{class:"i-lucide-chevron-right shrink-0",style:{width:"11px",height:"11px",color:"var(--ink-3)",transform:k?"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:w.account.charAt(0).toUpperCase()}),t("span",{class:"flex-1 truncate",style:{fontSize:"12px",fontWeight:600},children:w.account}),T&&t($e,{size:5,live:!0,glow:!1}),t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},title:`${w.items.length} projects · ${w.active} active tasks`,children:w.items.length})]}),k&&l("div",{class:"flex flex-col",style:{gap:"1px",marginLeft:"13px",paddingLeft:"6px",borderLeft:"1px solid var(--hair)",animation:"riseIn .24s var(--ease) both"},children:[f.map(g=>{const $=a===g.name;return l("button",{type:"button","aria-pressed":$,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 ${$?"var(--hair)":"transparent"}`,background:$?"var(--card)":"transparent",boxShadow:$?"var(--shadow-s)":"none"},onClick:()=>r(g.name),children:[t($e,{size:6,live:g.live}),t("span",{class:"flex-1 truncate",style:{fontWeight:$?600:450,opacity:g.count>0||g.live||$?1:.62},children:g.name}),g.count>0&&t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:g.count})]},g.name)}),w.items.length>an&&y===""&&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:()=>h(p?x.filter(g=>g!==w.account):[...x,w.account]),children:p?"Show less":`Show all ${w.items.length}`})]})]},w.account)})]})]})},_a={context:null,tokens:null,cost:null},fo=250,Ht=new Map,go=/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g,Qe=(e,n)=>{let a=null;for(const r of e.matchAll(n))a=r;return a},rn=e=>{const n=parseFloat(e),a=e.slice(-1).toLowerCase();return a==="k"?n*1e3:a==="m"?n*1e6:n};function xo(e){const n={},a=Qe(e,/(?:ctx|context)[:\s]*(\d{1,3}(?:\.\d+)?)\s*%/gi)??Qe(e,/[▓█▒░]+\s*(\d{1,3}(?:\.\d+)?)\s*%/g);a&&(n.context=Math.min(100,parseFloat(a[1])));const r=Qe(e,/(\d+(?:\.\d+)?[kKmM]?)\s*↑\s*(\d+(?:\.\d+)?[kKmM]?)\s*↓/g),o=Qe(e,/\((\d+(?:\.\d+)?[kKmM])\s*\/\s*\d+(?:\.\d+)?[kKmM]\)/g);r?n.tokens=rn(r[1])+rn(r[2]):o&&(n.tokens=rn(o[1]));const i=Qe(e,/\$(\d+\.\d{2})\b/g);return i&&(n.cost=parseFloat(i[1])),n}const Ka=e=>{let n=Ht.get(e);return n||(n={tail:"",timer:null,metrics:Y(_a)},Ht.set(e,n)),n},Ua=e=>Ka(e).metrics,mo=e=>{e.timer=null;const n=e.metrics.value,a={...n,...xo(e.tail)};(a.context!==n.context||a.tokens!==n.tokens||a.cost!==n.cost)&&(e.metrics.value=a)};function vo(e,n){const a=Ka(e);a.tail=(a.tail+n.slice(-4e3*2).replace(go,"")).slice(-4e3),a.timer||(a.timer=setTimeout(()=>mo(a),fo))}function yo(e){const n=Ht.get(e);n&&(n.timer&&clearTimeout(n.timer),n.metrics.value=_a,Ht.delete(e))}const Ha=e=>e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e),qa=e=>`$${e.toFixed(2)}`,ut=Y(null),bo=6e4;let Ze=null,Xe=null,on=0;function ia(e=!1){return Ze||(Ze=fetch(`/api/cw/usage${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(ut.value=n,Ze=null,n)),Ze)}function Ga(){return on+=1,ia(),Xe||(Xe=setInterval(()=>{document.visibilityState==="visible"&&ia()},bo)),()=>{on-=1,on===0&&Xe&&(clearInterval(Xe),Xe=null)}}const ko=(e,n)=>{var a;return((a=ut.value)!=null&&a.available?ut.value.usage.find(r=>r.account===e&&r.harness===n):null)??null},Ae=Y({}),sa=Y(null),Va=2e3,wo=15e3;let et=null,Ja=0,ln=!1;const Dt=new Set,So=(e,n)=>!!e&&Ke(n)&&(e.state!==n.state||e.since!==n.since);async function Ya(){if(!ln){ln=!0,Ja=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(So(a[r],o))for(const i of Dt)i(r,o)}catch{}finally{ln=!1}}}const Co=()=>{const e=document.visibilityState==="visible"?Va:wo;Date.now()-Ja>=e-100&&Ya()};function $o(e){return Dt.add(e),et||(Ya(),et=setInterval(Co,Va)),()=>{Dt.delete(e),Dt.size===0&&et&&(clearInterval(et),et=null)}}const Qa="forge.notify-sessions",Qt=typeof window<"u"&&"Notification"in window,zo=()=>{try{return Qt&&Notification.permission==="granted"&&localStorage.getItem(Qa)==="1"}catch{return!1}},Vn=Y(zo());async function Ro(e){if(e&&(!Qt||(Notification.permission==="default"?await Notification.requestPermission():Notification.permission)!=="granted"))return!1;Vn.value=e;try{localStorage.setItem(Qa,e?"1":"0")}catch{}return!0}function ca(e,n,a,r){if(!Vn.value||!Qt||Notification.permission!=="granted")return;const o=new Notification(e,{body:n,tag:a});o.onclick=()=>{window.focus(),r(),o.close()}}const be=Y([]),Mt=Y(!1),To=1e4;let tt=null,sn=0;async function ht(){try{const e=await fetch("/api/modules");e.ok&&(be.value=await e.json())}catch{}}const da=()=>{ht()};function jo(){return sn++,tt||(ht(),tt=setInterval(()=>{ht()},To),window.addEventListener("focus",da)),()=>{sn--,sn===0&&tt&&(clearInterval(tt),tt=null,window.removeEventListener("focus",da))}}const Za=e=>e.filter(n=>n.state!=="legacy"&&(n.view||n.state==="disabled")),Xa=e=>e.lastDenial?`Denied ${e.lastDenial.permission}: ${e.lastDenial.value}`:e.lastJobError??e.lastEventError??null,ft=Y([]),er=ja(()=>{var n;const e={};for(const a of ft.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}),tr=5e3,Po=15e3;let nt=null,nr=0,pa=!1,cn=!1;const Ft=new Set,ua=e=>`${e.moduleId}\0${e.key}\0${e.createdAt}`;async function ar(){if(!cn){cn=!0,nr=Date.now();try{const e=await fetch("/api/modules/notifications");if(!e.ok)return;const{items:n}=await e.json(),a=new Set(ft.value.map(ua));if(ft.value=n,pa){for(const r of n)if(r.kind==="attention"&&!r.seen&&!a.has(ua(r)))for(const o of Ft)o(r)}pa=!0}catch{}finally{cn=!1}}}const Ao=()=>{const e=document.visibilityState==="visible"?tr:Po;Date.now()-nr>=e-100&&ar()};function Io(e){return Ft.add(e),nt||(ar(),nt=setInterval(Ao,tr)),()=>{Ft.delete(e),Ft.size===0&&nt&&(clearInterval(nt),nt=null)}}async function Lo(e){ft.value=ft.value.map(n=>n.moduleId===e?{...n,seen:!0}:n),await fetch(`/api/modules/${encodeURIComponent(e)}/notifications/seen`,{method:"POST"}).catch(()=>{})}const rr=[{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"}],Cn="flex items-center w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",$n=e=>({borderRadius:"9px",border:`1px solid ${e?"var(--hair)":"transparent"}`,background:e?"var(--card)":"transparent",boxShadow:e?"var(--shadow-s)":"none",color:"var(--ink)"}),or="flex flex-col text-left cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m",zn={gap:"6px",padding:"9px 10px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",color:"var(--ink)"},Rn={fontSize:"10.5px",color:"var(--ink-3)"},Tn=({children:e})=>t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)",letterSpacing:".02em"},children:e}),Eo=({id:e,session:n,index:a,onOpen:r})=>{const o=Ua(e).value,i=Ae.value[e],c=Ke(i),s=n.type==="loop",d=(o==null?void 0:o.context)??null,[x,h]=a%2===0?["var(--blue)","var(--purple)"]:["var(--purple)","var(--blue)"],y=c?Ut(i):s?n.loop_interval?`every ${n.loop_interval}`:"self-paced":o&&(o.tokens!==null||o.cost!==null)?[o.tokens!==null?`${Ha(o.tokens)} tokens`:null,o.cost!==null?qa(o.cost):null].filter(Boolean).join(" · "):ie(n)||n.account;return l("button",{type:"button",class:or,style:c?{...zn,borderColor:`var(${Wt(i)})`}:zn,onClick:r,title:i?Ut(i):void 0,children:[l("span",{class:"flex items-center w-full",style:{gap:"6px"},children:[t($e,{size:6,color:i?`var(${Wt(i)})`:x,live:!i||i.state==="working"||c}),t("span",{class:"truncate",style:{fontSize:"12.5px",fontWeight:600},children:ue(n)}),t("span",{class:"flex-1"}),t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-2)"},children:d!==null?`${Math.round(d)}%`:"—"})]}),l("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}, ${h})`,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?{...Rn,color:`var(${Wt(i)})`,fontWeight:600}:Rn,children:y})]})},No=({view:e,onNavigate:n})=>{const a=Za(be.value),r=er.value,o=()=>{ze.value=!1,Mt.value=!0};return l("nav",{class:"flex flex-col sb-section",style:{gap:"2px"},"aria-label":"Modules",children:[l("div",{class:"flex items-center justify-between",style:{padding:"0 9px 4px"},children:[t(Tn,{children:"Modules"}),t("button",{type:"button","aria-label":"Add a module",title:"Add a module",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"}})})]}),a.length===0&&l("button",{type:"button",class:Cn,style:{...$n(!1),gap:"9px",height:"30px",padding:"0 9px",fontSize:"12.5px",color:"var(--ink-3)"},onClick:o,children:[t("span",{class:"i-lucide-package-plus shrink-0",style:{width:"15px",height:"15px"}}),t("span",{class:"flex-1 sb-label truncate",children:"Add a module"})]}),a.map(i=>{const c=`module:${i.id}`,s=e===c,d=i.state!=="enabled",x=d?null:Xa(i),h=r[i.id],y=i.color??"var(--ink-3)";return l("button",{type:"button","aria-current":s?"page":void 0,title:d?`${i.displayName} is disabled: ${i.reason??""}`:x??i.displayName,class:Cn,style:{...$n(s),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:s?600:450,opacity:d?.5:1},onClick:()=>n(c),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"18px",height:"18px",borderRadius:"5px",fontSize:"10px",fontWeight:600,background:s?`color-mix(in srgb, ${y} 18%, transparent)`:"var(--elev)",color:s?y:"var(--ink-3)"},children:i.displayName.charAt(0).toUpperCase()}),t("span",{class:"flex-1 sb-label truncate",children:i.displayName}),x&&t("span",{class:"sb-label","aria-label":"Has a warning",style:{width:"6px",height:"6px",borderRadius:"50%",background:"var(--orange)"}}),h&&h.attention>0&&t("span",{class:"mono sb-label","aria-label":`${h.attention} need you`,style:{fontSize:"10.5px",fontWeight:700,padding:"0 6px",borderRadius:"99px",color:"#fff",background:"var(--red)"},children:h.attention}),h&&h.badge>0&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:h.badge})]},`${i.id}-${i.source}`)})]})},Oo=()=>l("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(Kn,{checked:Vn.value,label:"Notify me when a session or module needs me",onChange:e=>{Ro(e).then(n=>{n||I("The browser blocked notifications for Forge","error")})}})]}),Wo=({account:e,harness:n,windows:a,stale:r,onOpen:o})=>{const i=a.reduce((s,d)=>d.percent>s.percent?d:s),c=he(n).label;return l("button",{type:"button",class:or,style:zn,onClick:o,title:`Usage limits for ${e} on ${c}`,children:[l("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(Pa,{bars:Da(a),size:"sm"}),t("span",{class:"mono truncate w-full",style:Rn,children:r?"last known values":Wa(i.resetsAt)})]})},Do=({view:e,counts:n,projects:a,accounts:r,selectedProject:o,live:i,onNavigate:c,onSelectProject:s,onAddProject:d,onOpenLive:x,onSearch:h})=>{var k;const y=Ma.value,v=rr.map(p=>{var f;return{...p,count:p.view==="skills"?((f=it.value)==null?void 0:f.length)??null:n[p.view]??null}});F(()=>Ga(),[]),F(()=>{co().catch(()=>{})},[]);const S=[...i].sort((p,f)=>Number(Ke(Ae.value[f.key]))-Number(Ke(Ae.value[p.key]))),w=(k=ut.value)!=null&&k.available?ut.value.usage.filter(p=>p.state==="ok"&&p.windows.some(f=>!f.scope)):[];return l("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:[l("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"}),y&&t("span",{class:"mono sb-label",style:{fontSize:"10px",color:"var(--ink-3)"},title:"Forge version",children:y})]}),h&&l("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:h,"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:v.map(p=>{const f=e===p.view;return l("button",{type:"button","aria-current":f?"page":void 0,title:p.label,class:Cn,style:{...$n(f),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:f?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:f?Z(p.token):"var(--elev)",color:f?`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(No,{view:e,onNavigate:c}),t(ho,{projects:a,accounts:r,selected:o,onSelect:s,onAdd:d}),l("div",{class:"flex flex-col",style:{marginTop:"auto",flex:"none",gap:"8px"},children:[i.length>0&&l("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Tn,{children:"Live now"})}),S.map((p,f)=>t(Eo,{id:p.key,session:p.session,index:f,onOpen:()=>x(p.session)},p.key))]}),w.length>0&&l("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Tn,{children:"Limits"})}),w.map(p=>t(Wo,{account:p.account,harness:p.harness,windows:p.windows.filter(f=>!f.scope),stale:p.stale,onOpen:()=>c("accounts")},`${p.account}/${p.harness}`))]}),Qt&&t("div",{class:"sb-section",children:t(Oo,{})}),t("div",{class:"sb-section",children:t(le,{fill:!0,size:"xs",label:"Appearance",tabs:[{id:"light",label:"Light"},{id:"dark",label:"Dark"}],active:vt.value,onChange:p=>La(p==="light"?"light":"dark")})})]})]})};function bt(){const e=oe(null);return F(()=>{var n;(n=e.current)==null||n.focus()},[]),e}const ha=(e,n,a)=>{const r=Un(e.type);return{id:q(e),label:ie(e)?`${ue(e)} · ${ie(e)}`:ue(e),hint:n,glyph:r.glyph,token:r.token,run:()=>a(e)}},Mo=({openTabs:e,sessions:n,projects:a,commands:r,onOpenSession:o,onSelectProject:i,onClose:c})=>{const[s,d]=b(""),[x,h]=b(0),y=oe(null),v=bt(),S=ee(()=>{const u=s.trim().toLowerCase(),T=O=>!u||O.label.toLowerCase().includes(u),g=new Set(e.map(q)),$=e.map((O,R)=>ha(O,R<5?`⌘${R+1}`:"open",o)),A=n.filter(O=>O.status==="active"&&!g.has(q(O))).map(O=>ha(O,"resume",o)),N=u?a.map(O=>({id:`project:${O}`,label:O,hint:"project",glyph:"P",token:"--green",run:()=>i(O)})):[];return[{name:"Live now",items:$.filter(T)},{name:"Tasks",items:A.filter(T).slice(0,u?12:6)},{name:"Projects",items:N.filter(T).slice(0,6)},{name:"Commands",items:r.filter(T)}].filter(O=>O.items.length>0)},[s,e,n,a,r,o,i]),w=S.flatMap(u=>u.items),k=Math.min(x,w.length-1);F(()=>{var u,T;(T=(u=y.current)==null?void 0:u.querySelector('[data-active="true"]'))==null||T.scrollIntoView({block:"nearest"})},[k]);const p=u=>{u&&(c(),u.run())},f=oe({flat:w,current:k,activate:p});f.current={flat:w,current:k,activate:p},F(()=>{const u=T=>{const{flat:g,current:$,activate:A}=f.current,N=g.length;T.key==="ArrowDown"?(T.preventDefault(),h(O=>N?(Math.min(O,N-1)+1)%N:0)):T.key==="ArrowUp"?(T.preventDefault(),h(O=>N?(Math.min(O,N-1)-1+N)%N:0)):T.key==="Enter"?(T.preventDefault(),A(g[$])):T.key==="Escape"&&(T.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:l("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:v,role:"combobox","aria-expanded":"true","aria-controls":"palette-list","aria-activedescendant":w[k]?`palette-${w[k].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),h(0)}}),l("div",{id:"palette-list",role:"listbox",ref:y,class:"overflow-auto",style:{padding:"6px"},children:[w.length===0&&l("p",{style:{padding:"14px 10px",fontSize:"13px",color:"var(--ink-2)"},children:["Nothing matches “",s,"”."]}),S.map(u=>l("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(T=>{m+=1;const g=m,$=g===k;return l("button",{id:`palette-${T.id}`,type:"button",role:"option","aria-selected":$,"data-active":$,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"10px",padding:"8px 10px",borderRadius:"10px",border:0,background:$?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px",transition:"background .14s"},onMouseMove:()=>{$||h(g)},onClick:()=>p(T),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"22px",height:"22px",borderRadius:"7px",fontSize:"10px",fontWeight:700,background:T.token?Z(T.token):"var(--elev)",color:T.token?`var(${T.token})`:"var(--ink-2)"},children:T.glyph}),t("span",{class:"flex-1 min-w-0 truncate",children:T.label}),t("span",{class:"mono shrink-0",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:T.hint})]},T.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))})]})})},Zt=Y(null),Fo=3e3;let at=null;function ve(e=!1){return at||(at=fetch(`/api/cw/harnesses${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(Zt.value=n,at=null,n)),at)}const gt=new Set;let st=null;const lr=()=>{gt.size===0&&st&&(clearInterval(st),st=null)},Bo=async()=>{const e=await ve(!0),n=Date.now();for(const a of gt){const r=e.available&&a.check(e.doctor);(r||n>a.deadline)&&(gt.delete(a),a.onDone(r))}lr()};function _o(e,{timeoutMs:n=6e5,onDone:a=()=>{}}={}){const r={check:e,deadline:Date.now()+n,onDone:a};return gt.add(r),st||(st=setInterval(Bo,Fo)),()=>{gt.delete(r),lr()}}const Fe=(e,n,a)=>{var r;return!!(e!=null&&e.available&&((r=e.capabilities[n])!=null&&r.includes(a)))},ir=e=>/linear\.app/.test(e)?"linear":/notion\.(so|site)/.test(e)?"notion":null,sr=(e,n,a)=>{const r=ir(a);return!!(e!=null&&e.available&&r&&!Fe(e,n,"mcp")&&!e.contextTokens[r])},jn=Y(null);let dn=null;function cr(){return dn||(dn=fetch("/api/cw/editors").then(e=>e.json()).then(e=>{jn.value=e}).catch(()=>{jn.value={enabled:!1,editors:[]}})),dn}async function Ko(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:yt(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 xt=e=>e.unpushed??e.commits??0,dr={OPEN:"open",MERGED:"merged",CLOSED:"closed"},Uo={passing:"✓",failing:"✗",pending:"…",none:""};function Ho(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=xt(e);if(a>0&&n.push(`${a} unpushed`),e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":dr[e.pr.state];n.push(`PR #${e.pr.number} ${r}`),e.pr.checks!=="none"&&n.push(`checks ${Uo[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 qo={passing:"checks pass",failing:"checks failing",pending:"checks running",none:""},fa=(e,n)=>`${e} ${n}${e===1?"":"s"}`;function Go(e){if(e.workspace==="missing")return"not created yet";if(e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":dr[e.pr.state];return[`PR #${e.pr.number} ${r}`,qo[e.pr.checks]].filter(Boolean).join(" · ")}const n=[];e.diff&&e.diff.files>0&&n.push(fa(e.diff.files,"file")),e.commits&&n.push(fa(e.commits,"commit"));const a=xt(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 pr(e,n,a){const r=await fetch(n,a===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),o=await r.json().catch(()=>({})),i=r.ok?o.error:o.error??o.message??`Request failed (${r.status})`;if(i)throw new Error(i);return o}const ge=(e,n)=>pr("POST",e,n),pe=e=>e instanceof Error?e.message:String(e);function Jn(e,n){navigator.clipboard.writeText(e).then(()=>I(`${n} copied`,"info"),()=>I(`Could not copy the ${n.toLowerCase()}`,"error"))}const Vo=({session:e,muted:n})=>{const a=he(e.harness);return l("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}}),Na(e)]})},ye=Y(null),Jo=6e4;let rt=null,ot=null,pn=0;function Re(e=!1){return rt&&!e||(rt=fetch(`/api/kioku/status${e?"?fresh=1":""}`).then(n=>n.json()).then(n=>{JSON.stringify(n)!==JSON.stringify(ye.value)&&(ye.value=n)}).catch(()=>{ye.value??(ye.value={installed:!1,version:null,brains:[],projects:{},activity:[],viewer:null})}).finally(()=>{rt=null})),rt}function ur(){return pn+=1,ye.value||Re(),ot||(ot=setInterval(()=>{document.visibilityState==="visible"&&Re()},Jo)),()=>{pn-=1,pn===0&&ot&&(clearInterval(ot),ot=null)}}const re=e=>e.name??e.key,qt=e=>e.reduce((n,a)=>n+a.pages,0);function Yn(e){const n=ye.value;return n!=null&&n.installed?(n.projects[e]??[]).flatMap(a=>n.brains.find(r=>re(r)===a.name)??[]):[]}function hr(e){return F(()=>ur(),[]),Yn(e)}const Yo=({project:e})=>{const[n,a]=b(null),r=hr(e);return r.length===0?null:l("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(re).join(", ")}`,onMouseEnter:o=>a(o.currentTarget.getBoundingClientRect()),onMouseLeave:()=>a(null),children:[t("span",{class:"inline-flex",children:r.map((o,i)=>t("span",{style:{width:"9px",height:"9px",borderRadius:"50%",background:`var(${_e(o.tier)})`,border:"2px solid var(--card)",marginLeft:i===0?0:"-4px"}},o.key))}),t("span",{class:"mono",children:qt(r)}),n&&Yr(l("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=>l("span",{class:"flex items-center",style:{gap:"7px",fontSize:"12px",color:"var(--ink)",fontWeight:500},children:[t($e,{color:`var(${_e(o.tier)})`}),re(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)]})},Pn=Y({}),fr=Y(0),Qo=6e4,At=new Map,gr=e=>`${e.project}::${yt(e)}`;function An(e,n=!1){const a=gr(e),r=At.get(a);if(r&&!n)return r;const o=`/api/cw/review-state/${encodeURIComponent(e.project)}/${encodeURIComponent(yt(e))}${n?"?fresh=1":""}`,i=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=>(Pn.value={...Pn.value,[a]:c},At.get(a)===i&&At.delete(a),c));return At.set(a,i),i}function Zo(){fr.value++}function xr(e,{poll:n=!1}={}){const a=gr(e),r=fr.value;return F(()=>{if(An(e),!n)return;const o=setInterval(()=>{An(e,!0)},Qo);return()=>clearInterval(o)},[a,n,r]),Pn.value[a]??null}const In=({type:e,size:n=28,radius:a=9,font:r=11})=>{const o=Un(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})},Xo=()=>l("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($e,{size:5,color:"var(--green)",live:!0,glow:!1}),"live"]}),mr=({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?l("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})},vr=({session:e})=>{const n=Gn(e);return n&&t(mr,{label:n.label,href:n.url})},el=({session:e})=>Gn(e)?t(vr,{session:e}):e.source?t("span",{class:"task-chip contents",children:t(mr,{label:e.source,href:e.source_url})}):null,yr=e=>e.type==="review"?`review/pr-${e.pr}`:e.type==="loop"?`loop/${e.task??"loop"}`:e.type==="task"?`task/${e.task}`:null,tl=({session:e,project:n})=>{var i;const a=xr(e),r=((i=a==null?void 0:a.state)==null?void 0:i.branch)??yr(e),o=a?a.error!==null?"changes unknown":Go(a.state):"checking…";return t(br,{branch:r,status:o,project:n})},br=({branch:e,status:n,project:a})=>l("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(),Jn(e,"Branch")},onKeyDown:r=>r.stopPropagation(),children:e}),t("span",{class:"whitespace-nowrap truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:n})]}),nl=e=>e.type==="loop"?e.loop_interval?`every ${e.loop_interval}`:"self-paced":`${e.opens} session${e.opens===1?"":"s"}`,kr=({session:e,isOpenInTab:n,onSelect:a,onMarkDone:r,showProject:o})=>{const i=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 l("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"} ${ue(e)}`,onKeyDown:h=>{h.target===h.currentTarget&&(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),a())},children:[t(In,{type:e.type}),l("div",{class:"flex-1 min-w-0",children:[l("div",{class:"flex items-center min-w-0",style:{gap:"8px"},children:[t("span",{class:"truncate",style:{fontSize:"14px",fontWeight:600},children:ue(e)}),n&&e.status==="active"&&t(Xo,{}),t(el,{session:e})]}),d?t(tl,{session:e,project:i}):t(br,{branch:yr(e),status:nl(e),project:i})]}),t(Yo,{project:ie(e)}),t(Vo,{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:Yt(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:h=>{h.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"})]})},al=({session:e,onSelect:n})=>l("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"}})}),l("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px"},children:[ue(e)," ",t("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:ie(e)})]}),t(vr,{session:e}),t("span",{class:"mono shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:Yt(e.closed??e.last_opened)})]}),rl=({project:e,account:n,accounts:a,onDeleted:r,onMoved:o})=>{const[i,c]=b(null),[s,d]=b(null),[x,h]=b(!1),[y,v]=b(!1),[S,w]=b(""),[k,p]=b(!1),f=(a??[]).filter(z=>z!==n);F(()=>{let z=!1;return fetch(`/api/cw/mcps?project=${encodeURIComponent(e)}`).then(B=>B.json()).catch(()=>null).then(B=>{z||c(B)}),()=>{z=!0}},[e]);const m=i?Object.keys(i.global):[],u=(i==null?void 0:i.project)??[],T=(i==null?void 0:i.cw)??[],g=(i==null?void 0:i.plugins)??[],$=[...u.map(z=>`${z} (project)`),...m,...T.map(z=>`${z} (CW)`)],A=z=>{d(s===z?null:z),w(""),h(!1)},N=async()=>{v(!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&&(I(`Project "${e}" deleted${x?" (files removed)":""}`,"info"),r==null||r())}catch{I("Failed to delete project","error")}finally{v(!1),d(null)}},O=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?(I(`Project "${e}" moved to "${S}"`,"success"),d(null),w(""),o==null||o()):I(B.error??"Failed to move project","error")}catch{I("Failed to move project","error")}finally{p(!1)}}};if(!i)return null;const R={padding:"12px 15px",borderTop:"1px solid var(--hair)",display:"flex",flexDirection:"column",gap:"10px"},j=(z,B)=>({padding:"5px 11px",borderRadius:"9px",border:"1px solid var(--hair)",fontSize:"12.5px",fontWeight:500,background:B?"var(--elev)":"var(--card)",color:z==="red"?"var(--red)":"var(--ink)",boxShadow:"var(--shadow-s)"});return l("section",{style:{borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",overflow:"hidden"},"aria-label":"Project settings",children:[l("div",{class:"flex items-center flex-wrap",style:{padding:"10px 15px",gap:"8px 12px"},children:[l("div",{class:"flex-1 min-w-0 flex flex-col",style:{gap:"2px",fontSize:"12.5px",color:"var(--ink-2)"},children:[$.length>0&&l("span",{class:"truncate",title:$.join(", "),children:["MCP · ",$.join(", ")]}),g.length>0&&l("span",{class:"truncate",title:g.join(", "),children:["Plugins · ",g.join(", ")]}),$.length===0&&g.length===0&&t("span",{children:"No MCPs or plugins for this project"})]}),f.length>0&&t("button",{type:"button",class:"cursor-pointer",style:j("ink",s==="move"),"aria-expanded":s==="move",onClick:()=>A("move"),children:"Move to account"}),t("button",{type:"button",class:"cursor-pointer",style:j("red",s==="delete"),"aria-expanded":s==="delete",onClick:()=>A("delete"),children:"Delete project"})]}),s==="move"&&l("div",{style:R,children:[l("p",{style:{fontSize:"13px"},children:['Move "',e,'" to a different account.']}),l("select",{class:"field",value:S,onChange:z=>w(z.target.value),children:[t("option",{value:"",children:"Select account…"}),f.map(z=>t("option",{value:z,children:z},z))]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(L,{label:k?"Moving…":"Move project",variant:"primary",size:"sm",loading:k,disabled:!S,onClick:O}),t(L,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),w("")}})]})]}),s==="delete"&&l("div",{style:R,children:[l("p",{style:{fontSize:"13px"},children:['This unregisters "',e,'" from CW.']}),l("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:z=>h(z.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."}),l("div",{class:"flex",style:{gap:"8px"},children:[t(L,{label:y?"Deleting…":x?"Delete project and files":"Unregister project",variant:"destructive",size:"sm",loading:y,onClick:N}),t(L,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),h(!1)}})]})]})]})},wr=e=>e.trim().replace(/\s+/g,"-").toLowerCase();function Xt(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:wr(n)}:null}const ol="A PR link becomes a review. A Linear or Notion link becomes a dev task with its notes.";function ll(e,n){const a=Xt(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:ol,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 Qn=(e,n)=>{var a;return n??((a=Xt(e))==null?void 0:a.type)??"dev"},ke=Y(""),Ue=Y(null),Be=Y(""),Gt=Y(""),Vt=e=>{ke.value=e,Ue.value=null},Zn=(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,il=(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 i=(s=e.harnesses.find(d=>d.name===n))==null?void 0:s.version,c=a==null?void 0:a.model;return[r?"Default":i,c].filter(Boolean).join(" · ")||(r?"Default":"")},sl=({doctor:e,account:n,value:a,defaultHarness:r,isLoop:o,onChange:i,onOpenAccounts:c})=>l("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=Zn(s.name,d,o),h=he(s.name),y=a===s.name,v=(d==null?void 0:d.status)==="not_logged_in",S=il(e,s.name,d,s.name===r,x);return l("div",{role:"radio","aria-checked":y,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 ${y?"var(--blue)":"var(--hair)"}`,background:y?Z("--blue"):"var(--card)",boxShadow:y?"var(--shadow-s)":"none",opacity:x?.45:1},onClick:()=>{x||i(s.name)},onKeyDown:w=>{!x&&(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),i(s.name))},children:[t("span",{class:"shrink-0",style:{width:"8px",height:"8px",borderRadius:"50%",marginTop:"5px",background:h.color,boxShadow:y?`0 0 8px ${h.color}`:"none"}}),l("span",{class:"flex flex-col min-w-0",children:[t("span",{style:{fontSize:"12.5px",fontWeight:600},children:h.label}),t("span",{class:"truncate",style:{fontSize:"11.5px",color:"var(--ink-2)"},title:S,children:S}),v&&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:w=>{w.stopPropagation(),c()},onKeyDown:w=>w.stopPropagation(),children:"Connect"})]})]},s.name)})})]}),cl=({options:e,value:n,label:a,onPick:r,onClose:o})=>{const[i,c]=b(""),[s,d]=b(0),x=bt(),h=oe(null),y=i.trim().toLowerCase(),v=ee(()=>e.filter(k=>{var p;return!y||k.label.toLowerCase().includes(y)||((p=k.group)==null?void 0:p.toLowerCase().includes(y))}),[e,y]);F(()=>{const k=v.findIndex(p=>p.value===n);d(k>=0&&!y?k:0)},[y]),F(()=>{var k,p;(p=(k=h.current)==null?void 0:k.querySelector('[data-active="true"]'))==null||p.scrollIntoView({block:"nearest"})},[s]);const S=k=>{if(k.key==="ArrowDown")k.preventDefault(),d(p=>Math.min(p+1,v.length-1));else if(k.key==="ArrowUp")k.preventDefault(),d(p=>Math.max(p-1,0));else if(k.key==="Enter"){k.preventDefault();const p=v[s];p&&r(p.value)}else k.key==="Escape"&&(k.preventDefault(),k.stopPropagation(),o())};let w;return l("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:[l("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:i,style:{height:"30px",padding:"0 8px 0 27px",borderRadius:"8px",fontSize:"12.5px",background:"var(--elev)"},onInput:k=>c(k.target.value)})]}),l("div",{ref:h,role:"listbox","aria-label":a,class:"overflow-y-auto min-h-0",style:{marginTop:"6px"},children:[v.length===0&&l("p",{style:{padding:"8px 10px",fontSize:"12.5px",color:"var(--ink-3)"},children:["No match for “",i.trim(),"”."]}),v.map((k,p)=>{const f=k.group&&k.group!==w?k.group:null;w=k.group;const m=p===s,u=k.value===n;return l("div",{children:[f&&t("div",{style:{padding:"7px 9px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:f}),l("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(k.value),children:[t("span",{class:"flex-1 truncate",style:{fontWeight:u?600:400,color:k.value?"var(--ink)":"var(--ink-2)"},children:k.label}),u&&t("span",{class:"i-lucide-check shrink-0",style:{width:"13px",height:"13px",color:"var(--blue)"}})]})]},k.value||"__empty")})]})]})},Sr=({label:e,value:n,options:a,onChange:r,placeholder:o="Choose…",size:i="sm",width:c})=>{const[s,d]=b(!1),x=oe(null),h=a.find(v=>v.value===n);return F(()=>{if(!s)return;const v=S=>{x.current&&!x.current.contains(S.target)&&d(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[s]),l("div",{ref:x,class:"relative",style:{width:c},children:[l("button",{type:"button","aria-haspopup":"listbox","aria-expanded":s,"aria-label":e,class:"field flex items-center text-left cursor-pointer",style:i==="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(v=>!v),onKeyDown:v=>{v.key==="ArrowDown"&&(v.preventDefault(),d(!0))},children:[t("span",{class:"flex-1 truncate",style:{color:h&&h.value?"var(--ink)":"var(--ink-2)"},children:(h==null?void 0:h.label)??o}),t("span",{class:"i-lucide-chevrons-up-down shrink-0",style:{width:"12px",height:"12px",color:"var(--ink-3)"}})]}),s&&t(cl,{options:a,value:n,label:e,onPick:v=>{r(v),d(!1)},onClose:()=>d(!1)})]})},Ln=(e,n,a=Object.keys(e))=>{const r=o=>{const i=n.indexOf(o);return i<0?n.length:i};return[...a].sort((o,i)=>r(e[o].account)-r(e[i].account)||o.localeCompare(i)).map(o=>({value:o,label:o,group:e[o].account}))},Cr=({ctx:e,size:n="md"})=>{const{text:a,ready:r}=ll(ke.value,{...e,harness:he(e.harness).label}),o=r&&(e.type==="general"||Xt(ke.value)!==null);return l("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})]})},$r=({fill:e})=>t(le,{fill:e,label:"Task type",tabs:Ge.map(n=>({id:n.key,label:Hn(n.key)})),active:Qn(ke.value,Ue.value),onChange:n=>{Ue.value=n}}),dl={width:"auto",maxWidth:"180px",height:"30px",padding:"0 26px 0 10px",borderRadius:"9px",fontSize:"12.5px",background:"var(--bg-2)"},pl=({label:e,value:n,onChange:a,options:r})=>l("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:dl,value:n,onChange:o=>a(o.target.value),children:r.map(o=>t("option",{value:o.value,children:o.label},o.value))})]}),ul=({projects:e,accounts:n,onStarted:a,onOpenDrawer:r})=>{var u,T;const[o,i]=b(!1),c=Zt.value,s=c!=null&&c.available?c.doctor:null,d=Qn(ke.value,Ue.value),x=d==="general",h=Be.value,y=Object.keys(e).sort(),v=x?Gt.value||((u=e[h])==null?void 0:u.account)||n[0]||"":((T=e[h])==null?void 0:T.account)??"",S=y.filter(g=>e[g].account===v),w=d==="loop"?"claude":s?Oa(h||void 0,v,e,s):"claude",k=ke.value.trim(),p=o||(x?!v:!k||!h),f=async()=>{if(p)return;const g=s?Pe(s,v,w):void 0,$=s?Zn(w,g,d==="loop"):null,A=!x&&sr(c,w,k);if(d==="loop"||$||A||(g==null?void 0:g.status)==="not_logged_in"){r();return}i(!0);try{const R=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x?{type:d,account:v,project:h||void 0,harness:s?w:void 0}:{type:d,project:h,task:k,account:v||void 0,harness:s?w:void 0})})).json();R.ok?(I(x?"Session started":d==="review"?"Review started":"Task started","success"),x||Vt(""),a(R.session)):I(R.error??"Failed to start","error")}catch{I("Failed to start","error")}finally{i(!1)}},m=g=>{var $;Gt.value=g,h&&(($=e[h])==null?void 0:$.account)!==g&&(Be.value="")};return l("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:[l("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:ke.value,onInput:g=>Vt(g.target.value),onKeyDown:g=>{g.key==="Enter"&&f()}}),t($r,{}),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 f(),children:o?"Starting…":x?"Launch":"Start"})]}),l("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(Cr,{ctx:{type:d,project:h,account:v,harness:w}})}),x&&t(pl,{label:"Account",value:v,onChange:m,options:n.map(g=>({value:g,label:g}))}),l("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(Sr,{label:"Project",value:h,onChange:g=>{Be.value=g},placeholder:x?"No project":"Choose…",options:x?[{value:"",label:"No project"},...Ln(e,n,S)]:Ln(e,n,y)})]})]})]})},Ve=({title:e,subtitle:n,leading:a,children:r,sticky:o=!0,size:i="lg"})=>l("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(Xn,{}),a,l("div",{class:"min-w-0",children:[t("h1",{class:"truncate",style:{fontSize:i==="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})]}),hl=({label:e="Tasks",onClick:n})=>l("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]}),Xn=()=>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"}})}),En=Y({}),ga=new Set;function fl(e){!e||ga.has(e)||(ga.add(e),fetch(`/api/cw/detect/${encodeURIComponent(e)}`).then(n=>n.ok?n.json():null).catch(()=>null).then(n=>{En.value={...En.value,[e]:n}}))}const zr=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 Rr(e){return F(()=>{fl(e)},[e]),En.value[e]}const xa=10,Tr="forge-task-layout",gl=()=>{try{return localStorage.getItem(Tr)==="project"?"project":"recent"}catch{return"recent"}},Bt={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",overflow:"hidden"},_t={padding:"11px 15px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},xl=({project:e,account:n,sessions:a,index:r,openTabKeys:o,onSelectTask:i,onMarkDone:c})=>{const s=zr(Rr(e)),d=a.some(x=>o.has(q(x)));return l("section",{style:{...Bt,animation:`riseIn .4s var(--ease) ${r*70}ms both`},"aria-label":e||"No project",children:[l("div",{class:"flex items-center flex-wrap",style:{..._t,gap:"10px"},children:[t($e,{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"}),l("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[a.length," task",a.length===1?"":"s"]})]}),a.map(x=>t(kr,{session:x,isOpenInTab:o.has(q(x)),onSelect:()=>i(x),onMarkDone:x.type==="login"?void 0:()=>c(x)},q(x)))]})},ml=({spaces:e,allSpaces:n,projects:a,accountNames:r,filterAccount:o,filterProject:i,onFilterProject:c,filterType:s,onFilterType:d,harnessNames:x,filterHarness:h,onFilterHarness:y,showDone:v,onShowDone:S,openTabKeys:w,onSelectTask:k,onMarkDone:p,onNewTask:f,onCreateProject:m,onRefresh:u,onStarted:T})=>{var H,ce;const[g,$]=b(gl),A=E=>{$(E);try{localStorage.setItem(Tr,E)}catch{}},N=ee(()=>e.filter(E=>E.status==="active"),[e]),O=ee(()=>e.filter(E=>E.status==="done"),[e]),R=ee(()=>n.filter(E=>E.status==="active").length,[n]),j=ee(()=>n.filter(E=>E.status==="done").length,[n]),z=ee(()=>n.filter(E=>E.status==="active"&&w.has(q(E))).length,[n,w]),B=ee(()=>n.filter(E=>E.status==="active"&&(!o||E.account===o)&&(!i||E.project===i)&&(!h||(E.harness??"claude")===h)),[n,o,i,h]),P=ee(()=>{const E=new Map;for(const Q of N){const te=ie(Q),we=E.get(te)??[];we.push(Q),E.set(te,we)}return Array.from(E,([Q,te])=>({project:Q,sessions:te}))},[N]),D=i?((H=a[i])==null?void 0:H.account)??((ce=N[0])==null?void 0:ce.account):void 0,M=i?`${D?`${D} · `:""}${B.length} active`:`${R} active · ${j} done · ${z} agent${z===1?"":"s"} working`;return l(G,{children:[l(Ve,{title:i??"Tasks",subtitle:M,children:[t(L,{label:"Add project",variant:"secondary",onClick:m}),t(L,{label:"New task",variant:"primary",onClick:f})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"16px",maxWidth:"1180px"},children:[t(ul,{projects:a,accounts:r,onStarted:T,onOpenDrawer:f}),l("div",{class:"flex items-center flex-wrap",style:{gap:"12px"},children:[t(le,{label:"Filter by type",tabs:[{id:"all",label:"All",count:B.length},...Ge.map(E=>({id:E.key,label:Hn(E.key),count:B.filter(Q=>Q.type===E.sessionType).length}))],active:s??"all",onChange:E=>d(E==="all"?null:E)}),x.length>1&&t(le,{label:"Filter by harness",tabs:[{id:"all",label:"Any harness"},...x.map(E=>({id:E,label:he(E).label}))],active:h??"all",onChange:E=>y(E==="all"?null:E)}),t("span",{class:"flex-1"}),!i&&t(le,{size:"sm",label:"Order tasks",tabs:[{id:"recent",label:"Recent"},{id:"project",label:"By project"}],active:g,onChange:E=>A(E==="project"?"project":"recent")}),t("button",{type:"button","aria-pressed":v,class:"cursor-pointer transition-all duration-180 ease-spring",style:{padding:"6px 12px",borderRadius:"9px",border:"1px solid var(--hair)",background:v?"var(--card)":"transparent",color:v?"var(--ink)":"var(--ink-2)",fontSize:"12.5px",fontWeight:500,boxShadow:v?"var(--shadow-s)":"none"},onClick:()=>S(!v),children:v?"Hide done":"Show done"})]}),i&&t(rl,{project:i,account:D,accounts:r,onDeleted:()=>{c(null),u()},onMoved:u}),g==="recent"&&!i&&N.length>0&&l("section",{style:{...Bt,animation:"riseIn .4s var(--ease) both"},"aria-label":"Recently opened",children:[l("div",{class:"flex items-center",style:{..._t,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"}),l("span",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[N.length," task",N.length===1?"":"s"]})]}),N.map(E=>t(kr,{session:E,showProject:!0,isOpenInTab:w.has(q(E)),onSelect:()=>k(E),onMarkDone:E.type==="login"?void 0:()=>p(E)},q(E)))]}),(g==="project"||i)&&P.map((E,Q)=>{var te;return t(xl,{project:E.project,account:((te=a[E.project])==null?void 0:te.account)??E.sessions[0].account,sessions:E.sessions,index:Q,openTabKeys:w,onSelectTask:k,onMarkDone:p},E.project)}),P.length===0&&l("section",{style:{...Bt,animation:"riseIn .4s var(--ease) both"},children:[i&&l("div",{class:"flex items-center",style:{..._t,gap:"10px"},children:[t($e,{size:9}),t("span",{style:{fontSize:"14px",fontWeight:650,letterSpacing:"-0.01em"},children:i})]}),l("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||h?"No active tasks match these filters.":i?`No active tasks on ${i}.`:"No active tasks. Start something new."}),t(L,{label:"New task",variant:"primary",onClick:f})]})]}),v&&O.length>0&&l("section",{style:{...Bt,boxShadow:"var(--shadow-s)"},"aria-label":"Done",children:[l("div",{style:{..._t,padding:"10px 15px",fontSize:"13px",fontWeight:600,color:"var(--ink-2)"},children:["Done · last ",Math.min(xa,O.length)," of ",O.length]}),O.slice(0,xa).map(E=>t(al,{session:E,onSelect:()=>k(E)},q(E)))]})]})]})},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"},He="inline-flex items-center gap-1 cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m hover:text-ink",jr={...Ie,color:"var(--ink-3)",boxShadow:"none"},Pr=({href:e,title:n,children:a})=>l("a",{class:He,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"}})]}),vl=({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 l("button",{type:"button",class:"inline-flex items-center gap-1 cursor-not-allowed",style:jr,disabled:!0,title:r,children:["GitHub ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]})}return t(Pr,{href:n.url,title:n.label,children:"GitHub"})},yl=({session:e})=>{const n=Gn(e);return n&&t(Pr,{href:n.url,title:n.url,children:n.label})},bl=({session:e,entry:n})=>{var x;const[a,r]=b(!1),o=oe(null);F(()=>{cr()},[]),F(()=>{if(!a)return;const h=y=>{o.current&&!o.current.contains(y.target)&&r(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[a]);const i=jn.value,c=i!=null&&i.enabled?i.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 l("button",{type:"button",class:"cursor-not-allowed",style:jr,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 h=>{r(!1);try{await Ko(e,h)}catch(y){I(y.message,"error")}};return c.length===1?l("button",{type:"button",class:He,style:Ie,onClick:()=>d(c[0].id),children:["Open in ",c[0].label]}):l("div",{class:"relative",ref:o,children:[l("button",{type:"button",class:He,style:Ie,"aria-expanded":a,onClick:()=>r(h=>!h),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(h=>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(h.id),children:h.label},h.id))})]})},kl={"--orange":"--red","--blue":"--purple","--purple":"--blue","--green":"--teal"},lt=({label:e,index:n,color:a="var(--ink)",bar:r,title:o,children:i})=>l("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:i}),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)"}})})]}),wl=({value:e,onChange:n,onSend:a,onCancel:r})=>{const o=bt();return l("form",{class:"flex items-center",style:{gap:"6px",marginTop:"6px"},onSubmit:i=>{i.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:i=>n(i.target.value),onKeyDown:i=>{i.key==="Escape"&&r()}}),t(L,{label:"Send",variant:"primary",size:"sm",disabled:!e.trim(),onClick:a})]})},Sl=({session:e,onOpen:n})=>{const a=ie(e),r=hr(a),[o,i]=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 ge("/api/kioku/remember",{project:a,sessionDir:yt(e),text:o}),I("Sent to the agent to remember","success"),i(null)}catch(d){I(pe(d),"error")}};return l("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:[l("div",{class:"flex items-center",style:{fontSize:"11.5px",color:"var(--ink-2)"},children:["Memory · ",qt(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:()=>i(""),children:"Remember…"})]}),o!==null&&t(wl,{value:o,onChange:i,onSend:s,onCancel:()=>i(null)}),t("div",{class:"flex items-center flex-wrap",style:{gap:"4px",marginTop:"6px"},children:r.map((d,x)=>l("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(_e(d.tier)),color:`var(${_e(d.tier)})`},title:`${d.tier??"brain"} · ${d.pages} pages`,onClick:()=>n==null?void 0:n(a),children:re(d)})]},d.key))})]})},un=({title:e,items:n,tone:a,empty:r})=>l("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}),l("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))]})]}),Cl=({session:e,active:n,onDone:a,onOpenMemory:r})=>{const[o,i]=b(""),[c,s]=b(!1),[d,x]=b(!1),[h,y]=b(0),[v,S]=b(null),[w,k]=b(!1),p=q(e),f=yt(e),m=e.type==="task"||e.type==="review",u=xr(e,{poll:n&&e.type==="task"}),T=Un(e.type),g=e.type==="login",$=zr(Rr(g?"":ie(e))),A=Ua(p).value,N=encodeURIComponent(e.project),O=encodeURIComponent(f),j=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal/${N}/${O}?k=${h}`;F(()=>{if(g)return;let E=!1;return Promise.all([fetch(`/api/cw/tools?project=${N}`).then(Q=>Q.json()).catch(()=>null),fetch(`/api/cw/git/branch/${N}/${O}`).then(Q=>Q.json()).catch(()=>null)]).then(([Q,te])=>{E||(Q&&S(Q),i((te==null?void 0:te.branch)||e.task||e.pr||""))}),()=>{E=!0}},[p]);const z=()=>{s(!1),y(E=>E+1)},B=(v==null?void 0:v.mcps)??[],P=(v==null?void 0:v.plugins)??[],D=(u==null?void 0:u.state)??null,M=(D==null?void 0:D.branch)??o,H=u?u.error!==null?"Changes unknown":Ho(u.state):"Checking changes…",ce=[ie(e)||"no project",e.account,[Na(e),e.provider&&e.provider!=="native"?null:e.model].filter(Boolean).join(", "),`${e.opens} session${e.opens===1?"":"s"}`].filter(Boolean).join(" · ");return l("div",{class:"flex flex-col h-full min-w-0",children:[l("div",{class:"flex flex-col shrink-0",style:{padding:"14px 20px",gap:"12px"},children:[l("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(${T.token}), var(${kl[T.token]??T.token}))`,boxShadow:"var(--shadow-m)",color:"#fff",fontSize:"13px",fontWeight:700},"aria-hidden":"true",children:T.glyph}),l("div",{class:"min-w-0",children:[t("h1",{class:"truncate",style:{fontSize:"19px",fontWeight:700,letterSpacing:"-0.02em"},children:ue(e)}),t("p",{class:"truncate",style:{marginTop:"1px",fontSize:"12.5px",color:"var(--ink-2)"},children:ce}),!g&&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"}}),l("div",{class:"flex flex-wrap items-center",style:{gap:"7px"},children:[!g&&t("button",{type:"button",class:He,style:Ie,"aria-expanded":w,onClick:()=>k(E=>!E),children:w?"Hide context":`Context · ${B.length} MCP, ${P.length} plugins`}),!g&&t(yl,{session:e}),!g&&t(vl,{entry:u}),!g&&t(bl,{session:e,entry:u}),c&&t(L,{label:"Restart",variant:"secondary",size:"sm",onClick:z}),e.status==="active"&&!g&&t(L,{label:"Mark done",variant:"primary",size:"sm",onClick:a})]})]}),!g&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(138px, 1fr))",gap:"9px"},children:[t(lt,{index:0,label:"Context used",color:"var(--blue)",bar:(A==null?void 0:A.context)??null,title:"Read from the harness status line",children:(A==null?void 0:A.context)!=null?`${Math.round(A.context)}%`:"—"}),t(lt,{index:1,label:"Tokens",children:(A==null?void 0:A.tokens)!=null?Ha(A.tokens):"—"}),t(lt,{index:2,label:"Cost",color:"var(--green)",children:(A==null?void 0:A.cost)!=null?qa(A.cost):"—"}),m&&t(lt,{index:3,label:"Commits",children:(D==null?void 0:D.commits)??"—"}),m&&t(lt,{index:4,label:"Unpushed",color:D&&xt(D)>0?"var(--orange)":"var(--ink)",children:D?xt(D):"—"}),t(Sl,{session:e,onOpen:r}),M&&l("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:()=>Jn(M,"Branch"),children:[l("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:M})]})]}),w&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:"9px",animation:"riseIn .3s var(--ease) both"},children:[t(un,{title:`MCP · ${B.length}`,tone:"--blue",empty:"No MCP servers",items:B.map(E=>({name:E.name,title:`${E.type} · ${E.source}`}))}),t(un,{title:`Plugins · ${P.length}`,tone:"--green",empty:"No plugins",items:P.map(E=>({name:E.name,muted:!E.enabled,title:`${E.enabled?"enabled":"disabled"} · ${E.marketplace}${E.hasMcp?` · MCP ${E.mcpName??""}`:""}`}))}),t(un,{title:"Stack",tone:null,empty:"Nothing detected",items:$.map(E=>({name:E}))})]})]}),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:l("div",{class:"absolute inset-0 flex flex-col",children:[l("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"}}),l("span",{class:"mono truncate",style:{fontSize:"11px",color:"#8a8a92",marginLeft:"6px"},children:[M||ue(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"})]}),l("div",{class:"relative flex-1 min-h-0",style:{padding:"12px 6px 6px 14px"},children:[t(Jr,{wsUrl:j,theme:vt.value,focused:n,onOutput:E=>vo(p,E),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…"})})]})]})})]})},me={fontSize:"12px",color:"var(--ink-2)"},ne=e=>e.target.value,U=({label:e,plain:n,children:a})=>l(n?"div":"label",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:me,children:e}),a]}),$l={dev:"New dev task",review:"Review a pull request",loop:"New loop",general:"New session"},zl={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."},Rl={dev:"Task name or ticket URL",review:"Pull request number or URL",loop:"Loop prompt",general:""},Tl={dev:"fix-auth or https://linear.app/…",review:"42 or https://github.com/…/pull/42",loop:"Babysit my open PRs…",general:""},jl=[{id:"",label:"Auto"},{id:"feature",label:"feature"},{id:"bugfix",label:"bugfix"},{id:"refactor",label:"refactor"}],hn={boxShadow:"var(--shadow-s)"},It=e=>/^[\w./:#-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Pl=({projects:e,accounts:n,initialAccount:a,initialProject:r,onClose:o,onCreated:i,onOpenAccounts:c})=>{var Tt;const s=Qn(ke.value,Ue.value),[d,x]=b(""),[h,y]=b(""),[v,S]=b(""),[w,k]=b(""),[p,f]=b(""),[m,u]=b(!1),[T,g]=b(!1),[$,A]=b(""),[N,O]=b("claude"),R=bt();F(()=>{ve()},[]);const j=Zt.value,z=j!=null&&j.available?j.doctor:null,B=Object.keys(e),P=s==="general",D=s==="review",M=s==="loop",H=ke.value,ce=!$.trim()||/^\d+[smh]$/.test($.trim()),E=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??_,W=C&&E.includes(C)?C:E[0]??"";x(W);const K=W?B.filter(ae=>{var X;return((X=e[ae])==null?void 0:X.account)===W}):B,V=r&&K.includes(r)?r:!P&&K.length>0?K[0]:"";V&&y(V)},[]);const te=oe(!1);F(()=>{if(!te.current){te.current=!0;return}!P&&!h&&Q.length>0&&y(Q[0])},[P]);const we=_=>{x(_);const C=B.filter(W=>{var K;return((K=e[W])==null?void 0:K.account)===_});!P&&C.length>0&&!C.includes(h)?y(C[0]):P&&h&&!C.includes(h)&&y("")},wt=z?Oa(h||void 0,d,e,z):"claude";F(()=>{!z||!d||O(M?"claude":wt)},[j==null?void 0:j.available,d,h,M]);const Se=z?Pe(z,d,N):void 0,St=!z||Fe(j,N,"skip_permissions"),Ce=!z||N==="claude",Ne=Ce||!P,fe=z?Zn(N,Se,M):null,Ct=he(N).label;F(()=>{St||u(!1),f(Ce?"":(Se==null?void 0:Se.model)??"")},[N]),F(()=>{Ce||f((Se==null?void 0:Se.model)??"")},[d]);const $t=ir(H),Je=sr(j,N,H),zt=!P&&!H.trim()||M&&!ce||!P&&!h||!!fe,Rt=async()=>{if(!zt){g(!0);try{const _={type:s,account:d||void 0,skipPermissions:m||void 0};z&&(_.harness=N),M?(_.project=h,_.loopPrompt=H.trim(),_.loopInterval=$.trim()||void 0):P?h&&(_.project=h):(_.project=h,_.task=H.trim(),_.description=v.trim()||void 0,_.workflow=w||void 0),_.model=Ne&&p||void 0;const W=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)})).json();W.ok?(I(P?"Session started":M?"Loop started":"Task started","success"),P||Vt(""),i(W.session)):I(W.error??"Failed to start","error")}catch{I("Failed to start","error")}finally{g(!1)}}},tn=d||E[0]||"default",nn=P?`cw launch ${It(tn)}`:M?`cw loop ${h||"<project>"} ${It(H.trim()||"<prompt>")}${$.trim()?` --every ${$.trim()}`:""}`:D?`cw review ${h||"<project>"} ${It(H.trim()||"<pr>")}`:`cw work ${h||"<project>"} ${H.trim()?It(((Tt=Xt(H))==null?void 0:Tt.kind)==="name"?wr(H):H.trim()):"<task>"}`;return l(qe,{title:$l[s],onClose:o,children:[t($r,{fill:!0}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",lineHeight:1.5},children:zl[s]}),!P&&l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t(U,{label:Rl[s],children:t("input",{class:"field",style:{...hn,fontSize:"14px"},placeholder:Tl[s],value:H,ref:R,onInput:_=>{const C=_.target.value;M?ke.value=C:Vt(C)},onKeyDown:_=>{_.key==="Enter"&&Rt()}})}),!M&&t(Cr,{ctx:{type:s,project:h,account:d,harness:N},size:"sm"})]}),l("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;we(C),Gt.value=C},children:E.map(_=>t("option",{value:_,children:_},_))})}),t(U,{plain:!0,label:P?"Project · optional":"Project",children:t(Sr,{label:"Project",size:"md",width:"100%",value:h,placeholder:P?"No project":"Choose…",onChange:_=>{y(_),Be.value=_},options:[...P?[{value:"",label:"No project"}]:[],...Ln(e,E,Q)]})})]}),M&&l(U,{label:"Interval · optional",children:[t("input",{class:"field mono",style:{...hn,borderColor:ce?void 0:"var(--red)"},value:$,placeholder:"auto — Claude decides the pace",onInput:_=>A(_.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:hn,placeholder:"Context the agent reads first…",value:v,onInput:_=>S(_.target.value)})}),z&&t(sl,{doctor:z,account:d,value:N,defaultHarness:wt,isLoop:M,onChange:O,onOpenAccounts:c}),Ne&&l("div",{class:"grid",style:{gridTemplateColumns:s==="dev"?"1fr 1fr":"1fr",gap:"10px"},children:[l("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:me,children:"Model"}),Ce?t(le,{fill:!0,size:"sm",label:"Model",tabs:lo.map(_=>({id:_.id,label:_.label})),active:p,onChange:f}):t("input",{class:"field mono",style:{height:"32px",fontSize:"12.5px"},value:p,placeholder:"the account's model","aria-label":"Model",onInput:_=>f(_.target.value)})]}),s==="dev"&&l("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:me,children:"Workflow"}),t(le,{fill:!0,size:"sm",label:"Workflow",tabs:jl,active:w,onChange:k})]})]}),St&&l("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:[l("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(Kn,{checked:m,onChange:u,label:"Bypass permissions"})]}),Je&&l("p",{style:{fontSize:"12.5px",padding:"10px 12px",borderRadius:"12px",background:Z("--orange"),color:"var(--ink)"},children:[Ct," has no MCP and CW has no ",$t==="linear"?"LINEAR_API_KEY":"NOTION_TOKEN",", so the ticket will not reach TASK_NOTES.md. The task still starts, without the ticket."]}),t(L,{label:T?"Starting…":P?"Launch session":M?"Start loop":D?"Start review":"Start task",variant:"primary",size:"lg",block:!0,loading:T,disabled:zt,onClick:Rt}),fe&&t("p",{style:{fontSize:"12px",color:"var(--red)",textAlign:"center"},children:fe}),t("p",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)",textAlign:"center",overflowWrap:"anywhere"},children:nn})]})},ct=Y(null),Nn=Y(null);async function ea(){const e=await fetch("/api/skills/plugins");if(!e.ok)throw new Error("fetch failed");ct.value=await e.json()}async function On(){const e=await fetch("/api/skills/marketplaces");if(!e.ok)throw new Error("fetch failed");Nn.value=await e.json()}const Ee=({title:e,sub:n,children:a})=>l("div",{class:"glass flex items-center flex-wrap shrink-0",style:{gap:"10px",padding:"12px 20px",borderBottom:"1px solid var(--hair)"},children:[l("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 Al(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 Il(e){return`add-skill-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,30).replace(/-+$/,"")||Date.now()}`}function Ll(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 Ar=e=>`/api/skills/plugins/${encodeURIComponent(e)}`;async function ta(e,n){try{return await ge(e,n)}catch(a){return I(pe(a),"error"),null}}async function Ir(e,n,a){await ta("/api/skills/plugins/install",{id:e,account:a})&&(I(`${n} installed in ${a} · applies to new sessions`,"success"),await Promise.all([ea(),On()]).catch(()=>{}))}const Lr=(e,n)=>n?e.skills.filter(a=>a.name.toLowerCase().includes(n)||a.description.toLowerCase().includes(n)):e.skills,El={padding:"6px 11px",fontSize:"11px",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase",color:"var(--ink-3)"},Nl=e=>/^[0-9a-f]{12,}$/.test(e)?e.slice(0,7):e,Ol=e=>{var n;return(n=e.installs.find(a=>a.update))==null?void 0:n.latest},Wl=({list:e,query:n,selected:a,onSelect:r})=>{const o=e.filter(c=>!n||Lr(c,n).length>0||c.name.toLowerCase().includes(n));if(e.length===0)return null;if(o.length===0)return t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:"No plugin matches."});const i=new Map;for(const c of o)i.set(c.marketplace,[...i.get(c.marketplace)??[],c]);return t(G,{children:[...i].map(([c,s])=>l("div",{style:{marginBottom:"8px"},children:[t("p",{class:"truncate",style:El,children:c}),s.map(d=>{const x=a===d.id,h=Ol(d),y=[...new Set(d.installs.map(v=>Nl(v.version)))].join(" · ");return l("button",{type:"button","aria-current":x?"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 ${x?"var(--hair)":"transparent"}`,background:x?"var(--card)":"transparent",boxShadow:x?"var(--shadow-s)":"none",color:"var(--ink)"},onClick:()=>r(d.id),children:[l("span",{class:"flex items-center",style:{gap:"8px"},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:d.name}),h&&l("span",{class:"mono shrink-0",title:`Update to ${h} available`,style:{fontSize:"10.5px",fontWeight:600,padding:"1px 6px",borderRadius:"6px",color:"var(--orange)",background:"color-mix(in srgb, var(--orange) 18%, transparent)"},children:["↑ ",h]})]}),l("span",{class:"flex items-center",style:{gap:"8px",marginTop:"2px",paddingLeft:"21px",fontSize:"11.5px",color:"var(--ink-3)"},children:[t("span",{class:"mono truncate",style:{maxWidth:"150px"},children:y}),t("span",{children:"·"}),t("span",{class:"shrink-0",children:d.skills.length===1?"1 skill":`${d.skills.length} skills`})]})]},d.id)})]},c))})},ma={fontSize:"12px",fontWeight:600,color:"var(--ink-2)",margin:"0 0 8px"},Er={gap:"10px",padding:"9px 12px",borderRadius:"11px",border:"1px solid var(--hair)",background:"var(--card)"},Dl=({plugin:e,install:n})=>{const[a,r]=b(!1),o=n.scope==="global"?"global":n.scopeRef,i=async()=>{r(!0);const s=await ta(`${Ar(e.id)}/update`,{scope:n.scope,scopeRef:n.scopeRef});r(!1),s&&(I(`${e.name} ${s.version??""} · applies to new sessions`,"success"),ea().catch(()=>{}))},c=n.update?{text:`${n.latest} available`,color:"var(--orange)"}:n.latest?{text:"up to date",color:"var(--green)"}:{text:"version not published",color:"var(--ink-3)"};return l("div",{class:"flex items-center",style:Er,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:c.color},children:c.text}),t("span",{style:{fontSize:"11.5px",color:n.enabled?"var(--green)":"var(--ink-3)"},children:n.enabled?"on":"off"}),t(L,{label:a?"Updating…":n.update?`Update to ${n.latest}`:"Check & update",variant:n.update?"primary":"secondary",size:"sm",loading:a,onClick:i})]})},Ml=({plugin:e,account:n})=>{const[a,r]=b(!1);return l("div",{class:"flex items-center",style:Er,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(L,{label:a?"Installing…":"Install",variant:"secondary",size:"sm",loading:a,onClick:async()=>{r(!0),await Ir(e.id,e.name,n),r(!1)}})]})},Fl=({plugin:e,name:n,onBack:a})=>{const[r,o]=b(null),[i,c]=b(!1);return F(()=>{let s=!1;return o(null),c(!1),fetch(`${Ar(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]),l(G,{children:[t(Ee,{title:n,sub:`${e.name} · read-only`,children:t(L,{label:"Back",variant:"secondary",size:"sm",onClick:a})}),l("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."}),i?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})]})]})},Bl=({plugin:e,accounts:n,query:a,onSelectSkill:r,onPropose:o})=>{const i=new Set(e.installs.map(s=>s.scopeRef)),c=n.filter(s=>!i.has(s));return l(G,{children:[l(Ee,{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(L,{label:"Propose a skill",variant:"primary",size:"sm",onClick:o})]}),t("div",{class:"flex-1 min-h-0 overflow-auto",children:l("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&&l("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."]}),l("section",{children:[t("h3",{style:ma,children:"Accounts · versions"}),l("div",{class:"flex flex-col",style:{gap:"6px"},children:[e.installs.map(s=>t(Dl,{plugin:e,install:s},`${s.scope}/${s.scopeRef}`)),c.map(s=>t(Ml,{plugin:e,account:s},s))]})]}),l("section",{children:[l("h3",{style:ma,children:["Skills (",e.skills.length,")"]}),e.skills.length===0&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-3)",margin:0},children:"No skills: this plugin brings MCP servers, commands or hooks."}),t("div",{class:"flex flex-col",style:{gap:"4px"},children:Lr(e,a).map(s=>l("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))})]})]})})]})},_l=({accounts:e})=>{const[n,a]=b(""),r=e.includes(n)?n:e[0]??"",[o,i]=b(""),[c,s]=b(""),[d,x]=b(""),[h,y]=b(!1),[v,S]=b(null);F(()=>{Nn.value===null&&On().catch(()=>I("Failed to load marketplaces","error"))},[]);const w=Nn.value,k=(w==null?void 0:w.find(g=>g.name===o))??(w==null?void 0:w[0]),p=new Set((ct.value??[]).flatMap(g=>g.installs.some($=>$.scope==="account"&&$.scopeRef===r)?[g.id]:[])),f=c.trim().toLowerCase(),m=((k==null?void 0:k.plugins)??[]).filter(g=>!f||g.name.toLowerCase().includes(f)||g.description.toLowerCase().includes(f)),u=async()=>{y(!0);const g=await ta("/api/skills/marketplaces",{source:d.trim(),account:r});y(!1),g&&(I(`Marketplace added to ${r}`,"success"),x(""),await On().catch(()=>{}))},T=async(g,$)=>{S(g),await Ir(g,$,r),S(null)};return l(G,{children:[t(Ee,{title:"Add a plugin",sub:r?`Claude Code only · installs into ${r}`:"Claude Code only"}),l("div",{class:"flex-1 min-h-0 overflow-auto flex flex-col",style:{padding:"14px 20px 20px",gap:"8px"},children:[l("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:g=>a(g.target.value),children:e.map(g=>t("option",{value:g,children:g},g))})}),w&&w.length>0&&t(U,{label:"Marketplace",children:t("select",{class:"field",value:k==null?void 0:k.name,onChange:g=>i(g.target.value),children:w.map(g=>l("option",{value:g.name,children:[g.name," · ",g.source]},g.name))})}),t(U,{label:"Add a marketplace",children:l("div",{class:"flex",style:{gap:"8px"},children:[t("input",{class:"field flex-1",value:d,placeholder:"owner/repo, git URL or path",onInput:g=>x(g.target.value),onKeyDown:g=>{g.key==="Enter"&&d.trim()&&u()}}),t(L,{label:h?"Adding…":"Add",variant:"secondary",size:"sm",loading:h,disabled:!d.trim()||!r,onClick:u})]})}),k&&k.plugins.length>0&&t("input",{class:"field",type:"search","aria-label":"Filter plugins",value:c,placeholder:`Filter ${k.plugins.length} plugins`,onInput:g=>s(g.target.value)})]}),w===null&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"Loading marketplaces…"}),(w==null?void 0:w.length)===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:"No marketplace yet. Add one above."}),k&&m.length===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:f?"No plugin matches.":"This marketplace lists no plugins."}),m.map((g,$)=>l("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($,8)*40}ms both`},children:[l("div",{class:"flex-1 min-w-0",children:[l("div",{class:"flex items-center min-w-0",style:{gap:"8px"},children:[t("span",{class:"truncate",style:{fontSize:"13.5px",fontWeight:600},children:g.name}),g.category&&t("span",{class:"mono shrink-0",style:{fontSize:"11px",color:"var(--ink-3)"},children:g.category})]}),g.description&&t("div",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-2)"},title:g.description,children:g.description})]}),p.has(g.id)?t("span",{style:{fontSize:"12px",color:"var(--green)"},children:"Installed"}):t(L,{label:v===g.id?"Installing…":"Install",variant:"secondary",size:"sm",loading:v===g.id,disabled:v!==null||!r,onClick:()=>T(g.id,g.name)})]},g.id))]})]})},Kl=({plugin:e,accounts:n,onSubmit:a,onCancel:r})=>{const o=Al(e),i=e.installs.filter(p=>p.scope==="account").map(p=>p.scopeRef),c=n.find(p=>i.includes(p))??n[0]??"",[s,d]=b(""),[x,h]=b(o[0]??""),[y,v]=b(c),[S,w]=b(!1),k=async()=>{w(!0);try{await a(s.trim(),o.length>1?x:void 0,y)}finally{w(!1)}};return l(G,{children:[t(Ee,{title:"Propose a skill",sub:`${e.repo??e.name} · project ${e.project??""}`}),t("div",{class:"flex-1 min-h-0 overflow-auto",children:l("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"14px",maxWidth:"560px"},children:[l("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=>h(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:y,onChange:p=>v(p.target.value),children:n.map(p=>t("option",{value:p,children:p},p))})}),l("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(L,{label:S?"Starting…":"Start task",variant:"primary",loading:S,disabled:!s.trim()||!y,onClick:k}),t(L,{label:"Cancel",variant:"secondary",onClick:r})]})]})})]})},Ul={global:"--blue",account:"--orange",project:"--green"},Lt=e=>`${e.scope}/${e.scopeRef}/${e.dirName}`;function Hl(e,n){return e==="global"?"global":e==="account"?`account/${encodeURIComponent(n)}`:`project/${encodeURIComponent(n)}`}const dt=e=>e.scope==="global"?"Global":`${e.scope==="account"?"Account":"Project"} · ${e.scopeRef}`,ql=e=>e.scope==="global"?`~/.claude/skills/${e.dirName}`:e.scope==="account"?`~/.cw/accounts/${e.scopeRef}/skills/${e.dirName}`:`<${e.scopeRef}>/.claude/skills/${e.dirName}`,Gl={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."},Nr=e=>e[0]?{scope:"account",scopeRef:e[0]}:{scope:"global",scopeRef:"global"},Wn=e=>e.scope==="global"||e.scopeRef!=="",Or=({accounts:e,projects:n,value:a,onChange:r})=>{const o=i=>{const c=i==="account"?e:n;r({scope:i,scopeRef:i==="global"?"global":c.includes(a.scopeRef)?a.scopeRef:c[0]??""})};return l(G,{children:[l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:me,children:"Scope"}),t(le,{label:"Scope",tabs:[{id:"account",label:"Account"},{id:"project",label:"Project"},{id:"global",label:"Global"}],active:a.scope,onChange:i=>o(i)}),t("span",{style:{fontSize:"12px",color:"var(--ink-3)"},children:Gl[a.scope]})]}),a.scope!=="global"&&t(U,{label:a.scope==="account"?"Account":"Project",children:t("select",{class:"field",value:a.scopeRef,onChange:i=>r({...a,scopeRef:i.target.value}),children:(a.scope==="account"?e:n).map(i=>t("option",{value:i,children:i},i))})})]})},Vl=(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),Wr=(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(...Wr(o,n+" "))):a.push(`${n}${r}: ${String(o??"")}`);return a},Jl=({skill:e,accounts:n,projects:a,onDeleted:r,onCopied:o,onRun:i})=>{const[c,s]=b(null),[d,x]=b(!0),[h,y]=b("SKILL.md"),[v,S]=b(""),[w,k]=b({}),[p,f]=b(!1),m=`/api/skills/${Hl(e.scope,e.scopeRef)}/${encodeURIComponent(e.dirName)}`;F(()=>{let R=!1;return x(!0),y("SKILL.md"),fetch(m).then(j=>{if(!j.ok)throw new Error("fetch failed");return j.json()}).then(j=>{if(R)return;s(j);const z=Wr(j.frontmatter);S(z.length>0?`---
3
+ ${z.join(`
4
4
  `)}
5
5
  ---
6
6
 
7
- ${T.body}`:T.body),w(Object.fromEntries(T.references.map(B=>[B.name,B.content])))}).catch(()=>{R||(s(null),P("Failed to load skill","error"))}).finally(()=>{R||x(!1)}),()=>{R=!0}},[v]);const p=async()=>{h(!0);const R=f==="SKILL.md";try{const $=await(await fetch(R?v:`${v}/references/${encodeURIComponent(f)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:R?m:k[f]??""})})).json();$.ok?P(R?"Skill saved":"Reference saved","success"):P($.error??"Failed to save","error")}catch{P("Failed to save","error")}finally{h(!1)}},z=async()=>{if(confirm(`Delete the skill "${e.name}" permanently?`))try{const T=await(await fetch(v,{method:"DELETE"})).json();T.ok?(P("Skill deleted","info"),r()):P(T.error??"Failed to delete","error")}catch{P("Failed to delete","error")}},g=async R=>{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:R})})).json();$.ok?(P(`Copied to ${ct(R)}`,"success"),o()):P($.error??"Failed to copy","error")}catch{P("Failed to copy","error")}},A=async()=>{const R=prompt("Reference filename (e.g. examples.md):");if(!(R!=null&&R.trim()))return;const T=R.trim(),$=`# ${T}
8
- `;try{const j=await(await fetch(`${v}/references/${encodeURIComponent(T)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:$})})).json();j.ok?(w(W=>({...W,[T]:$})),s(W=>W&&{...W,references:[...W.references,{name:T,content:$}]}),b(T),P("Reference added","success")):P(j.error??"Failed to add reference","error")}catch{P("Failed to add reference","error")}},L=async R=>{if(confirm(`Delete reference "${R}"?`))try{const $=await(await fetch(`${v}/references/${encodeURIComponent(R)}`,{method:"DELETE"})).json();$.ok?(w(B=>{const{[R]:j,...W}=B;return W}),s(B=>B&&{...B,references:B.references.filter(j=>j.name!==R)}),f===R&&b("SKILL.md"),P("Reference deleted","info")):P($.error??"Failed to delete reference","error")}catch{P("Failed to delete reference","error")}},N=["SKILL.md",...(c==null?void 0:c.references.map(R=>R.name))??[]],O=Hl(e,n,a);return l(V,{children:[l(Le,{title:e.name,sub:`${ct(e)} · ${Kl(e)}`,children:[t(I,{label:"Delete",variant:"danger",size:"sm",onClick:z}),l("select",{class:"field","aria-label":"Copy to",style:{height:"30px",padding:"0 8px",fontSize:"12.5px",width:"auto"},value:"",disabled:!c,onChange:R=>{const T=R.target,$=O[Number(T.value)];T.value="",$&&g($)},children:[t("option",{value:"",disabled:!0,children:"Copy to…"}),O.map((R,T)=>t("option",{value:T,children:ct(R)},`${R.scope}/${R.scopeRef}`))]}),t(I,{label:"Run in session",variant:"secondary",size:"sm",onClick:i}),t(I,{label:u?"Saving…":"Save",variant:"primary",size:"sm",loading:u,disabled:!c,onClick:p})]}),l("div",{class:"flex items-center flex-wrap shrink-0",style:{gap:"6px",padding:"10px 20px 0"},role:"tablist","aria-label":"Files",children:[N.map(R=>{const T=f===R;return l("span",{class:"inline-flex items-center",style:{gap:"4px",padding:T?"5px 8px 5px 11px":"5px 11px",borderRadius:"9px",background:T?"var(--card)":"transparent",border:`1px solid ${T?"var(--hair)":"transparent"}`,boxShadow:T?"var(--shadow-s)":"none"},children:[t("button",{type:"button",role:"tab","aria-selected":T,class:"mono cursor-pointer",style:{border:0,background:"none",padding:0,fontSize:"12px",fontWeight:T?600:400,color:T?"var(--ink)":"var(--ink-3)"},onClick:()=>b(R),children:R}),T&&R!=="SKILL.md"&&t("button",{type:"button","aria-label":`Delete ${R}`,class:"grid place-items-center cursor-pointer text-ink3 hover:text-red",style:{border:0,background:"none",padding:0},onClick:()=>L(R),children:t("span",{class:"i-lucide-x",style:{width:"12px",height:"12px"}})})]},R)}),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:A,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":f,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:f==="SKILL.md"?m:k[f]??"",onInput:R=>{const T=R.target.value;f==="SKILL.md"?S(T):w($=>({...$,[f]:T}))}}):t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Skill not found."})})]})},Gl=({query:e,accounts:n,projects:a,onInstalled:r})=>{const[o,i]=y(null),[c,s]=y(null),[d,x]=y(()=>Nr(n));F(()=>{let b=!1;return i(null),fetch(`/api/skills/explore?q=${encodeURIComponent(e)}`).then(m=>{if(!m.ok)throw new Error("search failed");return m.json()}).then(m=>{b||i(m.results)}).catch(()=>{b||(i([]),P("Failed to search skills","error"))}),()=>{b=!0}},[e]);const f=async b=>{s(b.slug);try{const S=await(await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:b.repo,skill:b.skillId,...d})})).json();S.ok?(P(`Installed in ${ct(d)}`,"success"),r()):P(S.error??"Failed to install","error")}catch{P("Failed to install","error")}finally{s(null)}};return l(V,{children:[t(Le,{title:`skills.sh · “${e}”`,sub:`Installs into ${ct(d)}`}),l("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(Or,{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((b,m)=>l("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(m,8)*40}ms both`},children:[l("div",{class:"flex-1 min-w-0",children:[t("div",{class:"truncate",style:{fontSize:"13.5px",fontWeight:600},children:b.name}),l("div",{class:"mono truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[b.repo," · ",b.installs," installs"]})]}),t(I,{label:c===b.slug?"Installing…":"Install",variant:"secondary",size:"sm",loading:c===b.slug,disabled:!Dn(d),onClick:()=>f(b)})]},b.slug))]})]})},Vl=({accounts:e,projects:n,onCreated:a,onCreateWithAI:r})=>{const[o,i]=y(()=>Nr(e)),[c,s]=y(""),[d,x]=y(""),[f,b]=y(!1),{scope:m,scopeRef:S}=o,k=async()=>{if(!c.trim())return;b(!0);const w=`---
7
+ ${j.body}`:j.body),k(Object.fromEntries(j.references.map(B=>[B.name,B.content])))}).catch(()=>{R||(s(null),I("Failed to load skill","error"))}).finally(()=>{R||x(!1)}),()=>{R=!0}},[m]);const u=async()=>{f(!0);const R=h==="SKILL.md";try{const z=await(await fetch(R?m:`${m}/references/${encodeURIComponent(h)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:R?v:w[h]??""})})).json();z.ok?I(R?"Skill saved":"Reference saved","success"):I(z.error??"Failed to save","error")}catch{I("Failed to save","error")}finally{f(!1)}},T=async()=>{if(confirm(`Delete the skill "${e.name}" permanently?`))try{const j=await(await fetch(m,{method:"DELETE"})).json();j.ok?(I("Skill deleted","info"),r()):I(j.error??"Failed to delete","error")}catch{I("Failed to delete","error")}},g=async R=>{try{const z=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:R})})).json();z.ok?(I(`Copied to ${dt(R)}`,"success"),o()):I(z.error??"Failed to copy","error")}catch{I("Failed to copy","error")}},$=async()=>{const R=prompt("Reference filename (e.g. examples.md):");if(!(R!=null&&R.trim()))return;const j=R.trim(),z=`# ${j}
8
+ `;try{const P=await(await fetch(`${m}/references/${encodeURIComponent(j)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).json();P.ok?(k(D=>({...D,[j]:z})),s(D=>D&&{...D,references:[...D.references,{name:j,content:z}]}),y(j),I("Reference added","success")):I(P.error??"Failed to add reference","error")}catch{I("Failed to add reference","error")}},A=async R=>{if(confirm(`Delete reference "${R}"?`))try{const z=await(await fetch(`${m}/references/${encodeURIComponent(R)}`,{method:"DELETE"})).json();z.ok?(k(B=>{const{[R]:P,...D}=B;return D}),s(B=>B&&{...B,references:B.references.filter(P=>P.name!==R)}),h===R&&y("SKILL.md"),I("Reference deleted","info")):I(z.error??"Failed to delete reference","error")}catch{I("Failed to delete reference","error")}},N=["SKILL.md",...(c==null?void 0:c.references.map(R=>R.name))??[]],O=Vl(e,n,a);return l(G,{children:[l(Ee,{title:e.name,sub:`${dt(e)} · ${ql(e)}`,children:[t(L,{label:"Delete",variant:"danger",size:"sm",onClick:T}),l("select",{class:"field","aria-label":"Copy to",style:{height:"30px",padding:"0 8px",fontSize:"12.5px",width:"auto"},value:"",disabled:!c,onChange:R=>{const j=R.target,z=O[Number(j.value)];j.value="",z&&g(z)},children:[t("option",{value:"",disabled:!0,children:"Copy to…"}),O.map((R,j)=>t("option",{value:j,children:dt(R)},`${R.scope}/${R.scopeRef}`))]}),t(L,{label:"Run in session",variant:"secondary",size:"sm",onClick:i}),t(L,{label:p?"Saving…":"Save",variant:"primary",size:"sm",loading:p,disabled:!c,onClick:u})]}),l("div",{class:"flex items-center flex-wrap shrink-0",style:{gap:"6px",padding:"10px 20px 0"},role:"tablist","aria-label":"Files",children:[N.map(R=>{const j=h===R;return l("span",{class:"inline-flex items-center",style:{gap:"4px",padding:j?"5px 8px 5px 11px":"5px 11px",borderRadius:"9px",background:j?"var(--card)":"transparent",border:`1px solid ${j?"var(--hair)":"transparent"}`,boxShadow:j?"var(--shadow-s)":"none"},children:[t("button",{type:"button",role:"tab","aria-selected":j,class:"mono cursor-pointer",style:{border:0,background:"none",padding:0,fontSize:"12px",fontWeight:j?600:400,color:j?"var(--ink)":"var(--ink-3)"},onClick:()=>y(R),children:R}),j&&R!=="SKILL.md"&&t("button",{type:"button","aria-label":`Delete ${R}`,class:"grid place-items-center cursor-pointer text-ink3 hover:text-red",style:{border:0,background:"none",padding:0},onClick:()=>A(R),children:t("span",{class:"i-lucide-x",style:{width:"12px",height:"12px"}})})]},R)}),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:$,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":h,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:h==="SKILL.md"?v:w[h]??"",onInput:R=>{const j=R.target.value;h==="SKILL.md"?S(j):k(z=>({...z,[h]:j}))}}):t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Skill not found."})})]})},Yl=({query:e,accounts:n,projects:a,onInstalled:r})=>{const[o,i]=b(null),[c,s]=b(null),[d,x]=b(()=>Nr(n));F(()=>{let y=!1;return i(null),fetch(`/api/skills/explore?q=${encodeURIComponent(e)}`).then(v=>{if(!v.ok)throw new Error("search failed");return v.json()}).then(v=>{y||i(v.results)}).catch(()=>{y||(i([]),I("Failed to search skills","error"))}),()=>{y=!0}},[e]);const h=async y=>{s(y.slug);try{const S=await(await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:y.repo,skill:y.skillId,...d})})).json();S.ok?(I(`Installed in ${dt(d)}`,"success"),r()):I(S.error??"Failed to install","error")}catch{I("Failed to install","error")}finally{s(null)}};return l(G,{children:[t(Ee,{title:`skills.sh · “${e}”`,sub:`Installs into ${dt(d)}`}),l("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(Or,{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((y,v)=>l("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(v,8)*40}ms both`},children:[l("div",{class:"flex-1 min-w-0",children:[t("div",{class:"truncate",style:{fontSize:"13.5px",fontWeight:600},children:y.name}),l("div",{class:"mono truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[y.repo," · ",y.installs," installs"]})]}),t(L,{label:c===y.slug?"Installing…":"Install",variant:"secondary",size:"sm",loading:c===y.slug,disabled:!Wn(d),onClick:()=>h(y)})]},y.slug))]})]})},Ql=({accounts:e,projects:n,onCreated:a,onCreateWithAI:r})=>{const[o,i]=b(()=>Nr(e)),[c,s]=b(""),[d,x]=b(""),[h,y]=b(!1),{scope:v,scopeRef:S}=o,w=async()=>{if(!c.trim())return;y(!0);const k=`---
9
9
  name: ${c.trim()}
10
10
  description: ${d.trim()}
11
11
  domain: general
@@ -14,18 +14,18 @@ domain: general
14
14
  # ${c.trim()}
15
15
 
16
16
  ${d.trim()}
17
- `;try{const h=await(await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:m,scopeRef:S,name:c.trim(),content:w})})).json();h.ok?(P("Skill created","success"),a()):P(h.error??"Failed to create skill","error")}catch{P("Failed to create skill","error")}finally{b(!1)}};return l(V,{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:l("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"14px",maxWidth:"560px"},children:[t(Or,{accounts:e,projects:Object.keys(n),value:o,onChange:i}),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)})}),l("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(I,{label:f?"Creating…":"Create",variant:"primary",loading:f,disabled:!c.trim()||!Dn(o),onClick:k}),r&&t(I,{label:"Create with AI",variant:"secondary",disabled:!d.trim()||!Dn(o),title:"Starts a session that drafts the skill",onClick:()=>r(m,S,d.trim())})]})]})})]})},Jl=({accounts:e,projects:n,onCreateWithAI:a,onRunSkill:r,onProposeSkill:o})=>{const[i,c]=y(""),[s,d]=y({kind:"empty"}),[x,f]=y(it.value===null),b=Object.keys(n),m=J(async()=>{try{await Promise.all([Fa(),ea()])}catch{P("Failed to load skills","error")}finally{f(!1)}},[]);F(()=>{(it.value===null||Vt.value===null)&&m()},[m]);const S=it.value??[],k=i.trim().toLowerCase(),w=k?S.filter(p=>p.name.toLowerCase().includes(k)||p.description.toLowerCase().includes(k)):S,u=Vt.value??[],h=s.kind==="plugin"||s.kind==="propose"?u.find(p=>p.id===s.id):void 0;F(()=>{s.kind==="empty"&&S.length>0&&d({kind:"editor",skill:S[0]})},[S.length]);const v=s.kind==="editor"?It(s.skill):null;return l("main",{class:"skills-page grid min-w-0",style:{gridTemplateColumns:"292px minmax(0,1fr)",height:"100vh"},children:[l("div",{class:"skills-rail flex flex-col min-h-0 overflow-hidden",style:{borderRight:"1px solid var(--hair)",background:"var(--bg-2)"},children:[l("div",{class:"flex flex-col shrink-0",style:{padding:"12px 14px",borderBottom:"1px solid var(--hair)",gap:"10px"},children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[t(Xn,{}),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(I,{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:i,onInput:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&i.trim()&&d({kind:"explore",query:i.trim()})}})]}),l("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&&u.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:k?"No installed skill matches.":"No skills yet."}),w.map(p=>{const z=v===It(p);return l("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:p}),children:[l("span",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{class:"shrink-0",style:{width:"7px",height:"7px",borderRadius:"50%",background:`var(${Bl[p.scope]})`}}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:p.name}),t("span",{class:"truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"90px"},children:p.scope==="global"?"global":p.scopeRef})]}),p.description&&t("span",{class:"block truncate",style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:p.description})]},It(p))}),t(Ll,{list:u,query:k,selected:s.kind==="plugin"||s.kind==="propose"?s.id:null,onSelect:p=>d({kind:"plugin",id:p})}),!k&&l("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"})]}),k&&l("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:i.trim()}),children:[t("span",{class:"i-lucide-search shrink-0",style:{width:"13px",height:"13px"}}),l("span",{class:"truncate",children:["Search skills.sh for “",i.trim(),"”"]})]})]})]}),l("div",{class:"flex flex-col min-h-0 min-w-0",children:[s.kind==="editor"&&t(ql,{skill:s.skill,accounts:e,projects:b,onCopied:()=>{m()},onRun:()=>r(s.skill),onDeleted:()=>{d({kind:"empty"}),m()}},It(s.skill)),s.kind==="create"&&t(Vl,{accounts:e,projects:n,onCreateWithAI:a,onCreated:()=>{d({kind:"empty"}),m()}}),s.kind==="explore"&&t(Gl,{query:s.query,accounts:e,projects:b,onInstalled:()=>{m()}}),s.kind==="plugins"&&t(Ml,{accounts:e}),s.kind==="plugin"&&h&&!s.skill&&t(Wl,{plugin:h,accounts:e,query:k,onSelectSkill:p=>d({kind:"plugin",id:h.id,skill:p}),onPropose:()=>d({kind:"propose",id:h.id})}),s.kind==="plugin"&&h&&s.skill&&t(Dl,{plugin:h,name:s.skill,onBack:()=>d({kind:"plugin",id:h.id})},s.skill),s.kind==="propose"&&h&&t(Fl,{plugin:h,accounts:e,onCancel:()=>d({kind:"plugin",id:h.id}),onSubmit:async(p,z,g)=>{await o(h,p,z,g)&&d({kind:"plugin",id:h.id})}}),s.kind==="empty"&&!x&&t("div",{class:"flex-1 grid place-items-center",style:{padding:"24px"},children:l("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(I,{label:"New skill",variant:"primary",onClick:()=>d({kind:"create"})})]})})]})]})},fn={auto:"qa:auto",escalated:"qa:needs-human",blocked:"qa:blocked"},va="<!-- qa-pilot:decision",Yl="-->",Ql=["auto","escalate","blocked"],Zl=["pass","fail","warn"],Xl=["journey","file","severity","artifact"],Te=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ie=e=>typeof e=="string",dt=e=>typeof e=="number"&&Number.isFinite(e);function ei(e){return Te(e)&&ie(e.id)&&ie(e.reason)}function ti(e){return!Te(e)||!ie(e.check)||!ie(e.kind)||!ie(e.message)?!1:Xl.every(n=>e[n]===void 0||ie(e[n]))}function ni(e){if(!Te(e)||e.version!==1||!ie(e.decision)||!Ql.includes(e.decision)||!ie(e.sha)||!Array.isArray(e.gates)||!e.gates.every(ei))return!1;const n=e.diff;return!Te(n)||!dt(n.files)||!dt(n.added)||!dt(n.removed)||!Te(e.checks)||!Object.values(e.checks).every(a=>ie(a)&&Zl.includes(a))?!1:Array.isArray(e.findings)&&e.findings.every(ti)}function ai(e){const n=e.lastIndexOf(va);if(n===-1)return null;const a=n+va.length,r=e.indexOf(Yl,a);if(r===-1)return null;try{const o=JSON.parse(e.slice(a,r));return ni(o)?o:null}catch{return null}}const ri=["github-actions[bot]","github-actions"];function oi(e){var a;const n=(a=e.author)==null?void 0:a.login;return typeof n=="string"&&ri.includes(n)}function li(e){for(let n=e.length-1;n>=0;n--){if(!oi(e[n]))continue;const a=ai(e[n].body);if(a)return a}return null}function ii(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(fn.auto)&&n.auto++,r.has(fn.escalated)&&n.escalated++,r.has(fn.blocked)&&n.blocked++}return n}function si(e,n){return e.sha!==n}const ci=/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/raw\/([0-9a-f]{40})\/(pr-\d+\/[0-9a-f]{7}\/)$/,di=/^artifacts\/[A-Za-z0-9._-]+\.png$/;function pi(e){const n=e.change;if(!Te(n)||!dt(n.pixels)||!dt(n.percent)||!ie(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(ie)&&e.elements.length?`${e.elements.join(", ")} · `:""}${a} · ${n.zone}`}function ui(e){const n=ci.exec(e.evidence??"");if(!n)return[];const[,a,r]=n,o=c=>ie(c)&&di.test(c)?{ref:a,path:r+c}:void 0,i=[];for(const c of e.findings)if(Array.isArray(c.images))for(const s of c.images){if(!Te(s)||!ie(s.name))continue;const d={name:s.name};c.journey&&(d.journey=c.journey),ie(s.ai)&&s.ai&&(d.ai=s.ai.slice(0,200));const x=pi(s);x&&(d.summary=x);const f=o(s.expected),b=o(s.marked)??o(s.actual),m=o(s.diff);f&&(d.before=f),b&&(d.after=b),m&&(d.diff=m),(f||b||m)&&i.push(d)}return i}function Wn(e){const n=Jt(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 Jt(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 hi(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 fi={pass:"✓",fail:"✗",warn:"!"};function gi(e){return fi[e]}const xi=/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/;function mi(e){const n=Jt(e);if(!n.ok){const a=n.message.split(`
17
+ `;try{const f=await(await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:v,scopeRef:S,name:c.trim(),content:k})})).json();f.ok?(I("Skill created","success"),a()):I(f.error??"Failed to create skill","error")}catch{I("Failed to create skill","error")}finally{y(!1)}};return l(G,{children:[t(Ee,{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:l("div",{class:"flex flex-col",style:{padding:"16px 20px 24px",gap:"14px",maxWidth:"560px"},children:[t(Or,{accounts:e,projects:Object.keys(n),value:o,onChange:i}),t(U,{label:"Name",children:t("input",{class:"field",value:c,placeholder:"my-skill",onInput:k=>s(k.target.value)})}),t(U,{label:"Description",children:t("textarea",{class:"field",rows:3,value:d,placeholder:"What does this skill do?",onInput:k=>x(k.target.value)})}),l("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(L,{label:h?"Creating…":"Create",variant:"primary",loading:h,disabled:!c.trim()||!Wn(o),onClick:w}),r&&t(L,{label:"Create with AI",variant:"secondary",disabled:!d.trim()||!Wn(o),title:"Starts a session that drafts the skill",onClick:()=>r(v,S,d.trim())})]})]})})]})},Zl=({accounts:e,projects:n,onCreateWithAI:a,onRunSkill:r,onProposeSkill:o})=>{const[i,c]=b(""),[s,d]=b({kind:"empty"}),[x,h]=b("skills"),[y,v]=b(it.value===null),S=Object.keys(n),w=J(async()=>{try{await Promise.all([Fa(),ea()])}catch{I("Failed to load skills","error")}finally{v(!1)}},[]);F(()=>{(it.value===null||ct.value===null)&&w()},[w]);const k=it.value??[],p=i.trim().toLowerCase(),f=p?k.filter($=>$.name.toLowerCase().includes(p)||$.description.toLowerCase().includes(p)):k,m=ct.value??[],u=s.kind==="plugin"||s.kind==="propose"?m.find($=>$.id===s.id):void 0,T=m.filter($=>$.installs.some(A=>A.update)).length;F(()=>{s.kind==="empty"&&k.length>0&&d({kind:"editor",skill:k[0]})},[k.length]);const g=s.kind==="editor"?Lt(s.skill):null;return l("main",{class:"skills-page grid min-w-0",style:{gridTemplateColumns:"292px minmax(0,1fr)",height:"100vh"},children:[l("div",{class:"skills-rail flex flex-col min-h-0 overflow-hidden",style:{borderRight:"1px solid var(--hair)",background:"var(--bg-2)"},children:[l("div",{class:"flex flex-col shrink-0",style:{padding:"12px 14px",borderBottom:"1px solid var(--hair)",gap:"10px"},children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[t(Xn,{}),t("h1",{style:{fontSize:"18px",fontWeight:700,letterSpacing:"-0.02em"},children:"Skills"}),t("span",{class:"flex-1"}),t(L,{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:i,onInput:$=>c($.target.value),onKeyDown:$=>{$.key==="Enter"&&i.trim()&&d({kind:"explore",query:i.trim()})}}),t(le,{fill:!0,size:"sm",label:"Skills or plugins",tabs:[{id:"skills",label:"Skills",count:k.length},{id:"plugins",label:"Plugins",count:T>0?`${m.length} · ${T}↑`:m.length}],active:x,onChange:$=>{h($);const A=s.kind==="plugin"||s.kind==="propose"||s.kind==="plugins";$==="plugins"&&!A&&d(m[0]?{kind:"plugin",id:m[0].id}:{kind:"plugins"}),$==="skills"&&A&&d(k[0]?{kind:"editor",skill:k[0]}:{kind:"empty"})}})]}),l("div",{class:"overflow-auto min-h-0",style:{padding:"8px"},children:[y&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:"Loading skills…"}),!y&&x==="skills"&&f.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:p?"No installed skill matches.":"No skills yet."}),x==="plugins"&&m.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:ct.value===null?"Loading plugins…":"No Claude Code plugins installed."}),x==="skills"&&f.map($=>{const A=g===Lt($);return l("button",{type:"button","aria-current":A?"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 ${A?"var(--hair)":"transparent"}`,background:A?"var(--card)":"transparent",boxShadow:A?"var(--shadow-s)":"none",color:"var(--ink)"},onClick:()=>d({kind:"editor",skill:$}),children:[l("span",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{class:"shrink-0",style:{width:"7px",height:"7px",borderRadius:"50%",background:`var(${Ul[$.scope]})`}}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:$.name}),t("span",{class:"truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"90px"},children:$.scope==="global"?"global":$.scopeRef})]}),$.description&&t("span",{class:"block truncate",style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:$.description})]},Lt($))}),x==="plugins"&&t(Wl,{list:m,query:p,selected:s.kind==="plugin"||s.kind==="propose"?s.id:null,onSelect:$=>d({kind:"plugin",id:$})}),x==="plugins"&&!p&&l("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"})]}),p&&l("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:i.trim()}),children:[t("span",{class:"i-lucide-search shrink-0",style:{width:"13px",height:"13px"}}),l("span",{class:"truncate",children:["Search skills.sh for “",i.trim(),"”"]})]})]})]}),l("div",{class:"flex flex-col min-h-0 min-w-0",children:[s.kind==="editor"&&t(Jl,{skill:s.skill,accounts:e,projects:S,onCopied:()=>{w()},onRun:()=>r(s.skill),onDeleted:()=>{d({kind:"empty"}),w()}},Lt(s.skill)),s.kind==="create"&&t(Ql,{accounts:e,projects:n,onCreateWithAI:a,onCreated:()=>{d({kind:"empty"}),w()}}),s.kind==="explore"&&t(Yl,{query:s.query,accounts:e,projects:S,onInstalled:()=>{w()}}),s.kind==="plugins"&&t(_l,{accounts:e}),s.kind==="plugin"&&u&&!s.skill&&t(Bl,{plugin:u,accounts:e,query:p,onSelectSkill:$=>d({kind:"plugin",id:u.id,skill:$}),onPropose:()=>d({kind:"propose",id:u.id})}),s.kind==="plugin"&&u&&s.skill&&t(Fl,{plugin:u,name:s.skill,onBack:()=>d({kind:"plugin",id:u.id})},s.skill),s.kind==="propose"&&u&&t(Kl,{plugin:u,accounts:e,onCancel:()=>d({kind:"plugin",id:u.id}),onSubmit:async($,A,N)=>{await o(u,$,A,N)&&d({kind:"plugin",id:u.id})}}),s.kind==="empty"&&!y&&t("div",{class:"flex-1 grid place-items-center",style:{padding:"24px"},children:l("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(L,{label:"New skill",variant:"primary",onClick:()=>d({kind:"create"})})]})})]})]})},fn={auto:"qa:auto",escalated:"qa:needs-human",blocked:"qa:blocked"},va="<!-- qa-pilot:decision",Xl="-->",ei=["auto","escalate","blocked"],ti=["pass","fail","warn"],ni=["journey","file","severity","artifact"],Te=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),se=e=>typeof e=="string",pt=e=>typeof e=="number"&&Number.isFinite(e);function ai(e){return Te(e)&&se(e.id)&&se(e.reason)}function ri(e){return!Te(e)||!se(e.check)||!se(e.kind)||!se(e.message)?!1:ni.every(n=>e[n]===void 0||se(e[n]))}function oi(e){if(!Te(e)||e.version!==1||!se(e.decision)||!ei.includes(e.decision)||!se(e.sha)||!Array.isArray(e.gates)||!e.gates.every(ai))return!1;const n=e.diff;return!Te(n)||!pt(n.files)||!pt(n.added)||!pt(n.removed)||!Te(e.checks)||!Object.values(e.checks).every(a=>se(a)&&ti.includes(a))?!1:Array.isArray(e.findings)&&e.findings.every(ri)}function li(e){const n=e.lastIndexOf(va);if(n===-1)return null;const a=n+va.length,r=e.indexOf(Xl,a);if(r===-1)return null;try{const o=JSON.parse(e.slice(a,r));return oi(o)?o:null}catch{return null}}const ii=["github-actions[bot]","github-actions"];function si(e){var a;const n=(a=e.author)==null?void 0:a.login;return typeof n=="string"&&ii.includes(n)}function ci(e){for(let n=e.length-1;n>=0;n--){if(!si(e[n]))continue;const a=li(e[n].body);if(a)return a}return null}function di(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(fn.auto)&&n.auto++,r.has(fn.escalated)&&n.escalated++,r.has(fn.blocked)&&n.blocked++}return n}function pi(e,n){return e.sha!==n}const ui=/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/raw\/([0-9a-f]{40})\/(pr-\d+\/[0-9a-f]{7}\/)$/,hi=/^artifacts\/[A-Za-z0-9._-]+\.png$/;function fi(e){const n=e.change;if(!Te(n)||!pt(n.pixels)||!pt(n.percent)||!se(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(se)&&e.elements.length?`${e.elements.join(", ")} · `:""}${a} · ${n.zone}`}function gi(e){const n=ui.exec(e.evidence??"");if(!n)return[];const[,a,r]=n,o=c=>se(c)&&hi.test(c)?{ref:a,path:r+c}:void 0,i=[];for(const c of e.findings)if(Array.isArray(c.images))for(const s of c.images){if(!Te(s)||!se(s.name))continue;const d={name:s.name};c.journey&&(d.journey=c.journey),se(s.ai)&&s.ai&&(d.ai=s.ai.slice(0,200));const x=fi(s);x&&(d.summary=x);const h=o(s.expected),y=o(s.marked)??o(s.actual),v=o(s.diff);h&&(d.before=h),y&&(d.after=y),v&&(d.diff=v),(h||y||v)&&i.push(d)}return i}function Dn(e){const n=Jt(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 Jt(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 xi(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 mi={pass:"✓",fail:"✗",warn:"!"};function vi(e){return mi[e]}const yi=/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/;function bi(e){const n=Jt(e);if(!n.ok){const a=n.message.split(`
18
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 xi.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)`,xe={background:"var(--card)",border:"1px solid var(--hair)",borderRadius:"12px"},vi={pass:"--green",fail:"--red",warn:"--orange"};function yi(e,n,a){return J(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(i){return{error:i instanceof Error?i.message:"Forge no respondió"}}},[e,n,a])}function Wr({message:e,onRetry:n}){return l("div",{style:{...xe,padding:"18px 20px",borderColor:bt("--red",50)},children:[t("h3",{style:{fontSize:"15px",fontWeight:700,marginBottom:"6px"},children:"No se pudo leer GitHub"}),l("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(I,{label:"Reintentar",variant:"secondary",size:"sm",onClick:n})]})}function bi({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=>l("div",{style:{...xe,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 ya({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 ki({decision:e}){return l(V,{children:[l("div",{class:"flex flex-wrap gap-1.5",children:[e.gates.map(n=>t(ya,{label:`${n.id} · ${n.reason}`,tone:"--orange"},n.id+n.reason)),Object.entries(e.checks).map(([n,a])=>t(ya,{label:`${n} ${gi(a)}`,tone:a==="pass"?void 0:vi[a]},n))]}),e.findings.length>0&&l("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)=>l("li",{style:{...xe,borderRadius:"8px",padding:"8px 10px",fontSize:"12.5px"},children:[l("div",{class:"flex flex-wrap gap-1.5 mb-1",style:{fontSize:"11px",color:"var(--ink-3)"},children:[t("span",{children:n.check}),l("span",{children:["· ",n.kind]}),n.journey&&l("span",{children:["· ",n.journey]}),n.severity&&l("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 gn({file:e,label:n,run:a,onOpen:r}){const[o,i]=y({state:"loading"});F(()=>{if(!e)return;let s=!0;return i({state:"loading"}),a("get-evidence",{REF:e.ref,PATH:e.path}).then(d=>{const x=mi(d);s&&i(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={...xe,borderRadius:"8px",overflow:"hidden",aspectRatio:"4 / 3",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--elev)"};return l("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 wi({changes:e,run:n}){const[a,r]=y(null);F(()=>{if(!a)return;const i=c=>{c.key==="Escape"&&r(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]);const o=(i,c)=>r({src:i,label:c});return l("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(i=>l("li",{style:{...xe,borderRadius:"10px",padding:"10px 12px"},children:[l("div",{style:{fontSize:"12.5px",fontWeight:600},children:[i.name,i.journey?` · ${i.journey}`:""]}),i.ai&&l("p",{style:{fontSize:"13px",margin:"4px 0 0"},children:[i.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"})]}),i.summary&&l("p",{style:{fontSize:"12px",color:"var(--ink-2)",margin:"3px 0 0"},children:["Cambió: ",i.summary]}),l("div",{class:"grid gap-2 mt-2",style:{gridTemplateColumns:"repeat(3, minmax(0, 1fr))"},children:[t(gn,{file:i.before,label:"Antes",run:n,onOpen:o}),t(gn,{file:i.after,label:"Después",run:n,onOpen:o}),t(gn,{file:i.diff,label:"Diferencia",run:n,onOpen:o})]})]},i.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 Si({pr:e,run:n,onDone:a}){var z;const[r,o]=y({state:"loading"}),[i,c]=y(!1),[s,d]=y(""),[x,f]=y("Esperando tu decisión."),b=J(async()=>{o({state:"loading"});const g=Wn(await n("get-decision",{PR:String(e.number)}));o(g.ok?{state:"ok",data:g.data}:{state:"error",message:g.message})},[e.number,n]);if(F(()=>{c(!1),d(""),f("Esperando tu decisión."),b()},[b]),r.state==="loading")return t("div",{style:{...xe,height:"220px"},class:"animate-pulse"});if(r.state==="error")return t(Wr,{message:r.message,onRetry:b});const m=r.data,S=li(m.comments),k=S?si(S,m.headRefOid):!1,w=S!==null&&S.decision==="escalate"&&!k,u=S?ui(S):[],h=(S==null?void 0:S.diff)??{files:m.changedFiles,added:m.additions,removed:m.deletions},v=async()=>{const g=Jt(await n("approve",{PR:String(e.number)}));f(g.ok?"Aprobado: qa-pilot pone el status en verde y activa el auto-merge.":`No se pudo aprobar: ${g.message}`),g.ok&&a()},p=async()=>{const g=Jt(await n("request-changes",{PR:String(e.number),MSG:s.trim()}));g.ok?(f("Comentario publicado en el PR."),c(!1),d("")):f(g.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: ${g.message}`)};return l("div",{class:"flex flex-col gap-3.5",style:{...xe,padding:"16px 18px",minWidth:0},children:[l("div",{children:[l("h3",{style:{fontSize:"15px",fontWeight:700,letterSpacing:"-0.01em"},children:["#",m.number," · ",m.title]}),l("div",{style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:[(z=m.author)!=null&&z.login?`abierto por ${m.author.login} en `:"rama ",t("code",{style:{fontFamily:"var(--mono)"},children:m.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."}):l(V,{children:[k&&l("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:m.headRefOid.slice(0,7)}),". Espera la nueva corrida."]}),t(ki,{decision:S}),u.length>0&&t(wi,{changes:u,run:n})]}),i&&l("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:g=>d(g.target.value.replace(/\s*\n\s*/g," ")),style:{...xe,borderRadius:"8px",padding:"8px 10px",fontSize:"13px",color:"var(--ink)",fontFamily:"var(--font)",resize:"vertical"}}),l("div",{class:"flex gap-2",children:[t(I,{label:"Enviar comentario",size:"sm",disabled:s.trim()==="",onClick:p}),t(I,{label:"Cancelar",variant:"secondary",size:"sm",onClick:()=>c(!1)})]})]}),l("div",{class:"flex flex-wrap gap-2",children:[!i&&t(I,{label:"Pedir cambios",variant:"secondary",icon:"i-lucide-message-square",onClick:()=>c(!0)}),t(I,{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:v}),l("a",{href:m.url,target:"_blank",rel:"noreferrer",class:"inline-flex items-center gap-1.5",style:{...xe,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 Ci({moduleId:e,projectId:n,cwProject:a}){const r=yi(e,n,a),o=!!(n||a),[i,c]=y({state:"loading"}),[s,d]=y({state:"loading"}),[x,f]=y(null),b=J(async()=>{c({state:"loading"});const[S,k]=await Promise.all([r("list-escalations").then(w=>Wn(w)),r("week-stats").then(w=>Wn(w))]);c(S.ok?{state:"ok",data:S.data}:{state:"error",message:S.message}),d(k.ok?{state:"ok",data:ii(k.data)}:{state:"error",message:k.message}),S.ok&&f(w=>{var u;return S.data.some(h=>h.number===w)?w:((u=S.data[0])==null?void 0:u.number)??null})},[r]);if(F(()=>{o&&b()},[o,b]),!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 m=i.state==="ok"?i.data.find(S=>S.number===x):void 0;return l("div",{children:[l("div",{class:"flex items-center justify-between mb-3.5",children:[t("h2",{style:{fontSize:"15px",fontWeight:700},children:"Escalamientos"}),t(I,{label:"Actualizar",variant:"secondary",size:"sm",icon:"i-lucide-refresh-cw",loading:i.state==="loading",onClick:b})]}),t(bi,{stats:s}),i.state==="loading"?t("div",{style:{...xe,height:"160px"},class:"animate-pulse"}):i.state==="error"?t(Wr,{message:i.message,onRetry:b}):i.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."}):l("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:i.data.map(S=>{var k;return l("button",{type:"button",role:"option","aria-selected":S.number===x,onClick:()=>f(S.number),class:"text-left cursor-pointer",style:{...xe,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:[l("div",{class:"flex justify-between gap-2",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[l("span",{children:["#",S.number," · ",hi(S.updatedAt)]}),((k=S.author)==null?void 0:k.login)&&t("span",{children:S.author.login})]}),t("b",{style:{display:"block",fontSize:"13px",marginTop:"2px"},children:S.title})]},S.number)})}),m&&t(Si,{pr:m,run:r,onDone:b},m.number)]})]})}const $i=Qr({id:"escalations",title:"Escalamientos",component:Ci}),Mr="forge.qa.project",zi="mod-qa";function ba(){try{return localStorage.getItem(Mr)??""}catch{return""}}const Ri=({projects:e,preferred:n})=>{const a=Object.keys(e).sort(),r=d=>a.includes(d)?d:a[0]??"",[o,i]=y(()=>r(n||ba()));F(()=>{a.includes(o)||i(r(n||ba()))},[a.join(`
20
- `),n]);const c=d=>{i(d);try{localStorage.setItem(Mr,d)}catch{}},s=$i.component;return l("div",{class:"flex flex-col min-h-full",children:[t(Ve,{title:"QA",subtitle:"PRs que qa-pilot escaló a una persona, con la evidencia para decidir",children:a.length>0&&l("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:zi,projectId:null,cwProject:o},o)})]})},Et=e=>e.target.value,Ti=({accounts:e,onOpenSession:n,onFramesChanged:a})=>{const[r,o]=y(null),[i,c]=y(null),[s,d]=y(""),[x,f]=y(""),[b,m]=y(""),[S,k]=y(null),[w,u]=y(""),h=J(async()=>{try{const R=await(await fetch("/api/liveframe/frames")).json();c(R),a(R.length)}catch{c([])}},[a]);F(()=>{h(),fetch("/api/liveframe/status").then(R=>R.json()).then(o).catch(()=>{})},[h]);const v=async R=>{if(r)try{const T=await ge("/api/cw/start",{type:"general",account:r.account,directory:R.dir,task:`Liveframe: ${R.project}/${R.frame}`});n(T.session)}catch(T){P(pe(T),"error")}},p=async(R,T)=>{try{const $=await R;return P(T,"success"),h(),await v($),!0}catch($){return P(pe($),"error"),!1}},z=async()=>{await p(ge("/api/liveframe/frames",{project:s,name:x}),`Frame "${x}" created`)&&f("")},g=async()=>{await p(ge("/api/liveframe/pull",{target:b}),`Pulled ${b}`)&&m("")},A=async()=>{if(S)try{const{url:R}=await ge(`/api/liveframe/frames/${S.project}/${S.frame}/push`,{note:w});P(`Published: ${R}`,"success"),k(null)}catch(R){P(pe(R),"error")}},L=r!==null&&!e.includes(r.account),N=(r==null?void 0:r.installed)!==!1&&!L,O=(i??[]).reduce((R,T)=>{var $;return(R[$=T.project]??(R[$]=[])).push(T),R},{});return l(V,{children:[l(Ve,{title:"Prototypes",subtitle:r?`Liveframe frames in ${r.root} · agents run on ${r.account}`:"Liveframe frames",children:[r&&l("a",{class:He,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(I,{label:"Refresh",variant:"secondary",onClick:h})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[r&&!r.installed&&l("p",{style:{...de,background:Z("--red")},children:["The Liveframe CLI is not installed. Run ",l("code",{children:["npm i -g ",r.api,"/cli.tgz"]}),", then ",t("code",{children:"lf login"}),"."]}),L&&l("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&&l("p",{style:{...de,background:Z("--orange")},children:["Liveframe is not signed in on this machine. Run ",t("code",{children:"lf login"})," in a terminal."]}),l("section",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(300px, 1fr))",gap:"14px"},children:[l("div",{class:"flex flex-col",style:{...Me,padding:"16px 18px",gap:"12px"},children:[l("div",{children:[t("h2",{style:{fontSize:"14.5px",fontWeight:600},children:"New prototype"}),l("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:R=>d(Et(R))})}),t(U,{label:"Frame name",children:t("input",{type:"text",class:"field",value:x,placeholder:"Checkout ideas",onInput:R=>f(Et(R))})}),t("div",{class:"flex justify-end",children:t(I,{label:"Create and open agent",variant:"primary",size:"sm",disabled:!N||!s.trim()||!x.trim(),onClick:z})})]}),l("div",{class:"flex flex-col",style:{...Me,padding:"16px 18px",gap:"12px"},children:[l("div",{children:[t("h2",{style:{fontSize:"14.5px",fontWeight:600},children:"Continue a frame"}),l("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:b,placeholder:"reservas/checkout-flow",onInput:R=>m(Et(R))})}),t("div",{class:"flex justify-end",children:t(I,{label:"Pull and open agent",variant:"secondary",size:"sm",disabled:!N||!b.includes("/"),onClick:g})})]})]}),i&&i.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(O).map(([R,T])=>l("section",{style:{...Me,overflow:"hidden"},children:[t("h2",{style:{padding:"12px 18px",fontSize:"13px",fontWeight:600,borderBottom:"1px solid var(--hair)"},children:R}),T.map($=>l("div",{class:"flex items-center flex-wrap",style:{gap:"10px",padding:"12px 18px",borderBottom:"1px solid var(--hair)"},children:[l("div",{class:"min-w-0",style:{flex:"1 1 220px"},children:[t("p",{class:"truncate",style:{fontSize:"13.5px",fontWeight:500},children:$.frame}),l("p",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-3)"},children:[$.kind," · ",$.branch," · ",$.dir]})]}),l("a",{class:He,style:Ie,href:$.url,target:"_blank",rel:"noopener noreferrer",children:["Live ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),t(I,{label:"Push",variant:"secondary",size:"sm",disabled:!N,onClick:()=>{u(""),k($)}}),t(I,{label:"Open agent",variant:"primary",size:"sm",disabled:!r||L,onClick:()=>v($)})]},$.dir))]},R))]}),t(Ee,{open:S!==null,title:`Push ${S==null?void 0:S.project}/${S==null?void 0:S.frame}`,onClose:()=>k(null),children:l("div",{class:"space-y-4",children:[l("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:R=>u(Et(R))})}),t("div",{class:"flex justify-end pt-1",children:t(I,{label:"Push",variant:"primary",onClick:A})})]})})]})},ji=[{id:"project",label:"Project"},{id:"team",label:"Team"},{id:"personal",label:"Personal"}],We="__new";async function en(e,n,a,r){try{await ge(e,n),P(a,"success"),Re(!0),r()}catch(o){P(pe(o),"error")}}const Mn=e=>{var n;return(((n=ye.value)==null?void 0:n.brains)??[]).filter(a=>a.onDisk&&e.includes(a.tier??""))},Fr=()=>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."}),Pi=({onClose:e})=>{const[n,a]=y(""),[r,o]=y("project"),[i,c]=y(""),[s,d]=y(""),x=Mn(["team"]);return l(qe,{title:"New brain",onClose:e,children:[t("div",{class:"flex",children:t(se,{size:"sm",label:"Tier",tabs:ji,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:f=>a(ne(f))})}),r==="project"&&x.length>0&&t(Fn,{label:"Team brain",brains:x,value:i,onValue:c}),t(U,{label:"Language of its pages · optional",children:t("input",{type:"text",class:"field",value:s,placeholder:"en",onInput:f=>d(ne(f))})}),t(Fr,{}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(I,{label:"Cancel",variant:"secondary",onClick:e}),t(I,{label:"Create",variant:"primary",disabled:!n.trim(),onClick:()=>en("/api/kioku/brains",{repo:n,tier:r,team:i,language:s},`Made ${n.trim()}`,e)})]})]})},Fn=({label:e,brains:n,value:a,onValue:r,repo:o,placeholder:i,onRepo:c})=>l(V,{children:[t(U,{label:e,children:l("select",{class:"field",value:a,onChange:s=>r(ne(s)),children:[t("option",{value:"",children:"None"}),n.map(s=>t("option",{value:s.key,children:re(s)},s.key)),c&&t("option",{value:We,children:"New brain…"})]})}),c&&a===We&&t("input",{type:"text",class:"field",value:o,placeholder:i,onInput:s=>c(ne(s))})]}),Ai=({project:e,onClose:n})=>{const[a,r]=y(We),[o,i]=y(""),[c,s]=y(""),[d,x]=y(""),f=(m,S)=>m===We?S.trim():m,b={brain:f(a,o),team:f(c,d)};return l(qe,{title:`A brain for ${e}`,onClose:n,children:[t(Fn,{label:"Project brain",brains:Mn(["project","client"]),value:a,repo:o,placeholder:`monoku/brain-${e}`,onValue:r,onRepo:i}),t(Fn,{label:"Team brain",brains:Mn(["team"]),value:c,repo:d,placeholder:"monoku/brain",onValue:s,onRepo:x}),l("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===We||c===We)&&t(Fr,{}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:"Link",variant:"primary",disabled:!b.brain&&!b.team,onClick:()=>en("/api/kioku/link",{project:e,...b},`Linked ${e}`,n)})]})]})},Br=({brain:e,onClose:n})=>{const[a,r]=y(""),[o,i]=y("");return t(Ee,{open:!0,title:`New area in ${re(e)}`,onClose:n,children:l("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(ne(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=>i(ne(c))})}),e.namespaces.length>0&&l("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Areas now: ",e.namespaces.join(", ")]}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:"Add area",variant:"primary",disabled:!a.trim()||!o.trim(),onClick:()=>en("/api/kioku/areas",{brain:e.key,area:a,summary:o},`Added ${a.trim()} to ${re(e)}`,n)})]})]})})},Ii=({brain:e,onClose:n})=>{const[a,r]=y(""),[o,i]=y(!1),c=re(e);return t(Ee,{open:!0,title:`Publish ${c}`,onClose:n,children:l("div",{class:"flex flex-col",style:{gap:"12px"},children:[l("div",{style:{...de,background:Z("--red")},children:[l("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(ne(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.":l(V,{children:["Left empty, kioku makes a private GitHub repository for ",t("code",{children:e.key})," with ",t("code",{children:"gh"}),", unless it exists."]})}),l("label",{class:"flex items-start cursor-pointer",style:{gap:"8px",fontSize:"12.5px"},children:[t("input",{type:"checkbox",checked:o,onChange:s=>i(s.target.checked),style:{marginTop:"2px"}}),l("span",{children:["I have the approval this needs, or it needs none. Publishing ",c," is my decision."]})]}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:"Publish",variant:"destructive",disabled:!o,onClick:()=>en("/api/kioku/publish",{brain:e.key,to:a,understood:o},`Published ${c}`,n)})]})]})})};function Ei(e,n){const r=(n?Yn(n):[]).find(o=>o.tier==="project"||o.tier==="client")??e.find(o=>o.personal)??e[0];return(r==null?void 0:r.key)??""}const Li=({project:e,onClose:n})=>{var B;const a=(((B=ye.value)==null?void 0:B.brains)??[]).filter(j=>j.onDisk),[r,o]=y(()=>Ei(a,e)),[i,c]=y(Tt[0].id),[s,d]=y(""),[x,f]=y(""),[b,m]=y(""),[S,k]=y({}),[w,u]=y(null),[h,v]=y(!1),[p,z]=y(!1),g=a.find(j=>j.key===r),A=(g==null?void 0:g.namespaces)??[],L=A.length===1?A[0]:s,N=Tt.find(j=>j.id===i)??Tt[0],O=N.sections.length===0,R=O?["Text"]:N.sections,T=!!(g&&L&&x.trim()&&b.trim()&&R.every(j=>{var W;return(W=S[j])==null?void 0:W.trim()})),$=async(j=!1)=>{if(!g||!T||h)return;v(!0);const W=O?`${(S.Text??"").trim()}
19
+ `)[0]}}return yi.test(n.data)?{ok:!0,data:`data:image/png;base64,${n.data}`}:{ok:!1,message:"la imagen no es un PNG"}}const kt=(e,n=16)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,xe={background:"var(--card)",border:"1px solid var(--hair)",borderRadius:"12px"},ki={pass:"--green",fail:"--red",warn:"--orange"};function wi(e,n,a){return J(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(i){return{error:i instanceof Error?i.message:"Forge no respondió"}}},[e,n,a])}function Dr({message:e,onRetry:n}){return l("div",{style:{...xe,padding:"18px 20px",borderColor:kt("--red",50)},children:[t("h3",{style:{fontSize:"15px",fontWeight:700,marginBottom:"6px"},children:"No se pudo leer GitHub"}),l("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(L,{label:"Reintentar",variant:"secondary",size:"sm",onClick:n})]})}function Si({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=>l("div",{style:{...xe,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 ya({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?kt(n):"var(--elev)"},children:e})}function Ci({decision:e}){return l(G,{children:[l("div",{class:"flex flex-wrap gap-1.5",children:[e.gates.map(n=>t(ya,{label:`${n.id} · ${n.reason}`,tone:"--orange"},n.id+n.reason)),Object.entries(e.checks).map(([n,a])=>t(ya,{label:`${n} ${vi(a)}`,tone:a==="pass"?void 0:ki[a]},n))]}),e.findings.length>0&&l("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)=>l("li",{style:{...xe,borderRadius:"8px",padding:"8px 10px",fontSize:"12.5px"},children:[l("div",{class:"flex flex-wrap gap-1.5 mb-1",style:{fontSize:"11px",color:"var(--ink-3)"},children:[t("span",{children:n.check}),l("span",{children:["· ",n.kind]}),n.journey&&l("span",{children:["· ",n.journey]}),n.severity&&l("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 gn({file:e,label:n,run:a,onOpen:r}){const[o,i]=b({state:"loading"});F(()=>{if(!e)return;let s=!0;return i({state:"loading"}),a("get-evidence",{REF:e.ref,PATH:e.path}).then(d=>{const x=bi(d);s&&i(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={...xe,borderRadius:"8px",overflow:"hidden",aspectRatio:"4 / 3",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--elev)"};return l("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 $i({changes:e,run:n}){const[a,r]=b(null);F(()=>{if(!a)return;const i=c=>{c.key==="Escape"&&r(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]);const o=(i,c)=>r({src:i,label:c});return l("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(i=>l("li",{style:{...xe,borderRadius:"10px",padding:"10px 12px"},children:[l("div",{style:{fontSize:"12.5px",fontWeight:600},children:[i.name,i.journey?` · ${i.journey}`:""]}),i.ai&&l("p",{style:{fontSize:"13px",margin:"4px 0 0"},children:[i.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:kt("--purple"),color:"var(--purple)"},children:"IA"})]}),i.summary&&l("p",{style:{fontSize:"12px",color:"var(--ink-2)",margin:"3px 0 0"},children:["Cambió: ",i.summary]}),l("div",{class:"grid gap-2 mt-2",style:{gridTemplateColumns:"repeat(3, minmax(0, 1fr))"},children:[t(gn,{file:i.before,label:"Antes",run:n,onOpen:o}),t(gn,{file:i.after,label:"Después",run:n,onOpen:o}),t(gn,{file:i.diff,label:"Diferencia",run:n,onOpen:o})]})]},i.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 zi({pr:e,run:n,onDone:a}){var T;const[r,o]=b({state:"loading"}),[i,c]=b(!1),[s,d]=b(""),[x,h]=b("Esperando tu decisión."),y=J(async()=>{o({state:"loading"});const g=Dn(await n("get-decision",{PR:String(e.number)}));o(g.ok?{state:"ok",data:g.data}:{state:"error",message:g.message})},[e.number,n]);if(F(()=>{c(!1),d(""),h("Esperando tu decisión."),y()},[y]),r.state==="loading")return t("div",{style:{...xe,height:"220px"},class:"animate-pulse"});if(r.state==="error")return t(Dr,{message:r.message,onRetry:y});const v=r.data,S=ci(v.comments),w=S?pi(S,v.headRefOid):!1,k=S!==null&&S.decision==="escalate"&&!w,p=S?gi(S):[],f=(S==null?void 0:S.diff)??{files:v.changedFiles,added:v.additions,removed:v.deletions},m=async()=>{const g=Jt(await n("approve",{PR:String(e.number)}));h(g.ok?"Aprobado: qa-pilot pone el status en verde y activa el auto-merge.":`No se pudo aprobar: ${g.message}`),g.ok&&a()},u=async()=>{const g=Jt(await n("request-changes",{PR:String(e.number),MSG:s.trim()}));g.ok?(h("Comentario publicado en el PR."),c(!1),d("")):h(g.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: ${g.message}`)};return l("div",{class:"flex flex-col gap-3.5",style:{...xe,padding:"16px 18px",minWidth:0},children:[l("div",{children:[l("h3",{style:{fontSize:"15px",fontWeight:700,letterSpacing:"-0.01em"},children:["#",v.number," · ",v.title]}),l("div",{style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:[(T=v.author)!=null&&T.login?`abierto por ${v.author.login} en `:"rama ",t("code",{style:{fontFamily:"var(--mono)"},children:v.headRefName}),` · ${f.files} archivos, +${f.added} −${f.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."}):l(G,{children:[w&&l("p",{style:{fontSize:"12.5px",padding:"8px 10px",borderRadius:"8px",background:kt("--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:v.headRefOid.slice(0,7)}),". Espera la nueva corrida."]}),t(Ci,{decision:S}),p.length>0&&t($i,{changes:p,run:n})]}),i&&l("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:g=>d(g.target.value.replace(/\s*\n\s*/g," ")),style:{...xe,borderRadius:"8px",padding:"8px 10px",fontSize:"13px",color:"var(--ink)",fontFamily:"var(--font)",resize:"vertical"}}),l("div",{class:"flex gap-2",children:[t(L,{label:"Enviar comentario",size:"sm",disabled:s.trim()==="",onClick:u}),t(L,{label:"Cancelar",variant:"secondary",size:"sm",onClick:()=>c(!1)})]})]}),l("div",{class:"flex flex-wrap gap-2",children:[!i&&t(L,{label:"Pedir cambios",variant:"secondary",icon:"i-lucide-message-square",onClick:()=>c(!0)}),t(L,{label:"Aprobar",icon:"i-lucide-check",disabled:!k,title:k?"Añade qa:approved al PR":"Solo se aprueba una decisión escalada y vigente",onClick:m}),l("a",{href:v.url,target:"_blank",rel:"noreferrer",class:"inline-flex items-center gap-1.5",style:{...xe,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 Ri({moduleId:e,projectId:n,cwProject:a}){const r=wi(e,n,a),o=!!(n||a),[i,c]=b({state:"loading"}),[s,d]=b({state:"loading"}),[x,h]=b(null),y=J(async()=>{c({state:"loading"});const[S,w]=await Promise.all([r("list-escalations").then(k=>Dn(k)),r("week-stats").then(k=>Dn(k))]);c(S.ok?{state:"ok",data:S.data}:{state:"error",message:S.message}),d(w.ok?{state:"ok",data:di(w.data)}:{state:"error",message:w.message}),S.ok&&h(k=>{var p;return S.data.some(f=>f.number===k)?k:((p=S.data[0])==null?void 0:p.number)??null})},[r]);if(F(()=>{o&&y()},[o,y]),!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 v=i.state==="ok"?i.data.find(S=>S.number===x):void 0;return l("div",{children:[l("div",{class:"flex items-center justify-between mb-3.5",children:[t("h2",{style:{fontSize:"15px",fontWeight:700},children:"Escalamientos"}),t(L,{label:"Actualizar",variant:"secondary",size:"sm",icon:"i-lucide-refresh-cw",loading:i.state==="loading",onClick:y})]}),t(Si,{stats:s}),i.state==="loading"?t("div",{style:{...xe,height:"160px"},class:"animate-pulse"}):i.state==="error"?t(Dr,{message:i.message,onRetry:y}):i.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."}):l("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:i.data.map(S=>{var w;return l("button",{type:"button",role:"option","aria-selected":S.number===x,onClick:()=>h(S.number),class:"text-left cursor-pointer",style:{...xe,borderRadius:"10px",padding:"10px 12px",color:"var(--ink)",borderColor:S.number===x?"var(--blue)":"var(--hair)",background:S.number===x?kt("--blue",10):"var(--card)"},children:[l("div",{class:"flex justify-between gap-2",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[l("span",{children:["#",S.number," · ",xi(S.updatedAt)]}),((w=S.author)==null?void 0:w.login)&&t("span",{children:S.author.login})]}),t("b",{style:{display:"block",fontSize:"13px",marginTop:"2px"},children:S.title})]},S.number)})}),v&&t(zi,{pr:v,run:r,onDone:y},v.number)]})]})}const Ti=Qr({id:"escalations",title:"Escalamientos",component:Ri}),Mr="forge.qa.project",ji="mod-qa";function ba(){try{return localStorage.getItem(Mr)??""}catch{return""}}const Pi=({projects:e,preferred:n})=>{const a=Object.keys(e).sort(),r=d=>a.includes(d)?d:a[0]??"",[o,i]=b(()=>r(n||ba()));F(()=>{a.includes(o)||i(r(n||ba()))},[a.join(`
20
+ `),n]);const c=d=>{i(d);try{localStorage.setItem(Mr,d)}catch{}},s=Ti.component;return l("div",{class:"flex flex-col min-h-full",children:[t(Ve,{title:"QA",subtitle:"PRs que qa-pilot escaló a una persona, con la evidencia para decidir",children:a.length>0&&l("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:ji,projectId:null,cwProject:o},o)})]})},Et=e=>e.target.value,Ai=({accounts:e,onOpenSession:n,onFramesChanged:a})=>{const[r,o]=b(null),[i,c]=b(null),[s,d]=b(""),[x,h]=b(""),[y,v]=b(""),[S,w]=b(null),[k,p]=b(""),f=J(async()=>{try{const R=await(await fetch("/api/liveframe/frames")).json();c(R),a(R.length)}catch{c([])}},[a]);F(()=>{f(),fetch("/api/liveframe/status").then(R=>R.json()).then(o).catch(()=>{})},[f]);const m=async R=>{if(r)try{const j=await ge("/api/cw/start",{type:"general",account:r.account,directory:R.dir,task:`Liveframe: ${R.project}/${R.frame}`});n(j.session)}catch(j){I(pe(j),"error")}},u=async(R,j)=>{try{const z=await R;return I(j,"success"),f(),await m(z),!0}catch(z){return I(pe(z),"error"),!1}},T=async()=>{await u(ge("/api/liveframe/frames",{project:s,name:x}),`Frame "${x}" created`)&&h("")},g=async()=>{await u(ge("/api/liveframe/pull",{target:y}),`Pulled ${y}`)&&v("")},$=async()=>{if(S)try{const{url:R}=await ge(`/api/liveframe/frames/${S.project}/${S.frame}/push`,{note:k});I(`Published: ${R}`,"success"),w(null)}catch(R){I(pe(R),"error")}},A=r!==null&&!e.includes(r.account),N=(r==null?void 0:r.installed)!==!1&&!A,O=(i??[]).reduce((R,j)=>{var z;return(R[z=j.project]??(R[z]=[])).push(j),R},{});return l(G,{children:[l(Ve,{title:"Prototypes",subtitle:r?`Liveframe frames in ${r.root} · agents run on ${r.account}`:"Liveframe frames",children:[r&&l("a",{class:He,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(L,{label:"Refresh",variant:"secondary",onClick:f})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[r&&!r.installed&&l("p",{style:{...de,background:Z("--red")},children:["The Liveframe CLI is not installed. Run ",l("code",{children:["npm i -g ",r.api,"/cli.tgz"]}),", then ",t("code",{children:"lf login"}),"."]}),A&&l("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&&l("p",{style:{...de,background:Z("--orange")},children:["Liveframe is not signed in on this machine. Run ",t("code",{children:"lf login"})," in a terminal."]}),l("section",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(300px, 1fr))",gap:"14px"},children:[l("div",{class:"flex flex-col",style:{...Me,padding:"16px 18px",gap:"12px"},children:[l("div",{children:[t("h2",{style:{fontSize:"14.5px",fontWeight:600},children:"New prototype"}),l("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:R=>d(Et(R))})}),t(U,{label:"Frame name",children:t("input",{type:"text",class:"field",value:x,placeholder:"Checkout ideas",onInput:R=>h(Et(R))})}),t("div",{class:"flex justify-end",children:t(L,{label:"Create and open agent",variant:"primary",size:"sm",disabled:!N||!s.trim()||!x.trim(),onClick:T})})]}),l("div",{class:"flex flex-col",style:{...Me,padding:"16px 18px",gap:"12px"},children:[l("div",{children:[t("h2",{style:{fontSize:"14.5px",fontWeight:600},children:"Continue a frame"}),l("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:y,placeholder:"reservas/checkout-flow",onInput:R=>v(Et(R))})}),t("div",{class:"flex justify-end",children:t(L,{label:"Pull and open agent",variant:"secondary",size:"sm",disabled:!N||!y.includes("/"),onClick:g})})]})]}),i&&i.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(O).map(([R,j])=>l("section",{style:{...Me,overflow:"hidden"},children:[t("h2",{style:{padding:"12px 18px",fontSize:"13px",fontWeight:600,borderBottom:"1px solid var(--hair)"},children:R}),j.map(z=>l("div",{class:"flex items-center flex-wrap",style:{gap:"10px",padding:"12px 18px",borderBottom:"1px solid var(--hair)"},children:[l("div",{class:"min-w-0",style:{flex:"1 1 220px"},children:[t("p",{class:"truncate",style:{fontSize:"13.5px",fontWeight:500},children:z.frame}),l("p",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-3)"},children:[z.kind," · ",z.branch," · ",z.dir]})]}),l("a",{class:He,style:Ie,href:z.url,target:"_blank",rel:"noopener noreferrer",children:["Live ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),t(L,{label:"Push",variant:"secondary",size:"sm",disabled:!N,onClick:()=>{p(""),w(z)}}),t(L,{label:"Open agent",variant:"primary",size:"sm",disabled:!r||A,onClick:()=>m(z)})]},z.dir))]},R))]}),t(Le,{open:S!==null,title:`Push ${S==null?void 0:S.project}/${S==null?void 0:S.frame}`,onClose:()=>w(null),children:l("div",{class:"space-y-4",children:[l("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:k,placeholder:"wallet-first layout",onInput:R=>p(Et(R))})}),t("div",{class:"flex justify-end pt-1",children:t(L,{label:"Push",variant:"primary",onClick:$})})]})})]})},Ii=[{id:"project",label:"Project"},{id:"team",label:"Team"},{id:"personal",label:"Personal"}],De="__new";async function en(e,n,a,r){try{await ge(e,n),I(a,"success"),Re(!0),r()}catch(o){I(pe(o),"error")}}const Mn=e=>{var n;return(((n=ye.value)==null?void 0:n.brains)??[]).filter(a=>a.onDisk&&e.includes(a.tier??""))},Fr=()=>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."}),Li=({onClose:e})=>{const[n,a]=b(""),[r,o]=b("project"),[i,c]=b(""),[s,d]=b(""),x=Mn(["team"]);return l(qe,{title:"New brain",onClose:e,children:[t("div",{class:"flex",children:t(le,{size:"sm",label:"Tier",tabs:Ii,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:h=>a(ne(h))})}),r==="project"&&x.length>0&&t(Fn,{label:"Team brain",brains:x,value:i,onValue:c}),t(U,{label:"Language of its pages · optional",children:t("input",{type:"text",class:"field",value:s,placeholder:"en",onInput:h=>d(ne(h))})}),t(Fr,{}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(L,{label:"Cancel",variant:"secondary",onClick:e}),t(L,{label:"Create",variant:"primary",disabled:!n.trim(),onClick:()=>en("/api/kioku/brains",{repo:n,tier:r,team:i,language:s},`Made ${n.trim()}`,e)})]})]})},Fn=({label:e,brains:n,value:a,onValue:r,repo:o,placeholder:i,onRepo:c})=>l(G,{children:[t(U,{label:e,children:l("select",{class:"field",value:a,onChange:s=>r(ne(s)),children:[t("option",{value:"",children:"None"}),n.map(s=>t("option",{value:s.key,children:re(s)},s.key)),c&&t("option",{value:De,children:"New brain…"})]})}),c&&a===De&&t("input",{type:"text",class:"field",value:o,placeholder:i,onInput:s=>c(ne(s))})]}),Ei=({project:e,onClose:n})=>{const[a,r]=b(De),[o,i]=b(""),[c,s]=b(""),[d,x]=b(""),h=(v,S)=>v===De?S.trim():v,y={brain:h(a,o),team:h(c,d)};return l(qe,{title:`A brain for ${e}`,onClose:n,children:[t(Fn,{label:"Project brain",brains:Mn(["project","client"]),value:a,repo:o,placeholder:`monoku/brain-${e}`,onValue:r,onRepo:i}),t(Fn,{label:"Team brain",brains:Mn(["team"]),value:c,repo:d,placeholder:"monoku/brain",onValue:s,onRepo:x}),l("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(Fr,{}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(L,{label:"Cancel",variant:"secondary",onClick:n}),t(L,{label:"Link",variant:"primary",disabled:!y.brain&&!y.team,onClick:()=>en("/api/kioku/link",{project:e,...y},`Linked ${e}`,n)})]})]})},Br=({brain:e,onClose:n})=>{const[a,r]=b(""),[o,i]=b("");return t(Le,{open:!0,title:`New area in ${re(e)}`,onClose:n,children:l("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(ne(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=>i(ne(c))})}),e.namespaces.length>0&&l("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Areas now: ",e.namespaces.join(", ")]}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(L,{label:"Cancel",variant:"secondary",onClick:n}),t(L,{label:"Add area",variant:"primary",disabled:!a.trim()||!o.trim(),onClick:()=>en("/api/kioku/areas",{brain:e.key,area:a,summary:o},`Added ${a.trim()} to ${re(e)}`,n)})]})]})})},Ni=({brain:e,onClose:n})=>{const[a,r]=b(""),[o,i]=b(!1),c=re(e);return t(Le,{open:!0,title:`Publish ${c}`,onClose:n,children:l("div",{class:"flex flex-col",style:{gap:"12px"},children:[l("div",{style:{...de,background:Z("--red")},children:[l("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(ne(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.":l(G,{children:["Left empty, kioku makes a private GitHub repository for ",t("code",{children:e.key})," with ",t("code",{children:"gh"}),", unless it exists."]})}),l("label",{class:"flex items-start cursor-pointer",style:{gap:"8px",fontSize:"12.5px"},children:[t("input",{type:"checkbox",checked:o,onChange:s=>i(s.target.checked),style:{marginTop:"2px"}}),l("span",{children:["I have the approval this needs, or it needs none. Publishing ",c," is my decision."]})]}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(L,{label:"Cancel",variant:"secondary",onClick:n}),t(L,{label:"Publish",variant:"destructive",disabled:!o,onClick:()=>en("/api/kioku/publish",{brain:e.key,to:a,understood:o},`Published ${c}`,n)})]})]})})};function Oi(e,n){const r=(n?Yn(n):[]).find(o=>o.tier==="project"||o.tier==="client")??e.find(o=>o.personal)??e[0];return(r==null?void 0:r.key)??""}const Wi=({project:e,onClose:n})=>{var B;const a=(((B=ye.value)==null?void 0:B.brains)??[]).filter(P=>P.onDisk),[r,o]=b(()=>Oi(a,e)),[i,c]=b(jt[0].id),[s,d]=b(""),[x,h]=b(""),[y,v]=b(""),[S,w]=b({}),[k,p]=b(null),[f,m]=b(!1),[u,T]=b(!1),g=a.find(P=>P.key===r),$=(g==null?void 0:g.namespaces)??[],A=$.length===1?$[0]:s,N=jt.find(P=>P.id===i)??jt[0],O=N.sections.length===0,R=O?["Text"]:N.sections,j=!!(g&&A&&x.trim()&&y.trim()&&R.every(P=>{var D;return(D=S[P])==null?void 0:D.trim()})),z=async(P=!1)=>{if(!g||!j||f)return;m(!0);const D=O?`${(S.Text??"").trim()}
21
21
  `:N.sections.map(M=>`## ${M}
22
22
 
23
23
  ${(S[M]??"").trim()}
24
24
  `).join(`
25
- `);try{const M=await ge("/api/kioku/pages",{brain:g.key,type:i,title:x,summary:b,body:W,namespace:L,create:j});M.status==="similar"?u(M.similar):M.status==="namespace"?P(`Pick an area of ${re(g)}`,"error"):(P(`Saved to ${M.brain}: ${M.path}`,"success"),Re(!0),n())}catch(M){P(pe(M),"error")}finally{v(!1)}};return l(qe,{title:"New memory",onClose:n,children:[t(U,{label:"Brain",children:t("select",{class:"field",value:r,onChange:j=>{o(ne(j)),d(""),u(null)},children:a.map(j=>l("option",{value:j.key,children:[re(j)," · ",j.tier]},j.key))})}),g&&A.length===0&&l("div",{class:"flex items-center",style:{...de,gap:"12px",background:Z("--orange")},children:[l("span",{class:"flex-1",children:[re(g)," has no areas yet. Each page goes in one, and a person names them."]}),t(I,{label:"Add area",variant:"secondary",size:"sm",onClick:()=>z(!0)})]}),A.length>1&&t(U,{label:"Area",children:l("select",{class:"field",value:s,onChange:j=>d(ne(j)),children:[t("option",{value:"",children:"Choose…"}),A.map(j=>t("option",{value:j,children:j},j))]})}),t("div",{class:"flex",children:t(se,{size:"sm",label:"Page type",tabs:Tt.map(j=>({id:j.id,label:j.label})),active:i,onChange:j=>{c(j),u(null)}})}),t(U,{label:"Title",children:t("input",{type:"text",class:"field",value:x,placeholder:"Payments retry at most three times",onInput:j=>{f(ne(j)),u(null)}})}),t(U,{label:"Summary · one line the agent reads first",children:t("input",{type:"text",class:"field",value:b,onInput:j=>m(ne(j))})}),R.map(j=>t(U,{label:j,children:t("textarea",{class:"field",rows:j==="Text"?8:3,value:S[j]??"",onInput:W=>k(M=>({...M,[j]:ne(W)}))})},`${i}:${j}`)),w&&l("div",{style:{...de,background:Z("--orange")},children:[l("p",{style:{fontWeight:600,marginBottom:"6px"},children:[g?re(g):"The brain"," already has pages on this:"]}),t("ul",{class:"flex flex-col",style:{gap:"4px",paddingLeft:"16px",listStyle:"disc"},children:w.map(j=>l("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."})]}),(g==null?void 0:g.remote)&&l("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Kioku commits to ",re(g),"'s main branch and pushes it; it has no review step."]}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:w?"Save anyway":"Save",variant:"primary",disabled:!T||h,onClick:()=>$(w!==null)})]}),p&&g&&t(Br,{brain:g,onClose:()=>z(!1)})]})},Ni=[{label:"Personal",tiers:["personal"]},{label:"Projects",tiers:["project","client"]},{label:"Team",tiers:["team"]}],Oi={save:"--green",update:"--blue",supersede:"--blue",evolve:"--purple",link:"--teal",confirm:"--green",retire:"--red",forget:"--red"},Di=({brain:e})=>{const n=Object.entries(e.kinds).filter(([,a])=>a>0).sort((a,r)=>r[1]-a[1]);return l(V,{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(${la(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])=>l("span",{class:"inline-flex items-center",style:{gap:"4px"},children:[t($e,{color:`var(${la(a)})`}),a," ",r]},a))})]})},ka={fontSize:"11.5px",fontWeight:500,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},wa=({brain:e,usedBy:n,showTier:a,onDialog:r})=>{const o=_e(e.tier);return l("div",{class:"flex flex-col min-w-0",style:{...Me,gap:"9px",padding:"14px 16px",borderTop:`3px solid var(${o})`},children:[l("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:re(e)}),t("span",{class:"flex-1"}),t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:e.onDisk?e.touched?Yt(e.touched):"quiet":"not on disk"})]}),l("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(Di,{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(i=>t(Aa,{label:i,variant:"neutral"},i))}),e.onDisk&&l("div",{class:"flex items-center",style:{gap:"12px",paddingTop:"8px",marginTop:"auto",borderTop:"1px solid var(--hair)"},children:[t("button",{type:"button",style:ka,onClick:()=>r({kind:"area",brain:e}),children:"+ Area"}),t("span",{class:"flex-1"}),!e.remote&&l(V,{children:[t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"only on this machine"}),t("button",{type:"button",style:ka,onClick:()=>r({kind:"publish",brain:e}),children:"Publish…"})]})]})]})},Wi=({writes:e})=>l("section",{style:{...Me,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=>l("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(Aa,{label:n.verb,color:`var(${Oi[n.verb]??"--ink-2"})`})}),t("span",{class:"truncate flex-1",title:n.path,children:n.title}),l("span",{class:"shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[n.brain,n.author?` · ${n.author}`:""," · ",Yt(n.date)]})]},`${n.brain}:${n.path}:${n.date}:${n.verb}`))]}),Mi=({project:e,onProject:n})=>{const[a,r]=y(!1),[o,i]=y(null),c=()=>i(null);F(()=>ur(),[]);const s=ye.value,d=async()=>{const v=window.open("","_blank");r(!0);try{const{address:p}=await ge("/api/kioku/viewer",{});v?v.location.href=p:P(`Viewer running at ${p}`,"info"),Re()}catch(p){v==null||v.close(),P(pe(p),"error")}finally{r(!1)}},x=async()=>{await fetch("/api/kioku/viewer",{method:"DELETE"}).catch(()=>{}),Re()},f=(s==null?void 0:s.brains)??[],b=(s==null?void 0:s.projects)??{},m=Object.keys(b).filter(v=>b[v].some(p=>p.tier!=="personal")).sort();e&&!m.includes(e)&&m.unshift(e);const S=e?Yn(e):[],k=v=>Object.keys(b).filter(p=>b[p].some(z=>z.name===re(v))).sort(),w=new Set(S.map(re)),u=((s==null?void 0:s.activity)??[]).filter(v=>!e||w.has(v.brain)).slice(0,15),h=s!=null&&s.installed?e?`${e} · ${Ht(S)} pages its sessions can recall`:`Kioku ${s.version??""} · ${Ht(f)} pages in ${f.length} brain${f.length===1?"":"s"}`:"Kioku brains on this machine";return l(V,{children:[l(Ve,{title:"Memory",subtitle:h,children:[(s==null?void 0:s.viewer)&&t(I,{label:"Stop viewer",variant:"secondary",onClick:x}),t(I,{label:"Refresh",variant:"secondary",onClick:()=>Re(!0)}),t(I,{label:"New brain",variant:"secondary",disabled:!(s!=null&&s.installed),onClick:()=>i({kind:"brain"})}),t(I,{label:"New memory",variant:"secondary",disabled:!f.some(v=>v.onDisk),onClick:()=>i({kind:"memory"})}),t(I,{label:s!=null&&s.viewer?"Viewer open ↗":"Open viewer",variant:"primary",disabled:!(s!=null&&s.installed)||a,onClick:d})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[s&&!s.installed&&l("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)&&f.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."}),f.length>0&&m.length>0&&t("div",{class:"flex",children:t(se,{size:"sm",label:"Project",tabs:[{id:"",label:"All"},...m.map(v=>({id:v,label:v}))],active:e??"",onChange:v=>n(v||null)})}),f.length>0&&!e&&t("div",{class:"flex flex-wrap",style:{gap:"14px 12px"},children:Ni.map(v=>{const p=f.filter(z=>v.tiers.includes(z.tier??""));return p.length===0?null:l("section",{class:"flex flex-col min-w-0",style:{gap:"8px",flex:`${p.length} 1 ${p.length*250}px`},children:[l("h2",{class:"flex items-center",style:{gap:"8px",fontSize:"11px",fontWeight:600,letterSpacing:".03em",color:`var(${_e(v.tiers[0])})`},children:["● ",v.label.toUpperCase(),p.length>1&&t("span",{style:{color:"var(--ink-3)"},children:p.length})]}),t("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:"12px"},children:p.map(z=>t(wa,{brain:z,usedBy:k(z),onDialog:i},z.key))})]},v.label)})}),e&&S.length>0&&t("div",{class:"grid items-center",style:{gridTemplateColumns:S.map(()=>"minmax(0, 1fr)").join(" 24px ")},children:S.map((v,p)=>l(Hr,{children:[p>0&&t("span",{style:{textAlign:"center",color:"var(--ink-3)",fontSize:"16px"},children:"→"}),t(wa,{brain:v,showTier:!0,onDialog:i})]},v.key))}),e&&(s==null?void 0:s.installed)&&!S.some(v=>v.tier!=="personal")&&l("div",{class:"flex items-center",style:{...de,gap:"12px",background:"var(--elev)",color:"var(--ink-2)"},children:[l("span",{class:"flex-1",children:[e," has no project or team brain, so its sessions recall only yours."]}),t(I,{label:"Give it a brain",variant:"secondary",size:"sm",onClick:()=>i({kind:"link"})})]}),f.length>0&&t(Wi,{writes:u}),(s==null?void 0:s.installed)&&l("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(Li,{project:e,onClose:c}),(o==null?void 0:o.kind)==="brain"&&t(Pi,{onClose:c}),(o==null?void 0:o.kind)==="link"&&e&&t(Ai,{project:e,onClose:c}),(o==null?void 0:o.kind)==="area"&&t(Br,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="publish"&&t(Ii,{brain:o.brain,onClose:c})]})},xt=Y(null);function Fi(e,n){var a;return(a=xt.value)==null||a.resolve(!1),new Promise(r=>{xt.value={confirmation:e,module:n,resolve:r}})}const xn=e=>{const n=xt.value;xt.value=null,n==null||n.resolve(e)},Bi=()=>{var a;const e=xt.value;if(!e)return null;const{confirmation:n}=e;return l(Ee,{open:!0,title:n.title,onClose:()=>xn(!1),footer:l(V,{children:[l("span",{class:"flex-1",style:{fontSize:"12px",color:"var(--ink-3)"},children:[e.module," asks for this"]}),t(I,{label:"Cancel",variant:"secondary",onClick:()=>xn(!1)}),t(I,{label:n.confirmLabel,variant:"destructive",onClick:()=>xn(!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)=>l("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))})]})},Lt=e=>`/api/modules/${encodeURIComponent(e)}`;async function mn(e){const n=await e.json().catch(()=>({}));throw new _t(n.code??`http_${e.status}`,n.message??n.error??`Request failed (${e.status})`)}const Sa=(e,n)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});async function _i(e,n){var i,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(`
25
+ `);try{const M=await ge("/api/kioku/pages",{brain:g.key,type:i,title:x,summary:y,body:D,namespace:A,create:P});M.status==="similar"?p(M.similar):M.status==="namespace"?I(`Pick an area of ${re(g)}`,"error"):(I(`Saved to ${M.brain}: ${M.path}`,"success"),Re(!0),n())}catch(M){I(pe(M),"error")}finally{m(!1)}};return l(qe,{title:"New memory",onClose:n,children:[t(U,{label:"Brain",children:t("select",{class:"field",value:r,onChange:P=>{o(ne(P)),d(""),p(null)},children:a.map(P=>l("option",{value:P.key,children:[re(P)," · ",P.tier]},P.key))})}),g&&$.length===0&&l("div",{class:"flex items-center",style:{...de,gap:"12px",background:Z("--orange")},children:[l("span",{class:"flex-1",children:[re(g)," has no areas yet. Each page goes in one, and a person names them."]}),t(L,{label:"Add area",variant:"secondary",size:"sm",onClick:()=>T(!0)})]}),$.length>1&&t(U,{label:"Area",children:l("select",{class:"field",value:s,onChange:P=>d(ne(P)),children:[t("option",{value:"",children:"Choose…"}),$.map(P=>t("option",{value:P,children:P},P))]})}),t("div",{class:"flex",children:t(le,{size:"sm",label:"Page type",tabs:jt.map(P=>({id:P.id,label:P.label})),active:i,onChange:P=>{c(P),p(null)}})}),t(U,{label:"Title",children:t("input",{type:"text",class:"field",value:x,placeholder:"Payments retry at most three times",onInput:P=>{h(ne(P)),p(null)}})}),t(U,{label:"Summary · one line the agent reads first",children:t("input",{type:"text",class:"field",value:y,onInput:P=>v(ne(P))})}),R.map(P=>t(U,{label:P,children:t("textarea",{class:"field",rows:P==="Text"?8:3,value:S[P]??"",onInput:D=>w(M=>({...M,[P]:ne(D)}))})},`${i}:${P}`)),k&&l("div",{style:{...de,background:Z("--orange")},children:[l("p",{style:{fontWeight:600,marginBottom:"6px"},children:[g?re(g):"The brain"," already has pages on this:"]}),t("ul",{class:"flex flex-col",style:{gap:"4px",paddingLeft:"16px",listStyle:"disc"},children:k.map(P=>l("li",{children:[t("b",{children:P.title}),P.summary?` — ${P.summary}`:""]},P.path))}),t("p",{style:{marginTop:"6px",color:"var(--ink-2)"},children:"Save it anyway to keep both; kioku links them under See also."})]}),(g==null?void 0:g.remote)&&l("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Kioku commits to ",re(g),"'s main branch and pushes it; it has no review step."]}),l("div",{class:"flex justify-end",style:{gap:"8px"},children:[t(L,{label:"Cancel",variant:"secondary",onClick:n}),t(L,{label:k?"Save anyway":"Save",variant:"primary",disabled:!j||f,onClick:()=>z(k!==null)})]}),u&&g&&t(Br,{brain:g,onClose:()=>T(!1)})]})},Di=[{label:"Personal",tiers:["personal"]},{label:"Projects",tiers:["project","client"]},{label:"Team",tiers:["team"]}],Mi={save:"--green",update:"--blue",supersede:"--blue",evolve:"--purple",link:"--teal",confirm:"--green",retire:"--red",forget:"--red"},Fi=({brain:e})=>{const n=Object.entries(e.kinds).filter(([,a])=>a>0).sort((a,r)=>r[1]-a[1]);return l(G,{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(${la(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])=>l("span",{class:"inline-flex items-center",style:{gap:"4px"},children:[t($e,{color:`var(${la(a)})`}),a," ",r]},a))})]})},ka={fontSize:"11.5px",fontWeight:500,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},wa=({brain:e,usedBy:n,showTier:a,onDialog:r})=>{const o=_e(e.tier);return l("div",{class:"flex flex-col min-w-0",style:{...Me,gap:"9px",padding:"14px 16px",borderTop:`3px solid var(${o})`},children:[l("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:re(e)}),t("span",{class:"flex-1"}),t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:e.onDisk?e.touched?Yt(e.touched):"quiet":"not on disk"})]}),l("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(Fi,{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(i=>t(Aa,{label:i,variant:"neutral"},i))}),e.onDisk&&l("div",{class:"flex items-center",style:{gap:"12px",paddingTop:"8px",marginTop:"auto",borderTop:"1px solid var(--hair)"},children:[t("button",{type:"button",style:ka,onClick:()=>r({kind:"area",brain:e}),children:"+ Area"}),t("span",{class:"flex-1"}),!e.remote&&l(G,{children:[t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"only on this machine"}),t("button",{type:"button",style:ka,onClick:()=>r({kind:"publish",brain:e}),children:"Publish…"})]})]})]})},Bi=({writes:e})=>l("section",{style:{...Me,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=>l("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(Aa,{label:n.verb,color:`var(${Mi[n.verb]??"--ink-2"})`})}),t("span",{class:"truncate flex-1",title:n.path,children:n.title}),l("span",{class:"shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[n.brain,n.author?` · ${n.author}`:""," · ",Yt(n.date)]})]},`${n.brain}:${n.path}:${n.date}:${n.verb}`))]}),_i=({project:e,onProject:n})=>{const[a,r]=b(!1),[o,i]=b(null),c=()=>i(null);F(()=>ur(),[]);const s=ye.value,d=async()=>{const m=window.open("","_blank");r(!0);try{const{address:u}=await ge("/api/kioku/viewer",{});m?m.location.href=u:I(`Viewer running at ${u}`,"info"),Re()}catch(u){m==null||m.close(),I(pe(u),"error")}finally{r(!1)}},x=async()=>{await fetch("/api/kioku/viewer",{method:"DELETE"}).catch(()=>{}),Re()},h=(s==null?void 0:s.brains)??[],y=(s==null?void 0:s.projects)??{},v=Object.keys(y).filter(m=>y[m].some(u=>u.tier!=="personal")).sort();e&&!v.includes(e)&&v.unshift(e);const S=e?Yn(e):[],w=m=>Object.keys(y).filter(u=>y[u].some(T=>T.name===re(m))).sort(),k=new Set(S.map(re)),p=((s==null?void 0:s.activity)??[]).filter(m=>!e||k.has(m.brain)).slice(0,15),f=s!=null&&s.installed?e?`${e} · ${qt(S)} pages its sessions can recall`:`Kioku ${s.version??""} · ${qt(h)} pages in ${h.length} brain${h.length===1?"":"s"}`:"Kioku brains on this machine";return l(G,{children:[l(Ve,{title:"Memory",subtitle:f,children:[(s==null?void 0:s.viewer)&&t(L,{label:"Stop viewer",variant:"secondary",onClick:x}),t(L,{label:"Refresh",variant:"secondary",onClick:()=>Re(!0)}),t(L,{label:"New brain",variant:"secondary",disabled:!(s!=null&&s.installed),onClick:()=>i({kind:"brain"})}),t(L,{label:"New memory",variant:"secondary",disabled:!h.some(m=>m.onDisk),onClick:()=>i({kind:"memory"})}),t(L,{label:s!=null&&s.viewer?"Viewer open ↗":"Open viewer",variant:"primary",disabled:!(s!=null&&s.installed)||a,onClick:d})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[s&&!s.installed&&l("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)&&h.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."}),h.length>0&&v.length>0&&t("div",{class:"flex",children:t(le,{size:"sm",label:"Project",tabs:[{id:"",label:"All"},...v.map(m=>({id:m,label:m}))],active:e??"",onChange:m=>n(m||null)})}),h.length>0&&!e&&t("div",{class:"flex flex-wrap",style:{gap:"14px 12px"},children:Di.map(m=>{const u=h.filter(T=>m.tiers.includes(T.tier??""));return u.length===0?null:l("section",{class:"flex flex-col min-w-0",style:{gap:"8px",flex:`${u.length} 1 ${u.length*250}px`},children:[l("h2",{class:"flex items-center",style:{gap:"8px",fontSize:"11px",fontWeight:600,letterSpacing:".03em",color:`var(${_e(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(T=>t(wa,{brain:T,usedBy:w(T),onDialog:i},T.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)=>l(Hr,{children:[u>0&&t("span",{style:{textAlign:"center",color:"var(--ink-3)",fontSize:"16px"},children:"→"}),t(wa,{brain:m,showTier:!0,onDialog:i})]},m.key))}),e&&(s==null?void 0:s.installed)&&!S.some(m=>m.tier!=="personal")&&l("div",{class:"flex items-center",style:{...de,gap:"12px",background:"var(--elev)",color:"var(--ink-2)"},children:[l("span",{class:"flex-1",children:[e," has no project or team brain, so its sessions recall only yours."]}),t(L,{label:"Give it a brain",variant:"secondary",size:"sm",onClick:()=>i({kind:"link"})})]}),h.length>0&&t(Bi,{writes:p}),(s==null?void 0:s.installed)&&l("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(Wi,{project:e,onClose:c}),(o==null?void 0:o.kind)==="brain"&&t(Li,{onClose:c}),(o==null?void 0:o.kind)==="link"&&e&&t(Ei,{project:e,onClose:c}),(o==null?void 0:o.kind)==="area"&&t(Br,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="publish"&&t(Ni,{brain:o.brain,onClose:c})]})},mt=Y(null);function Ki(e,n){var a;return(a=mt.value)==null||a.resolve(!1),new Promise(r=>{mt.value={confirmation:e,module:n,resolve:r}})}const xn=e=>{const n=mt.value;mt.value=null,n==null||n.resolve(e)},Ui=()=>{var a;const e=mt.value;if(!e)return null;const{confirmation:n}=e;return l(Le,{open:!0,title:n.title,onClose:()=>xn(!1),footer:l(G,{children:[l("span",{class:"flex-1",style:{fontSize:"12px",color:"var(--ink-3)"},children:[e.module," asks for this"]}),t(L,{label:"Cancel",variant:"secondary",onClick:()=>xn(!1)}),t(L,{label:n.confirmLabel,variant:"destructive",onClick:()=>xn(!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)=>l("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))})]})},Nt=e=>`/api/modules/${encodeURIComponent(e)}`;async function mn(e){const n=await e.json().catch(()=>({}));throw new Kt(n.code??`http_${e.status}`,n.message??n.error??`Request failed (${e.status})`)}const Sa=(e,n)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});async function Hi(e,n){var i,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
26
 
27
- `))>=0;){const f=o.slice(0,x);o=o.slice(x+2);const b=(i=/^event: (.*)$/m.exec(f))==null?void 0:i[1],m=JSON.parse(((c=/^data: (.*)$/m.exec(f))==null?void 0:c[1])??"null");if(b==="output"&&m.chunk&&n(m.chunk),b==="done")return m.result;if(b==="error")throw new _t(m.code??"module_error",m.message??"action failed")}}throw new _t("module_error","the action stream ended early")}function Ki(e,n,a){const r=Y({}),o=async()=>{const c=await fetch(`${Lt(e)}/settings`);c.ok&&(r.value=await c.json())};o();const i=async(c,s,d,x)=>{const f=`${Lt(e)}/actions/${encodeURIComponent(c)}${x?"/stream":""}`,b=await Sa(f,{input:s,token:d});return b.status===409?{needsConfirmation:!0}:b.ok?x?{result:await _i(b,x)}:{result:(await b.json()).result}:mn(b)};return{settings:r,status:ja(()=>be.value.find(c=>c.id===e)),openSettings:a,reloadSettings:o,async route(c,s){const d=await fetch(`${Lt(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():mn(d)},async action(c,s,d){var k,w,u;if(((u=(w=(k=be.value.find(h=>h.id===e))==null?void 0:k.actions)==null?void 0:w.find(h=>h.id===c))==null?void 0:u.effect)!=="external"){const h=await i(c,s,void 0,d==null?void 0:d.onOutput);if(!("needsConfirmation"in h))return h.result}const f=await Sa(`${Lt(e)}/actions/${encodeURIComponent(c)}/prepare`,{input:s});if(!f.ok)return mn(f);const{confirmation:b,token:m}=await f.json();if(!await Fi(b,n()))return;const S=await i(c,s,m,d==null?void 0:d.onOutput);if("needsConfirmation"in S)throw new _t("confirmation_required","The confirmation expired; try again");return S.result}}}const Bn=({value:e,onChange:n,initialPath:a,requireGit:r=!0})=>{const[o,i]=y(a??"~"),[c,s]=y(o),[d,x]=y([]),[f,b]=y(null),[m,S]=y(null),[k,w]=y(""),[u,h]=y(!1),[v,p]=y(!1),[z,g]=y(null);F(()=>{let j=!1;return(async()=>{p(!0),g(null);try{const H=await(await fetch(`/api/cw/browse-dirs?path=${encodeURIComponent(o)}`)).json();if(j)return;if(!H.ok){g(H.error??"Failed to load directory"),x([]);return}x(H.entries??[]),b(H.parent??null),S(H.home??null),w(H.path??o),h(!!H.isGitRepo)}catch{j||(g("Network error"),x([]))}finally{j||p(!1)}})(),()=>{j=!0}},[o]);const A=j=>{i(j),s(j)},L=e===k,N=r&&!u,O=k?m&&k===m?"~":m&&k.startsWith(m+"/")?"~"+k.slice(m.length):k:o,R={width:"24px",height:"24px",borderRadius:"7px",border:0,background:"var(--card)",color:"var(--ink-2)",boxShadow:"var(--shadow-s)"},T="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 l("div",{style:{borderRadius:"12px",border:"1px solid var(--hair)",background:"var(--card)",boxShadow:"var(--shadow-s)",overflow:"hidden"},children:[l("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:R,onClick:()=>f&&A(f),disabled:!f||v,title:"Parent folder","aria-label":"Parent folder",children:"←"}),t("button",{type:"button",class:"grid place-items-center cursor-pointer",style:R,onClick:()=>A("~"),title:"Home","aria-label":"Home",children:"~"}),t("input",{type:"text",value:c,"aria-label":"Path",onInput:j=>s(j.target.value),onBlur:()=>i(c),onKeyDown:j=>{j.key==="Enter"&&i(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&&l("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:v?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}):l(V,{children:[l("button",{type:"button",class:T,style:{...$,background:L?"var(--elev)":"none",fontWeight:600},onClick:()=>n(k,u),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)"}}),l("span",{class:"flex-1 truncate",children:["Pick ",t("span",{class:"mono",children:O})]}),u?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=>l("button",{type:"button",class:T,style:$,onClick:()=>A(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))]})})]})},_r={fontSize:"11.5px",color:"var(--red)"},Ca=e=>e.type==="boolean"||e.type==="string"&&e.format==="path",$a=({def:e,value:n,projects:a,onChange:r})=>e.type==="boolean"?t(Kn,{checked:n===!0,onChange:r,label:e.label}):e.type==="enum"?t("select",{class:"field",value:typeof n=="string"?n:"",onChange:o=>r(ne(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 i=ne(o);r(i===""?void 0:Number(i))}}):e.format==="cw-project"?l("select",{class:"field",value:typeof n=="string"?n:"",onChange:o=>r(ne(o)||void 0),children:[t("option",{value:"",children:"None"}),a.map(o=>t("option",{value:o,children:o},o))]}):e.format==="path"?t(Bn,{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(ne(o))}),za=({def:e,error:n,plain:a,children:r})=>l(U,{plain:a,label:l(V,{children:[e.label??"",e.required?" *":""]}),children:[r,e.help&&t("span",{style:me,children:e.help}),n&&t("span",{style:_r,children:n})]}),Ui=({moduleId:e,displayName:n,schema:a,onClose:r,onSaved:o})=>{const[i,c]=y(null),[s,d]=y({}),[x,f]=y([]),[b,m]=y(!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=>f(Object.keys(h))).catch(()=>{})},[S]);const k=(h,v)=>c(p=>({...p,[h]:v})),w=(h,v,p,z)=>c(g=>{const A=[...(g==null?void 0:g[h])??[]];return A[v]={...A[v],[p]:z},{...g,[h]:A}}),u=async()=>{m(!0);try{const h=await fetch(S,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(h.status===400){const{errors:v}=await h.json();d(Object.fromEntries(v.map(p=>[p.path,p.message])));return}if(!h.ok)throw new Error(`Saving failed (${h.status})`);d({}),P(`${n} settings saved`,"success"),o(),r()}catch(h){P(pe(h),"error")}finally{m(!1)}};return t(qe,{title:`${n} settings`,onClose:r,children:i?l("div",{class:"flex flex-col",style:{gap:"14px"},children:[Object.entries(a).map(([h,v])=>{if(v.type!=="list")return t(za,{def:{...v,label:v.label??h},error:s[h],plain:Ca(v),children:t($a,{def:v,value:i[h],projects:x,onChange:z=>k(h,z)})},h);const p=i[h]??[];return l("div",{class:"flex flex-col",style:{gap:"10px"},children:[t("span",{style:{...me,fontWeight:600},children:v.label??h}),v.help&&t("span",{style:me,children:v.help}),s[h]&&t("span",{style:_r,children:s[h]}),p.map((z,g)=>l("div",{class:"flex flex-col",style:{gap:"10px",padding:"12px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},children:[Object.entries(v.item).map(([A,L])=>t(za,{def:{...L,label:L.label??A},error:s[`${h}[${g}].${A}`],plain:Ca(L),children:t($a,{def:L,value:z[A],projects:x,onChange:N=>w(h,g,A,N)})},A)),t("div",{children:t(I,{label:"Remove",variant:"danger",size:"sm",onClick:()=>c(A=>({...A,[h]:p.filter((L,N)=>N!==g)}))})})]},g)),t("div",{children:t(I,{label:`Add ${(v.label??h).replace(/s$/,"").toLowerCase()}`,icon:"i-lucide-plus",variant:"secondary",size:"sm",onClick:()=>k(h,[...p,{}])})})]},h)}),l("div",{class:"flex",style:{gap:"8px",marginTop:"6px"},children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:r}),t(I,{label:"Save",loading:b,onClick:u})]})]}):t("div",{class:"text-ink2",style:{fontSize:"13px"},children:"Loading…"})})};class Hi extends qr{constructor(){super(...arguments);aa(this,"state",{error:null})}componentDidCatch(a){this.setState({error:a})}render(){const{error:a}=this.state;return a?t(_n,{title:`${this.props.name}'s view crashed`,message:a.message,onReload:()=>{this.setState({error:null}),this.props.onReload()}}):this.props.children}}const _n=({title:e,message:n,onReload:a})=>l("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(I,{label:"Reload view",variant:"secondary",size:"sm",onClick:a})})]}),qi=({status:e,onClose:n,onRemoved:a})=>{const[r,o]=y(!1),i=async()=>{o(!0);try{be.value=await pr("DELETE",`/api/modules/${encodeURIComponent(e.id)}`),P(`Removed ${e.displayName}`,"success"),a()}catch(c){P(pe(c),"error"),o(!1)}};return t(Ee,{open:!0,title:`Remove ${e.displayName}?`,onClose:n,footer:l(V,{children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:"Remove",variant:"destructive",loading:r,onClick:i})]}),children:l("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:["Forge uninstalls ",t("span",{class:"mono",children:e.name})," and stops it now. Its settings stay saved, so installing it again brings them back."]})})},vn=new Map;function Gi(e){const n=`${e.view.url}?v=${encodeURIComponent(e.view.version)}`;let a=vn.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(()=>vn.delete(n)),vn.set(n,a)),a}const Vi=({moduleId:e,cwProject:n,onBack:a})=>{var g,A,L,N;const r=be.value.find(O=>O.id===e),[o,i]=y(!1),[c,s]=y(!1),[d,x]=y(null),[f,b]=y(0),m=oe(e);r&&(m.current=r.displayName);const S=m.current,k=ee(()=>Ki(e,()=>m.current,()=>i(!0)),[e]),w=(r==null?void 0:r.state)==="enabled"?(g=r.view)==null?void 0:g.version:void 0,u=((A=er.value[e])==null?void 0:A.attention)??0;F(()=>{u>0&&Eo(e)},[e,u]),F(()=>{if(!r||!w)return;let O=!0;return Gi(r).then(R=>{O&&x({version:w,config:R})},R=>{O&&x({version:w,error:R.message})}),()=>{O=!1}},[e,w,f]);const h=r?Xa(r):null,v=l(Ve,{title:((L=r==null?void 0:r.view)==null?void 0:L.title)??S,subtitle:r?`${r.name} ${r.version}`:void 0,children:[h&&l("span",{class:"mono truncate",title:h,style:{maxWidth:"320px",fontSize:"11.5px",color:"var(--orange)"},children:["⚠ ",h]}),(r==null?void 0:r.settingsSchema)&&Object.keys(r.settingsSchema).length>0&&t(I,{label:"Settings",icon:"i-lucide-settings",variant:"secondary",size:"sm",onClick:()=>i(!0)}),(r==null?void 0:r.removable)&&t(I,{label:"Remove",icon:"i-lucide-trash-2",variant:"secondary",size:"sm",onClick:()=>s(!0)}),c&&r&&t(qi,{status:r,onClose:()=>s(!1),onRemoved:a})]});if(!r)return l("div",{children:[v,t("div",{style:{padding:"56px 22px"},children:t(je,{icon:"i-lucide-package-x",title:`${S} was removed`,description:"The module is no longer installed.",action:{label:"Back to Tasks",onClick:a}})})]});if(r.state!=="enabled")return l("div",{children:[v,t(_n,{title:`${S} is disabled`,message:r.reason??"No reason given",onReload:()=>{ut()}})]});const p=d&&d.version===w?d:null,z=(N=p==null?void 0:p.config)==null?void 0:N.component;return l("div",{children:[v,p!=null&&p.error?t(_n,{title:`${S}'s view did not load`,message:p.error,onReload:()=>b(O=>O+1)}):z?t(Hi,{name:S,onReload:()=>b(O=>O+1),children:t(z,{moduleId:e,projectId:null,cwProject:n,forge:k})},`${w}-${f}`):l("div",{class:"py-20 text-center text-ink2",children:["Loading ",S,"…"]}),o&&r.settingsSchema&&t(Ui,{moduleId:e,displayName:S,schema:r.settingsSchema,onClose:()=>i(!1),onSaved:()=>{k.reloadSettings(),ut()}})]})},yn={padding:"12px 14px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},Ji=({onClose:e,onInstalled:n})=>{const[a,r]=y(""),[o,i]=y(null),[c,s]=y(null),[d,x]=y(null),f=async()=>{x("preview"),s(null);try{i(await ge("/api/modules/install/preview",{spec:a}))}catch(m){s(pe(m))}finally{x(null)}},b=async()=>{if(o){x("install"),s(null);try{const{status:m,modules:S}=await ge("/api/modules/install",{token:o.token});be.value=S,(m==null?void 0:m.state)==="disabled"?P(`Installed ${o.displayName}, but Forge disabled it: ${m.reason??""}`,"error"):P(`Installed ${o.displayName}`,"success"),m&&n(m),e()}catch(m){i(null),s(pe(m))}finally{x(null)}}};return l(qe,{title:"Add a module",onClose:e,children:[l("form",{class:"flex flex-col",style:{gap:"10px"},onSubmit:m=>{m.preventDefault(),a.trim()&&!d&&f()},children:[t(U,{label:"npm package, folder or git url",children:t("input",{class:"field mono",value:a,placeholder:"@scope/forge-mod-name",autoFocus:!0,spellcheck:!1,onInput:m=>{r(ne(m)),i(null)}})}),t("span",{style:me,children:"Forge reads the module's manifest first; none of its code runs until you install it."})]}),c&&t("div",{role:"alert",class:"mono",style:{...yn,fontSize:"12px",color:"var(--red)",whiteSpace:"pre-wrap",borderColor:"color-mix(in srgb, var(--red) 45%, var(--hair))"},children:c}),o&&l("div",{class:"flex flex-col",style:{gap:"12px"},children:[l("div",{style:yn,children:[t("div",{style:{fontSize:"15px",fontWeight:650},children:o.displayName}),l("div",{class:"mono",style:{marginTop:"2px",fontSize:"11.5px",color:"var(--ink-3)"},children:[o.name," ",o.version,o.kind==="legacy"?" · legacy module":""]}),o.description&&t("p",{style:{marginTop:"8px",fontSize:"13px",color:"var(--ink-2)"},children:o.description})]}),l("div",{class:"flex flex-col",style:{gap:"6px"},children:[t("span",{style:{...me,fontWeight:600},children:o.permissions.length?"It asks for":"It asks for no permissions"}),o.permissions.map((m,S)=>l("div",{class:"flex",style:{gap:"10px",fontSize:"12.5px"},children:[t("span",{class:"mono shrink-0",style:{width:"64px",color:"var(--ink-3)"},children:m.kind}),t("span",{class:"mono",style:{wordBreak:"break-all"},children:m.value})]},S))]}),t("p",{style:{...yn,fontSize:"12.5px",color:"var(--ink-2)",borderColor:"color-mix(in srgb, var(--orange) 45%, var(--hair))"},children:o.trustNote}),l("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)",wordBreak:"break-all"},children:["npm install ",o.spec]})]}),l("div",{class:"flex",style:{gap:"8px"},children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:e}),o?t(I,{label:`Install ${o.displayName}`,loading:d==="install",onClick:b}):t(I,{label:"Review",loading:d==="preview",disabled:!a.trim(),onClick:f})]})]})},Yi=({open:e,accounts:n,onClose:a,onCreated:r})=>{const[o,i]=y("create"),[c,s]=y(""),[d,x]=y(""),[f,b]=y(""),[m,S]=y(""),[k,w]=y(""),[u,h]=y(""),[v,p]=y(!1),[z,g]=y(""),[A,L]=y(!1);F(()=>{e&&n.length>0&&!c&&s(n[0])},[e,n]),F(()=>{e||(i("create"),x(""),b(""),S(""),w(""),h(""),p(!1),g(""),L(!1))},[e]);const N=c.trim().length>0&&d.trim().length>0&&m.trim().length>0,O=c.trim().length>0&&u.length>0&&v,R=async()=>{if(N){L(!0);try{const M=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:m.trim(),account:c.trim()||void 0,directory:f.trim()||void 0,model:k||void 0})})).json();M.ok?(P("Project creation started in terminal","success"),r(M.session)):P(M.error??"Failed to create project","error")}catch{P("Failed to create project","error")}finally{L(!1)}}},T=async()=>{if(O){L(!0);try{const M=await(await fetch("/api/cw/register-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:u,account:c.trim(),alias:z.trim()||void 0})})).json();M.ok?(P(`Project "${M.project}" registered`,"success"),r()):P(M.error??"Failed to register project","error")}catch{P("Failed to register project","error")}finally{L(!1)}}},$=o==="create";return t(Ee,{open:e,title:"Add a project",onClose:a,footer:l(V,{children:[t("span",{class:"mono flex-1 truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:$?"cw create":"cw project register"}),t(I,{label:"Cancel",variant:"secondary",onClick:a}),t(I,{label:$?A?"Creating…":"Create":A?"Registering…":"Register",variant:"primary",loading:A,disabled:!($?N:O),onClick:$?R:T})]}),children:l("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:W=>i(W)}),l("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:W=>s(W.target.value),children:n.map(W=>t("option",{value:W,children:W},W))}):t("input",{type:"text",class:"field",value:c,placeholder:"account-name",onInput:W=>s(W.target.value)})}),$?t(U,{label:"Project name",children:t("input",{type:"text",class:"field",value:d,placeholder:"my-new-project",onInput:W=>x(W.target.value)})}):t(U,{label:"Alias",children:t("input",{type:"text",class:"field",value:z,placeholder:"defaults to folder name",onInput:W=>g(W.target.value)})})]}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:me,children:$?"Parent folder · optional":"Repository · must contain .git"}),$?t(Bn,{value:f,onChange:b,requireGit:!1},"dir-create"):t(Bn,{value:u,onChange:(W,M)=>{h(W),p(M)}},"dir-existing")]}),$&&l(V,{children:[t(U,{label:"Description",children:t("textarea",{rows:2,class:"field",value:m,placeholder:"A SaaS platform for…",onInput:W=>S(W.target.value)})}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:me,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:k,onChange:w})]})]})]})})},Qi=(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"}},Zi=(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 i=[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,i].filter(Boolean));break}case"api_key":o.push(...[e.providerModel,"stored by cw"].filter(i=>!!i));break;case"connected":o.push(...[r.model,n].filter(i=>!!i)),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(" · ")},Oe=({token:e,label:n})=>l("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]}),Xi=({view:e,onConnect:n,onCancel:a})=>{switch(e.kind){case"connecting":return l("span",{class:"inline-flex items-center shrink-0",style:{gap:"8px"},children:[t(Oe,{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(Oe,{token:null,label:"Not installed"});case"error":return t(Oe,{token:"--red",label:"Error"});case"local":return t(Oe,{token:"--orange",label:"Local"});case"api_key":return t(Oe,{token:"--green",label:"API key"});case"connected":return t(Oe,{token:"--green",label:"Connected"});case"connect":return t(I,{label:"Connect",size:"sm",onClick:n})}},bn=({children:e})=>l("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})]}),kn=({warn:e,children:n})=>t("span",{style:{fontSize:"11.5px",color:e?"var(--orange)":"var(--ink-3)"},children:n}),es=({account:e,harness:n})=>{const a=ko(e,n);return!a||a.state==="not_connected"?null:a.state==="expired"?t(bn,{children:t(kn,{warn:!0,children:"Reconnect to see usage limits"})}):a.state==="error"?t(bn,{children:l(kn,{children:["Limits unavailable — ",a.detail??"the request failed"]})}):a.windows.length===0?null:l(bn,{children:[t(Pa,{bars:Wa(a.windows)}),a.stale&&l(kn,{children:["Last known values — ",a.detail??"the refresh failed"]})]})},ts=3e3,ns=({account:e,harness:n,canUseApiKey:a,onConnected:r,onClose:o})=>{const[i,c]=y(null),[s,d]=y(!1),[x,f]=y(0),[b,m]=y(""),[S,k]=y(!1),w=he(n).label,u=`/api/cw/accounts/${encodeURIComponent(e)}`,h=`${u}/login/${encodeURIComponent(n)}`,v=oe(!1),p=oe(!1);F(()=>{let L=!1,N=null;c(null),d(!1),v.current=!1,p.current=!1;const O=()=>{v.current||(v.current=!0,fetch(h,{method:"DELETE"}).catch(()=>{}),P(`${e} is connected to ${w}`,"success"),r())},R=async()=>{var W;const $=await fetch(h).catch(()=>null);if(!($!=null&&$.ok)||L)return;const{login:B}=await $.json();if(c(B),B.status!=="exited"||(p.current=!0,N&&(clearInterval(N),N=null),B.exitCode!==0))return;d(!0);const j=await ve(!0);L||(j.available&&((W=Pe(j.doctor,e,n))==null?void 0:W.status)==="connected"?O():d(!1))};fetch(`${u}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n})}).then($=>$.json()).then($=>{if(!L){if(!$.ok||!$.login){P($.error??"Could not start the login","error");return}c($.login),N=setInterval(R,ts)}}).catch(()=>P("Could not start the login","error"));const T=_o($=>{var B;return((B=Pe($,e,n))==null?void 0:B.status)==="connected"},{onDone:$=>{$&&O()}});return()=>{L=!0,N&&clearInterval(N),T(),p.current||fetch(h,{method:"DELETE"}).catch(()=>{})}},[e,n,x]);const z=()=>{fetch(h,{method:"DELETE"}).catch(()=>{}),o()},g=async()=>{const L=b.trim();if(L){k(!0);try{const O=await(await fetch(`${u}/api-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n,apiKey:L})})).json();O.ok?(m(""),P("API key saved","success"),ve(!0)):P(O.error??"Could not save the API key","error")}catch{P("Could not save the API key","error")}finally{k(!1)}}},A=(i==null?void 0:i.status)==="exited";return l("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:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[l("h3",{style:{fontSize:"14px",fontWeight:650},children:["Connect ",e," on ",w]}),t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:z})]}),!i&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Starting the login…"}),i&&!A&&l(V,{children:[l("div",{class:"flex flex-wrap items-center",style:{gap:"12px"},children:[i.url&&l("a",{href:i.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"}})]}),i.code&&l(V,{children:[t("span",{class:"mono",style:{fontSize:"19px",fontWeight:650,letterSpacing:".12em"},children:i.code}),t(I,{label:"Copy",variant:"secondary",size:"sm",onClick:()=>Jn(i.code??"","Code")})]})]}),i.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:i.url||i.code?"Checks every 3 s. The status turns Connected on its own.":"Waiting for the login URL…"})]}),A&&s&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Checking the connection…"}),A&&!s&&l("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(I,{label:"Retry",variant:"secondary",size:"sm",onClick:()=>f(L=>L+1)})]}),i&&i.output.length>0&&l("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:i.output.join(`
28
- `)})]}),a&&l("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"}),l("div",{class:"flex items-center",style:{gap:"8px"},children:[t("input",{type:"password",autocomplete:"off","aria-label":"API key",value:b,onInput:L=>m(L.target.value),placeholder:"sk-…",class:"field mono flex-1 min-w-0"}),t(I,{label:"Save",variant:"secondary",size:"sm",loading:S,disabled:!b.trim(),onClick:g})]}),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"},as=({response:e,onCancel:n,onCreated:a})=>{const[r,o]=y(""),[i,c]=y(""),[s,d]=y(""),[x,f]=y(""),[b,m]=y(!1),S=yt(),k=r.trim(),w=io.test(k),u=e!=null&&e.available?e.doctor.harnesses.map(p=>p.name).filter(p=>p!=="claude"):[],h=!!i&&Fe(e,i,"custom_provider"),v=async()=>{if(!(!w||b)){m(!0);try{const z=await(await fetch("/api/cw/accounts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:k,harness:i||void 0,provider:h&&s.trim()||void 0,model:h&&x.trim()||void 0})})).json();z.ok?(P(`Account "${k}" created`,"success"),a()):P(z.error??"Failed to create account","error")}catch{P("Failed to create account","error")}finally{m(!1)}}};return l("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"}),l("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:p=>o(p.target.value),onKeyDown:p=>{p.key==="Enter"&&v()},placeholder:"my-account",class:"field",ref:S}),k&&!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."})]}),u.length>0&&l("div",{children:[t("span",{style:Nt,children:"Default harness"}),t(se,{label:"Default harness",tabs:[{id:"",label:"Claude Code"},...u.map(p=>({id:p,label:he(p).label}))],active:i,onChange:c}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)",marginTop:"5px"},children:"The default harness cannot be changed later."})]}),h&&l("div",{class:"grid",style:{gridTemplateColumns:"1fr 1fr",gap:"10px",maxWidth:"520px"},children:[l("div",{children:[t("label",{style:Nt,children:"Provider · optional"}),t("input",{type:"text",value:s,onInput:p=>d(p.target.value),placeholder:"zai, ollama, openrouter",class:"field"})]}),l("div",{children:[t("label",{style:Nt,children:"Model · optional"}),t("input",{type:"text",value:x,onInput:p=>f(p.target.value),placeholder:"glm-5.1",class:"field"})]})]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:b?"Creating…":"Add account",variant:"primary",loading:b,disabled:!w,onClick:v}),t(I,{label:"Cancel",variant:"secondary",onClick:n})]})]})},rs=new Set(["localhost","127.0.0.1","::1","[::1]"]),Ra={...Me,overflow:"hidden"},os=({account:e,onRemoved:n})=>{const[a,r]=y(!1),o=async()=>{try{const c=await(await fetch(`/api/cw/accounts/${encodeURIComponent(e)}`,{method:"DELETE"})).json();c.ok?(P(`Account "${e}" removed`,"info"),n()):P(c.error??"Failed to remove account","error")}catch{P("Failed to remove account","error")}finally{r(!1)}};return a?l("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(I,{label:"Remove account",variant:"destructive",size:"sm",onClick:o}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>r(!1)})]}):t(I,{label:"Remove",variant:"danger",size:"sm",onClick:()=>r(!0)})},ls=({projects:e,onOpenSession:n,onAccountsChanged:a})=>{const[r,o]=y(null),[i,c]=y(!1);F(()=>{ve()},[]),F(()=>Ga(),[]);const s=Zt.value,d=!rs.has(window.location.hostname),x=s!=null&&s.available?s.doctor:null,f=()=>{r&&(fetch(`/api/cw/accounts/${encodeURIComponent(r.account)}/login/${encodeURIComponent(r.harness)}`,{method:"DELETE"}).catch(()=>{}),o(null))},b=async(u,h)=>{if(Fe(s,h,"headless_login")){o({account:u,harness:h});return}try{const p=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"login",account:u,harness:h})})).json();p.ok&&p.session?n(p.session):P(p.error??"Could not open the login","error")}catch{P("Could not open the login","error")}},m=x?x.accounts.reduce((u,h)=>u+h.harnesses.filter(v=>v.status==="not_logged_in").length,0):0,S=x?`${x.accounts.length} account${x.accounts.length===1?"":"s"} · ${x.harnesses.length} harnesses · ${m} need${m===1?"s":""} connecting`:"Reading cw doctor…",k=u=>Object.values(e).filter(h=>h.account===u).length,w=(u,h)=>{if(!x)return null;const[v,p]=La(h),z=k(u.name),g=Pe(x,u.name,u.default_harness),A=[he(u.default_harness).label,g&&g.provider!=="native"?g.provider:null].filter(Boolean).join(" · ");return l("section",{style:{...Ra,animation:`riseIn .36s var(--ease) ${h*90}ms both`},"aria-label":u.name,children:[l("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(${v}), var(${p}))`,boxShadow:"var(--shadow-s)",color:"#fff",fontSize:"12px",fontWeight:700},children:u.name.charAt(0).toUpperCase()}),t("span",{style:{fontSize:"15px",fontWeight:650,letterSpacing:"-0.01em"},children:u.name}),l("span",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Default ",A," · ",z," project",z===1?"":"s"]}),t("span",{class:"flex-1"}),t(os,{account:u.name,onRemoved:()=>{ve(!0),a()}})]}),x.harnesses.map(L=>{const N=Pe(x,u.name,L.name),O=(r==null?void 0:r.account)===u.name&&r.harness===L.name,R=he(L.name),T=N?Qi(N,O):null;return l("div",{style:{borderBottom:"1px solid var(--hair)"},children:[l("div",{class:"flex items-center flex-wrap",style:{gap:"12px",padding:"11px 15px"},children:[l("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:R.color}}),R.label]}),t("span",{class:"flex-1",style:{minWidth:"140px",fontSize:"12.5px",color:"var(--ink-2)"},children:N&&T?Zi(T,L.version,Fe(s,L.name,"headless_login"),N):"Not configured for this account"}),T&&t(Xi,{view:T,onConnect:()=>{b(u.name,L.name)},onCancel:f})]}),N&&t(es,{account:u.name,harness:L.name}),O&&t("div",{style:{padding:"0 15px 13px"},children:t(ns,{account:u.name,harness:L.name,canUseApiKey:Fe(s,L.name,"api_key_login"),onConnected:()=>o(null),onClose:()=>o(null)},`${u.name}::${L.name}`)})]},L.name)})]},u.name)};return l(V,{children:[l(Ve,{title:"Accounts",subtitle:S,children:[t(I,{label:"Refresh",variant:"secondary",onClick:()=>{ve(!0)}}),t(I,{label:"Add account",variant:"primary",onClick:()=>c(!0)})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[i&&t(as,{response:s,onCancel:()=>c(!1),onCreated:()=>{c(!1),ve(!0),a()}}),s&&!s.available&&l("section",{style:{...Ra,padding:"16px 18px"},children:[l("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(I,{label:"Retry",variant:"secondary",size:"sm",onClick:()=>{ve(!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(u=>t("p",{style:{...de,background:Z("--red"),color:"var(--ink)"},children:u.message},u.code)),x&&x.warnings.map(u=>t("p",{style:{...de,background:"var(--elev)",color:"var(--ink-2)"},children:u.message},u.code)),x==null?void 0:x.accounts.map(w)]})]})},Ta="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev",is=({sessions:e,openTabKeys:n,onOpenSession:a,onNewTask:r,onClose:o,position:i})=>{const c=oe(null);F(()=>{const d=f=>{c.current&&!c.current.contains(f.target)&&o()},x=f=>{f.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 l("div",{ref:c,class:"popover fixed z-[60] flex flex-col",style:{top:`${i.top}px`,left:`${i.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"}),Ge.map(d=>l("button",{type:"button",class:Ta,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{r(d.key),o()},children:[t(In,{type:d.sessionType,size:22,radius:7,font:10}),t("span",{class:"flex-1",children:Hn(d.key)})]},d.key)),s.length>0&&l(V,{children:[t("div",{style:{padding:"9px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:"Resume"}),s.map(d=>l("button",{type:"button",class:Ta,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{a(d),o()},children:[t(In,{type:d.type,size:22,radius:7,font:10}),t("span",{class:"flex-1 truncate",children:ue(d)}),t("span",{class:"mono truncate",style:{fontSize:"10.5px",color:"var(--ink-3)",maxWidth:"110px"},children:le(d)})]},q(d)))]})]})},ss=({tabs:e,activeIndex:n,onActivate:a,onClose:r,onBack:o,allSessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d})=>{const[x,f]=y(!1),b=oe(null),[m,S]=y({top:0,left:0}),k=J(()=>f(!1),[]),w=()=>{if(!x&&b.current){const u=b.current.getBoundingClientRect();S({top:u.bottom+6,left:Math.max(8,Math.min(u.left,window.innerWidth-328))})}f(!x)};return l(V,{children:[l("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(Xn,{}),t(hl,{onClick:o}),e.map((u,h)=>{const v=h===n,p=Ae.value[q(u)],z=!v&&Ke(p);return l("div",{role:"tab",tabIndex:0,"aria-selected":v,title:[z?Kt(p):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:v?"var(--card)":"transparent",border:`1px solid ${v?"var(--hair)":"transparent"}`,boxShadow:v?"var(--shadow-s)":"none"},onClick:()=>a(h),onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),a(h))},children:[t($e,{size:6,live:u.status==="active",color:z?`var(${Ot(p)})`:void 0}),t("span",{style:{fontWeight:600,color:v?"var(--ink)":"var(--ink-2)"},children:ue(u)}),t("span",{class:"mono truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"110px"},children:le(u)}),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:g=>{g.stopPropagation(),r(h)},title:"Close tab (⌘W)","aria-label":`Close ${ue(u)}`,children:t("span",{class:"i-lucide-x",style:{width:"13px",height:"13px"}})})]},q(u))}),t("button",{ref:b,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(is,{sessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d,onClose:k,position:m})]})};function cs(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?gt(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 ds=({request:e,onCancel:n,onConfirm:a})=>{if(!e)return null;const r=e.state?e.state.closeWarnings:["state-unknown"],o=r.includes("uncommitted");return l(Ee,{open:!0,title:"Close this task?",onClose:n,footer:l(V,{children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{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:cs(c,e.state)},c))}),e.error&&t("p",{style:{marginTop:"10px",fontSize:"12.5px",color:"var(--ink-2)"},children:e.error})]})},wn="forge-open-tabs";function ps({spaces:e,loading:n,onFetchData:a}){const[r,o]=y([]),[i,c]=y(0),[s,d]=y(!0),x=oe(!1),f=oe(r);f.current=r,F(()=>{if(!(n||e.length===0||x.current)){x.current=!0;try{const u=sessionStorage.getItem(wn);if(!u)return;const{keys:h,activeIndex:v}=JSON.parse(u),p=[];for(const z of h){const g=e.find(A=>q(A)===z);g&&p.push(g)}p.length>0&&(o(p),c(Math.min(v,p.length-1)))}catch{}}},[n,e]),F(()=>{if(x.current)if(r.length>0){const u=r.map(q);sessionStorage.setItem(wn,JSON.stringify({keys:u,activeIndex:i}))}else sessionStorage.removeItem(wn)},[r,i]);const b=J(u=>{const h=q(u),v=r.findIndex(p=>q(p)===h);v>=0?c(v):(o(p=>[...p,u]),c(r.length)),d(!1)},[r]),m=J(async u=>{const h=f.current.find(g=>q(g)===u);if(!h)return;const v=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:v})})}catch{}const p=f.current.findIndex(g=>q(g)===u);if(p<0)return;yo(u);const z=f.current.length-1;o(g=>g.filter(A=>q(A)!==u)),z===0?(d(!0),c(0),a()):c(g=>g>p?g-1:Math.min(g,z-1))},[a]),S=J(u=>{const h=r[u];return h?m(q(h)):Promise.resolve()},[r,m]),k=J(()=>{d(!0),a()},[a]);F(()=>{const u=h=>{if(r.length===0||s)return;const v=h.metaKey||h.ctrlKey;if(v&&h.key>="1"&&h.key<="5"){const p=parseInt(h.key)-1;p<r.length&&(h.preventDefault(),c(p));return}if(v&&(h.key==="ArrowLeft"||h.key==="ArrowRight")){h.preventDefault(),c(p=>h.key==="ArrowLeft"?p>0?p-1:r.length-1:p<r.length-1?p+1:0);return}if(v&&h.key==="w"){h.preventDefault(),S(i);return}v&&h.key==="l"&&(h.preventDefault(),k())};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r,s,i,S,k]);const w=ee(()=>new Set(r.map(q)),[r]);return{openTabs:r,activeTabIndex:i,setActiveTabIndex:c,showList:s,openTab:b,closeTab:S,closeTabByKey:m,goToList:k,openTabKeys:w}}function us({spaces:e,accounts:n,projects:a}){const[r,o]=y(null),[i,c]=y(null),[s,d]=y(null),[x,f]=y(null),[b,m]=y(!1),S=ee(()=>Array.from(new Set(e.map(v=>v.harness??"claude"))).sort(),[e]),k=ee(()=>{if(n.length>0)return n;const v=new Set;for(const p of e)p.account&&v.add(p.account);return Array.from(v).sort()},[n,e]),w=ee(()=>{const v=new Set;for(const p of e)r&&p.account!==r||le(p)&&v.add(p.project);for(const[p,z]of Object.entries(a))r&&z.account!==r||v.add(p);return Array.from(v).sort()},[e,a,r]),u=v=>{if(o(v),v&&i){const p=a[i];p&&p.account!==v&&c(null)}},h=ee(()=>e.filter(v=>!(r&&v.account!==r||i&&v.project!==i||x&&(v.harness??"claude")!==x||s&&v.type!==ao(s)||!b&&v.status==="done")),[e,r,i,s,x,b]);return{filterAccount:r,setFilterAccount:u,filterProject:i,setFilterProject:c,filterType:s,setFilterType:d,filterHarness:x,setFilterHarness:f,showDone:b,setShowDone:m,accountNames:k,projectNames:w,harnessNames:S,filteredSpaces:h}}function hs(){const[e,n]=y([]),[a,r]=y({}),[o,i]=y([]),[c,s]=y(!0),[d,x]=y("list"),[f,b]=y(!1),[m,S]=y(null),[k,w]=y(!1);F(()=>{ve(),cr(),fetch("/api/liveframe/frames").then(C=>C.json()).then(C=>S(C.length)).catch(()=>{})},[]);const u=J(async()=>{try{const[C,D,K]=await Promise.all([fetch("/api/cw/spaces"),fetch("/api/cw/projects"),fetch("/api/cw/accounts")]);n(await C.json()),r(await D.json()),i(await K.json()),Zo()}catch{P("Failed to connect to server","error")}finally{s(!1)}},[]),h=J(()=>{setTimeout(u,500),setTimeout(u,2500)},[u]);F(()=>{u()},[u]);const v=ps({spaces:e,loading:c,onFetchData:u}),p=us({spaces:e,accounts:o,projects:a}),z=Object.keys(a).length>0,g=C=>{const D=Ge.find(K=>K.key===C);D&&(Ue.value=D.key),b(!0)},[A,L]=y(null),N=J(async(C,D)=>{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)P("Task closed","info"),D==null||D(),h();else{const ae=G.error??"cw --done failed";console.error(`[forge] closing ${C.project}/${C.task??C.pr} failed:
29
- ${ae}`),P(ae.split(`
30
- `)[0],"error")}}catch{P("Failed to close the task","error")}},[h]),O=J(async(C,D)=>{const K=await An(C,!0);if(K.state&&K.state.closeWarnings.length===0){await N(C,D);return}L({session:C,state:K.state,error:K.error,onClosed:D})},[N]),R=t(ds,{request:A,onCancel:()=>L(null),onConfirm:async()=>{const C=A;if(C)try{await N(C.session,C.onClosed)}finally{L(null)}}}),T=J(C=>{ze.value=!1,v.showList||v.goToList(),b(!1),x(C)},[v.showList,v.goToList]),$=J(()=>T("list"),[T]),B=J(()=>b(!1),[]),j=J(C=>{p.setFilterProject(p.filterProject===C?null:C),T(d==="memory"?"memory":"list")},[p.filterProject,p.setFilterProject,T,d]),W=J(C=>{p.setFilterProject(C),T("memory")},[p.setFilterProject,T]),M=J(C=>{ze.value=!1,b(!1),v.openTab(C)},[v.openTab]),[H,ce]=y(!1),E=J(()=>ce(!1),[]),Q=J(()=>ce(!0),[]);F(()=>{const C=D=>{const K=D.metaKey||D.ctrlKey,G=D.key.toLowerCase();if(K&&G==="j"){D.preventDefault(),ra();return}if(K&&G==="k"){D.preventDefault(),H?ce(!1):Q();return}const ae=D.target;ae!=null&&ae.closest('input, textarea, select, [contenteditable="true"]')||K||D.altKey||H||f||k||(D.key==="/"?(D.preventDefault(),Q()):G==="n"?(D.preventDefault(),b(!0)):G==="p"&&(D.preventDefault(),w(!0)))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[H,f,k,Q]);const te=J(async(C,D,K,G)=>{try{const X=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"general",account:D,project:K,description:C})})).json();X.ok&&X.session?(M(X.session),h(),P(G,"success")):P(X.error??"Failed to start session","error")}catch{P("Failed to start session","error")}},[M,h]),we=J((C,D)=>{const K=C==="project"&&a[D]?D:void 0;return{account:C==="account"?D:K?a[K].account:o[0]||"default",project:K}},[o,a]),kt=J((C,D,K)=>{const{account:G,project:ae}=we(C,D),X=C==="global"?"~/.claude/skills/":C==="account"?`~/.cw/accounts/${D}/skills/`:`${ae?a[ae].path:"<project>"}/.claude/skills/`,Ye=["Use the skill-creator skill to create a new Claude Code skill.","",`The user wants: ${K}`,`Target scope: ${C}${C!=="global"?` (${D})`:""}`,`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(Ye,G,ae,"AI skill creation session started")},[a,we,te]),Se=J(C=>{const{account:D,project:K}=we(C.scope,C.scopeRef);te(`Use the ${C.name} skill.`,D,K,`Session started with ${C.name}`)},[we,te]),wt=J(async(C,D,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:Il(D),description:El(C,D,K),account:G,harness:"claude"})})).json();if(X.ok&&X.session)return M(X.session),h(),P(`Proposing a skill in ${C.project}`,"success"),!0;P(X.error??"Failed to start session","error")}catch{P("Failed to start session","error")}return!1},[M,h]);F(()=>{c||Fa().catch(()=>{})},[c]);const Ce=ee(()=>e.filter(C=>C.status==="active"),[e]),Ne=ee(()=>v.openTabs.filter(C=>C.status==="active"&&C.type!=="login").map(C=>({key:q(C),session:C})),[v.openTabs]),fe=!v.showList&&v.openTabs.length>0;F(()=>{const C=fe?v.openTabs[v.activeTabIndex]:void 0;sa.value=C?q(C):null},[fe,v.openTabs,v.activeTabIndex]);const St=oe({openTabs:v.openTabs,spaces:e,openSession:M});St.current={openTabs:v.openTabs,spaces:e,openSession:M},F(()=>$o((C,D)=>{if(document.visibilityState==="visible"&&C===sa.value)return;const{openTabs:K,spaces:G,openSession:ae}=St.current,X=K.find(Ye=>q(Ye)===C)??G.find(Ye=>q(Ye)===C);X&&ca(`${ue(X)}: ${Kt(D).toLowerCase()}`,le(X)||X.account,C,()=>ae(X))}),[]),F(()=>jo(),[]);const Ct=oe(T);Ct.current=T,F(()=>Io(C=>{var K;const D=((K=be.value.find(G=>G.id===C.moduleId))==null?void 0:K.displayName)??C.moduleId;ca(`${D}: ${C.title}`,C.body??"",`module:${C.moduleId}:${C.key}`,()=>Ct.current(`module:${C.moduleId}`))}),[]);const Je=Object.values(Ae.value).filter(Ke).length;F(()=>{document.title=Je>0?`(${Je}) Forge Console`:"Forge Console"},[Je]);const na=ee(()=>{const C=new Map(Object.entries(a).map(([D,K])=>[D,K.account]));for(const D of e)le(D)&&!C.has(D.project)&&C.set(D.project,D.account);return Array.from(C,([D,K])=>({name:D,account:K||"unassigned",count:Ce.filter(G=>G.project===D).length,live:Ne.some(G=>G.session.project===D)}))},[a,e,Ce,Ne]);F(()=>{p.filterProject&&(Be.value=p.filterProject)},[p.filterProject]);const $t=ee(()=>Object.keys(a),[a]),zt=J(C=>{p.setFilterProject(C),T("list")},[p.setFilterProject,T]),tn=fe?"list":d,nn=ee(()=>[{id:"new-task",label:"New task",hint:"N",glyph:"+",token:"--blue",run:()=>g()},{id:"add-project",label:"Add project",hint:"P",glyph:"P",token:"--green",run:()=>w(!0)},...rr.map(C=>({id:C.view,label:C.label,hint:C.view==="list"?"⌘L":"",glyph:C.glyph,token:C.token,run:()=>T(C.view)})),...Za(be.value).map(C=>({id:`module:${C.id}`,label:C.displayName,hint:"",glyph:C.displayName.charAt(0).toUpperCase(),token:null,run:()=>T(`module:${C.id}`)})),{id:"add-module",label:"Add a module",hint:"",glyph:"+",token:null,run:()=>{Wt.value=!0}},{id:"appearance",label:"Toggle appearance",hint:"⌘J",glyph:"◐",token:null,run:ra}],[T,be.value]),Rt=t(Wo,{view:tn,counts:{list:Ce.length,accounts:p.accountNames.length,prototypes:m},projects:na,accounts:p.accountNames,selectedProject:p.filterProject,live:Ne,onNavigate:T,onSelectProject:j,onAddProject:()=>{ze.value=!1,w(!0)},onOpenLive:M,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(ml,{spaces:p.filteredSpaces,allSpaces:e,projects:a,accountNames:p.accountNames,filterAccount:p.filterAccount,filterProject:p.filterProject,onFilterProject:p.setFilterProject,filterType:p.filterType,onFilterType:p.setFilterType,harnessNames:p.harnessNames,filterHarness:p.filterHarness,onFilterHarness:p.setFilterHarness,showDone:p.showDone,onShowDone:p.setShowDone,openTabKeys:v.openTabKeys,onSelectTask:M,onMarkDone:O,onNewTask:()=>g(),onCreateProject:()=>w(!0),onRefresh:()=>u(),onStarted:C=>{C&&M(C),h()}}):d.startsWith("module:")?t(Vi,{moduleId:d.slice(7),cwProject:p.filterProject,onBack:$},d):d==="qa"?t(Ri,{projects:a,preferred:p.filterProject??void 0}):d==="memory"?t(Mi,{project:p.filterProject,onProject:p.setFilterProject}):d==="prototypes"?t(Ti,{accounts:p.accountNames,onOpenSession:M,onFramesChanged:S}):d==="accounts"?t(ls,{projects:a,onOpenSession:M,onAccountsChanged:()=>{u()}}):t(Jl,{accounts:p.accountNames,projects:a,onCreateWithAI:kt,onRunSkill:Se,onProposeSkill:wt});return l(Xr,{sidebar:Rt,children:[!fe&&_,v.openTabs.length>0&&l("div",{class:"flex flex-col","aria-hidden":!fe,style:fe?{height:"100vh"}:{position:"absolute",top:0,left:0,right:0,height:"100vh",visibility:"hidden",pointerEvents:"none",zIndex:-1},children:[t(ss,{tabs:v.openTabs,activeIndex:v.activeTabIndex,onActivate:v.setActiveTabIndex,onClose:v.closeTab,onBack:$,allSessions:Ce,openTabKeys:v.openTabKeys,onOpenSession:M,onNewTask:C=>{$(),g(C)}}),t("div",{class:"flex-1 min-h-0 relative",children:v.openTabs.map((C,D)=>{const K=D===v.activeTabIndex,G=K&&fe;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(Cl,{session:C,active:G,onDone:()=>O(C,()=>{v.closeTabByKey(q(C))}),onOpenMemory:W})},q(C))})})]}),f&&t(Pl,{projects:a,accounts:p.accountNames,initialAccount:p.filterAccount??(qt.value||void 0),initialProject:Be.value||void 0,onClose:B,onCreated:C=>{b(!1),C&&M(C),h()},onOpenAccounts:()=>T("accounts")}),H&&t(Mo,{openTabs:v.openTabs,sessions:e,projects:$t,commands:nn,onOpenSession:M,onSelectProject:zt,onClose:E}),t(Yi,{open:k,accounts:p.accountNames,onClose:()=>w(!1),onCreated:C=>{w(!1),C&&M(C),h()}}),R,t(Bi,{}),Wt.value&&t(Ji,{onClose:()=>{Wt.value=!1},onInstalled:C=>{C.view&&T(`module:${C.id}`)}})]})}Gr(t(hs,{}),document.getElementById("app"));
27
+ `))>=0;){const h=o.slice(0,x);o=o.slice(x+2);const y=(i=/^event: (.*)$/m.exec(h))==null?void 0:i[1],v=JSON.parse(((c=/^data: (.*)$/m.exec(h))==null?void 0:c[1])??"null");if(y==="output"&&v.chunk&&n(v.chunk),y==="done")return v.result;if(y==="error")throw new Kt(v.code??"module_error",v.message??"action failed")}}throw new Kt("module_error","the action stream ended early")}function qi(e,n,a){const r=Y({}),o=async()=>{const c=await fetch(`${Nt(e)}/settings`);c.ok&&(r.value=await c.json())};o();const i=async(c,s,d,x)=>{const h=`${Nt(e)}/actions/${encodeURIComponent(c)}${x?"/stream":""}`,y=await Sa(h,{input:s,token:d});return y.status===409?{needsConfirmation:!0}:y.ok?x?{result:await Hi(y,x)}:{result:(await y.json()).result}:mn(y)};return{settings:r,status:ja(()=>be.value.find(c=>c.id===e)),openSettings:a,reloadSettings:o,async route(c,s){const d=await fetch(`${Nt(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():mn(d)},async action(c,s,d){var w,k,p;if(((p=(k=(w=be.value.find(f=>f.id===e))==null?void 0:w.actions)==null?void 0:k.find(f=>f.id===c))==null?void 0:p.effect)!=="external"){const f=await i(c,s,void 0,d==null?void 0:d.onOutput);if(!("needsConfirmation"in f))return f.result}const h=await Sa(`${Nt(e)}/actions/${encodeURIComponent(c)}/prepare`,{input:s});if(!h.ok)return mn(h);const{confirmation:y,token:v}=await h.json();if(!await Ki(y,n()))return;const S=await i(c,s,v,d==null?void 0:d.onOutput);if("needsConfirmation"in S)throw new Kt("confirmation_required","The confirmation expired; try again");return S.result}}}const Bn=({value:e,onChange:n,initialPath:a,requireGit:r=!0})=>{const[o,i]=b(a??"~"),[c,s]=b(o),[d,x]=b([]),[h,y]=b(null),[v,S]=b(null),[w,k]=b(""),[p,f]=b(!1),[m,u]=b(!1),[T,g]=b(null);F(()=>{let P=!1;return(async()=>{u(!0),g(null);try{const H=await(await fetch(`/api/cw/browse-dirs?path=${encodeURIComponent(o)}`)).json();if(P)return;if(!H.ok){g(H.error??"Failed to load directory"),x([]);return}x(H.entries??[]),y(H.parent??null),S(H.home??null),k(H.path??o),f(!!H.isGitRepo)}catch{P||(g("Network error"),x([]))}finally{P||u(!1)}})(),()=>{P=!0}},[o]);const $=P=>{i(P),s(P)},A=e===w,N=r&&!p,O=w?v&&w===v?"~":v&&w.startsWith(v+"/")?"~"+w.slice(v.length):w:o,R={width:"24px",height:"24px",borderRadius:"7px",border:0,background:"var(--card)",color:"var(--ink-2)",boxShadow:"var(--shadow-s)"},j="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev disabled:cursor-not-allowed disabled:opacity-60",z={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 l("div",{style:{borderRadius:"12px",border:"1px solid var(--hair)",background:"var(--card)",boxShadow:"var(--shadow-s)",overflow:"hidden"},children:[l("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:R,onClick:()=>h&&$(h),disabled:!h||m,title:"Parent folder","aria-label":"Parent folder",children:"←"}),t("button",{type:"button",class:"grid place-items-center cursor-pointer",style:R,onClick:()=>$("~"),title:"Home","aria-label":"Home",children:"~"}),t("input",{type:"text",value:c,"aria-label":"Path",onInput:P=>s(P.target.value),onBlur:()=>i(c),onKeyDown:P=>{P.key==="Enter"&&i(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&&l("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…"}):T?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--red)"},children:T}):l(G,{children:[l("button",{type:"button",class:j,style:{...z,background:A?"var(--elev)":"none",fontWeight:600},onClick:()=>n(w,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)"}}),l("span",{class:"flex-1 truncate",children:["Pick ",t("span",{class:"mono",children:O})]}),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(P=>l("button",{type:"button",class:j,style:z,onClick:()=>$(P.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:P.name}),P.isGitRepo&&t("span",{style:B,children:"git"})]},P.path))]})})]})},_r={fontSize:"11.5px",color:"var(--red)"},Ca=e=>e.type==="boolean"||e.type==="string"&&e.format==="path",$a=({def:e,value:n,projects:a,onChange:r})=>e.type==="boolean"?t(Kn,{checked:n===!0,onChange:r,label:e.label}):e.type==="enum"?t("select",{class:"field",value:typeof n=="string"?n:"",onChange:o=>r(ne(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 i=ne(o);r(i===""?void 0:Number(i))}}):e.format==="cw-project"?l("select",{class:"field",value:typeof n=="string"?n:"",onChange:o=>r(ne(o)||void 0),children:[t("option",{value:"",children:"None"}),a.map(o=>t("option",{value:o,children:o},o))]}):e.format==="path"?t(Bn,{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(ne(o))}),za=({def:e,error:n,plain:a,children:r})=>l(U,{plain:a,label:l(G,{children:[e.label??"",e.required?" *":""]}),children:[r,e.help&&t("span",{style:me,children:e.help}),n&&t("span",{style:_r,children:n})]}),Gi=({moduleId:e,displayName:n,schema:a,onClose:r,onSaved:o})=>{const[i,c]=b(null),[s,d]=b({}),[x,h]=b([]),[y,v]=b(!1),S=`/api/modules/${encodeURIComponent(e)}/settings`;F(()=>{fetch(S).then(f=>f.json()).then(c).catch(()=>c({})),fetch("/api/cw/projects").then(f=>f.json()).then(f=>h(Object.keys(f))).catch(()=>{})},[S]);const w=(f,m)=>c(u=>({...u,[f]:m})),k=(f,m,u,T)=>c(g=>{const $=[...(g==null?void 0:g[f])??[]];return $[m]={...$[m],[u]:T},{...g,[f]:$}}),p=async()=>{v(!0);try{const f=await fetch(S,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(f.status===400){const{errors:m}=await f.json();d(Object.fromEntries(m.map(u=>[u.path,u.message])));return}if(!f.ok)throw new Error(`Saving failed (${f.status})`);d({}),I(`${n} settings saved`,"success"),o(),r()}catch(f){I(pe(f),"error")}finally{v(!1)}};return t(qe,{title:`${n} settings`,onClose:r,children:i?l("div",{class:"flex flex-col",style:{gap:"14px"},children:[Object.entries(a).map(([f,m])=>{if(m.type!=="list")return t(za,{def:{...m,label:m.label??f},error:s[f],plain:Ca(m),children:t($a,{def:m,value:i[f],projects:x,onChange:T=>w(f,T)})},f);const u=i[f]??[];return l("div",{class:"flex flex-col",style:{gap:"10px"},children:[t("span",{style:{...me,fontWeight:600},children:m.label??f}),m.help&&t("span",{style:me,children:m.help}),s[f]&&t("span",{style:_r,children:s[f]}),u.map((T,g)=>l("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(([$,A])=>t(za,{def:{...A,label:A.label??$},error:s[`${f}[${g}].${$}`],plain:Ca(A),children:t($a,{def:A,value:T[$],projects:x,onChange:N=>k(f,g,$,N)})},$)),t("div",{children:t(L,{label:"Remove",variant:"danger",size:"sm",onClick:()=>c($=>({...$,[f]:u.filter((A,N)=>N!==g)}))})})]},g)),t("div",{children:t(L,{label:`Add ${(m.label??f).replace(/s$/,"").toLowerCase()}`,icon:"i-lucide-plus",variant:"secondary",size:"sm",onClick:()=>w(f,[...u,{}])})})]},f)}),l("div",{class:"flex",style:{gap:"8px",marginTop:"6px"},children:[t("span",{class:"flex-1"}),t(L,{label:"Cancel",variant:"secondary",onClick:r}),t(L,{label:"Save",loading:y,onClick:p})]})]}):t("div",{class:"text-ink2",style:{fontSize:"13px"},children:"Loading…"})})};class Vi extends qr{constructor(){super(...arguments);aa(this,"state",{error:null})}componentDidCatch(a){this.setState({error:a})}render(){const{error:a}=this.state;return a?t(_n,{title:`${this.props.name}'s view crashed`,message:a.message,onReload:()=>{this.setState({error:null}),this.props.onReload()}}):this.props.children}}const _n=({title:e,message:n,onReload:a})=>l("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(L,{label:"Reload view",variant:"secondary",size:"sm",onClick:a})})]}),Ji=({status:e,onClose:n,onRemoved:a})=>{const[r,o]=b(!1),i=async()=>{o(!0);try{be.value=await pr("DELETE",`/api/modules/${encodeURIComponent(e.id)}`),I(`Removed ${e.displayName}`,"success"),a()}catch(c){I(pe(c),"error"),o(!1)}};return t(Le,{open:!0,title:`Remove ${e.displayName}?`,onClose:n,footer:l(G,{children:[t("span",{class:"flex-1"}),t(L,{label:"Cancel",variant:"secondary",onClick:n}),t(L,{label:"Remove",variant:"destructive",loading:r,onClick:i})]}),children:l("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:["Forge uninstalls ",t("span",{class:"mono",children:e.name})," and stops it now. Its settings stay saved, so installing it again brings them back."]})})},vn=new Map;function Yi(e){const n=`${e.view.url}?v=${encodeURIComponent(e.view.version)}`;let a=vn.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(()=>vn.delete(n)),vn.set(n,a)),a}const Qi=({moduleId:e,cwProject:n,onBack:a})=>{var g,$,A,N;const r=be.value.find(O=>O.id===e),[o,i]=b(!1),[c,s]=b(!1),[d,x]=b(null),[h,y]=b(0),v=oe(e);r&&(v.current=r.displayName);const S=v.current,w=ee(()=>qi(e,()=>v.current,()=>i(!0)),[e]),k=(r==null?void 0:r.state)==="enabled"?(g=r.view)==null?void 0:g.version:void 0,p=(($=er.value[e])==null?void 0:$.attention)??0;F(()=>{p>0&&Lo(e)},[e,p]),F(()=>{if(!r||!k)return;let O=!0;return Yi(r).then(R=>{O&&x({version:k,config:R})},R=>{O&&x({version:k,error:R.message})}),()=>{O=!1}},[e,k,h]);const f=r?Xa(r):null,m=l(Ve,{title:((A=r==null?void 0:r.view)==null?void 0:A.title)??S,subtitle:r?`${r.name} ${r.version}`:void 0,children:[f&&l("span",{class:"mono truncate",title:f,style:{maxWidth:"320px",fontSize:"11.5px",color:"var(--orange)"},children:["⚠ ",f]}),(r==null?void 0:r.settingsSchema)&&Object.keys(r.settingsSchema).length>0&&t(L,{label:"Settings",icon:"i-lucide-settings",variant:"secondary",size:"sm",onClick:()=>i(!0)}),(r==null?void 0:r.removable)&&t(L,{label:"Remove",icon:"i-lucide-trash-2",variant:"secondary",size:"sm",onClick:()=>s(!0)}),c&&r&&t(Ji,{status:r,onClose:()=>s(!1),onRemoved:a})]});if(!r)return l("div",{children:[m,t("div",{style:{padding:"56px 22px"},children:t(je,{icon:"i-lucide-package-x",title:`${S} was removed`,description:"The module is no longer installed.",action:{label:"Back to Tasks",onClick:a}})})]});if(r.state!=="enabled")return l("div",{children:[m,t(_n,{title:`${S} is disabled`,message:r.reason??"No reason given",onReload:()=>{ht()}})]});const u=d&&d.version===k?d:null,T=(N=u==null?void 0:u.config)==null?void 0:N.component;return l("div",{children:[m,u!=null&&u.error?t(_n,{title:`${S}'s view did not load`,message:u.error,onReload:()=>y(O=>O+1)}):T?t(Vi,{name:S,onReload:()=>y(O=>O+1),children:t(T,{moduleId:e,projectId:null,cwProject:n,forge:w})},`${k}-${h}`):l("div",{class:"py-20 text-center text-ink2",children:["Loading ",S,"…"]}),o&&r.settingsSchema&&t(Gi,{moduleId:e,displayName:S,schema:r.settingsSchema,onClose:()=>i(!1),onSaved:()=>{w.reloadSettings(),ht()}})]})},yn={padding:"12px 14px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},Zi=({onClose:e,onInstalled:n})=>{const[a,r]=b(""),[o,i]=b(null),[c,s]=b(null),[d,x]=b(null),h=async()=>{x("preview"),s(null);try{i(await ge("/api/modules/install/preview",{spec:a}))}catch(v){s(pe(v))}finally{x(null)}},y=async()=>{if(o){x("install"),s(null);try{const{status:v,modules:S}=await ge("/api/modules/install",{token:o.token});be.value=S,(v==null?void 0:v.state)==="disabled"?I(`Installed ${o.displayName}, but Forge disabled it: ${v.reason??""}`,"error"):I(`Installed ${o.displayName}`,"success"),v&&n(v),e()}catch(v){i(null),s(pe(v))}finally{x(null)}}};return l(qe,{title:"Add a module",onClose:e,children:[l("form",{class:"flex flex-col",style:{gap:"10px"},onSubmit:v=>{v.preventDefault(),a.trim()&&!d&&h()},children:[t(U,{label:"npm package, folder or git url",children:t("input",{class:"field mono",value:a,placeholder:"@scope/forge-mod-name",autoFocus:!0,spellcheck:!1,onInput:v=>{r(ne(v)),i(null)}})}),t("span",{style:me,children:"Forge reads the module's manifest first; none of its code runs until you install it."})]}),c&&t("div",{role:"alert",class:"mono",style:{...yn,fontSize:"12px",color:"var(--red)",whiteSpace:"pre-wrap",borderColor:"color-mix(in srgb, var(--red) 45%, var(--hair))"},children:c}),o&&l("div",{class:"flex flex-col",style:{gap:"12px"},children:[l("div",{style:yn,children:[t("div",{style:{fontSize:"15px",fontWeight:650},children:o.displayName}),l("div",{class:"mono",style:{marginTop:"2px",fontSize:"11.5px",color:"var(--ink-3)"},children:[o.name," ",o.version,o.kind==="legacy"?" · legacy module":""]}),o.description&&t("p",{style:{marginTop:"8px",fontSize:"13px",color:"var(--ink-2)"},children:o.description})]}),l("div",{class:"flex flex-col",style:{gap:"6px"},children:[t("span",{style:{...me,fontWeight:600},children:o.permissions.length?"It asks for":"It asks for no permissions"}),o.permissions.map((v,S)=>l("div",{class:"flex",style:{gap:"10px",fontSize:"12.5px"},children:[t("span",{class:"mono shrink-0",style:{width:"64px",color:"var(--ink-3)"},children:v.kind}),t("span",{class:"mono",style:{wordBreak:"break-all"},children:v.value})]},S))]}),t("p",{style:{...yn,fontSize:"12.5px",color:"var(--ink-2)",borderColor:"color-mix(in srgb, var(--orange) 45%, var(--hair))"},children:o.trustNote}),l("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)",wordBreak:"break-all"},children:["npm install ",o.spec]})]}),l("div",{class:"flex",style:{gap:"8px"},children:[t("span",{class:"flex-1"}),t(L,{label:"Cancel",variant:"secondary",onClick:e}),o?t(L,{label:`Install ${o.displayName}`,loading:d==="install",onClick:y}):t(L,{label:"Review",loading:d==="preview",disabled:!a.trim(),onClick:h})]})]})},Xi=({open:e,accounts:n,onClose:a,onCreated:r})=>{const[o,i]=b("create"),[c,s]=b(""),[d,x]=b(""),[h,y]=b(""),[v,S]=b(""),[w,k]=b(""),[p,f]=b(""),[m,u]=b(!1),[T,g]=b(""),[$,A]=b(!1);F(()=>{e&&n.length>0&&!c&&s(n[0])},[e,n]),F(()=>{e||(i("create"),x(""),y(""),S(""),k(""),f(""),u(!1),g(""),A(!1))},[e]);const N=c.trim().length>0&&d.trim().length>0&&v.trim().length>0,O=c.trim().length>0&&p.length>0&&m,R=async()=>{if(N){A(!0);try{const M=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:v.trim(),account:c.trim()||void 0,directory:h.trim()||void 0,model:w||void 0})})).json();M.ok?(I("Project creation started in terminal","success"),r(M.session)):I(M.error??"Failed to create project","error")}catch{I("Failed to create project","error")}finally{A(!1)}}},j=async()=>{if(O){A(!0);try{const M=await(await fetch("/api/cw/register-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p,account:c.trim(),alias:T.trim()||void 0})})).json();M.ok?(I(`Project "${M.project}" registered`,"success"),r()):I(M.error??"Failed to register project","error")}catch{I("Failed to register project","error")}finally{A(!1)}}},z=o==="create";return t(Le,{open:e,title:"Add a project",onClose:a,footer:l(G,{children:[t("span",{class:"mono flex-1 truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:z?"cw create":"cw project register"}),t(L,{label:"Cancel",variant:"secondary",onClick:a}),t(L,{label:z?$?"Creating…":"Create":$?"Registering…":"Register",variant:"primary",loading:$,disabled:!(z?N:O),onClick:z?R:j})]}),children:l("div",{class:"flex flex-col",style:{gap:"13px"},children:[t(le,{fill:!0,label:"Mode",tabs:[{id:"create",label:"Create new"},{id:"existing",label:"Register existing"}],active:o,onChange:D=>i(D)}),l("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)})}),z?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:T,placeholder:"defaults to folder name",onInput:D=>g(D.target.value)})})]}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:me,children:z?"Parent folder · optional":"Repository · must contain .git"}),z?t(Bn,{value:h,onChange:y,requireGit:!1},"dir-create"):t(Bn,{value:p,onChange:(D,M)=>{f(D),u(M)}},"dir-existing")]}),z&&l(G,{children:[t(U,{label:"Description",children:t("textarea",{rows:2,class:"field",value:v,placeholder:"A SaaS platform for…",onInput:D=>S(D.target.value)})}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:me,children:"Model"}),t(le,{size:"sm",label:"Model",tabs:[{id:"",label:"Auto"},{id:"haiku",label:"Haiku"},{id:"sonnet",label:"Sonnet"},{id:"opus",label:"Opus"}],active:w,onChange:k})]})]})]})})},es=(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"}},ts=(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 i=[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,i].filter(Boolean));break}case"api_key":o.push(...[e.providerModel,"stored by cw"].filter(i=>!!i));break;case"connected":o.push(...[r.model,n].filter(i=>!!i)),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(" · ")},Oe=({token:e,label:n})=>l("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]}),ns=({view:e,onConnect:n,onCancel:a})=>{switch(e.kind){case"connecting":return l("span",{class:"inline-flex items-center shrink-0",style:{gap:"8px"},children:[t(Oe,{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(Oe,{token:null,label:"Not installed"});case"error":return t(Oe,{token:"--red",label:"Error"});case"local":return t(Oe,{token:"--orange",label:"Local"});case"api_key":return t(Oe,{token:"--green",label:"API key"});case"connected":return t(Oe,{token:"--green",label:"Connected"});case"connect":return t(L,{label:"Connect",size:"sm",onClick:n})}},bn=({children:e})=>l("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})]}),kn=({warn:e,children:n})=>t("span",{style:{fontSize:"11.5px",color:e?"var(--orange)":"var(--ink-3)"},children:n}),as=({account:e,harness:n})=>{const a=ko(e,n);return!a||a.state==="not_connected"?null:a.state==="expired"?t(bn,{children:t(kn,{warn:!0,children:"Reconnect to see usage limits"})}):a.state==="error"?t(bn,{children:l(kn,{children:["Limits unavailable — ",a.detail??"the request failed"]})}):a.windows.length===0?null:l(bn,{children:[t(Pa,{bars:Da(a.windows)}),a.stale&&l(kn,{children:["Last known values — ",a.detail??"the refresh failed"]})]})},rs=3e3,os=({account:e,harness:n,canUseApiKey:a,onConnected:r,onClose:o})=>{const[i,c]=b(null),[s,d]=b(!1),[x,h]=b(0),[y,v]=b(""),[S,w]=b(!1),k=he(n).label,p=`/api/cw/accounts/${encodeURIComponent(e)}`,f=`${p}/login/${encodeURIComponent(n)}`,m=oe(!1),u=oe(!1);F(()=>{let A=!1,N=null;c(null),d(!1),m.current=!1,u.current=!1;const O=()=>{m.current||(m.current=!0,fetch(f,{method:"DELETE"}).catch(()=>{}),I(`${e} is connected to ${k}`,"success"),r())},R=async()=>{var D;const z=await fetch(f).catch(()=>null);if(!(z!=null&&z.ok)||A)return;const{login:B}=await z.json();if(c(B),B.status!=="exited"||(u.current=!0,N&&(clearInterval(N),N=null),B.exitCode!==0))return;d(!0);const P=await ve(!0);A||(P.available&&((D=Pe(P.doctor,e,n))==null?void 0:D.status)==="connected"?O():d(!1))};fetch(`${p}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n})}).then(z=>z.json()).then(z=>{if(!A){if(!z.ok||!z.login){I(z.error??"Could not start the login","error");return}c(z.login),N=setInterval(R,rs)}}).catch(()=>I("Could not start the login","error"));const j=_o(z=>{var B;return((B=Pe(z,e,n))==null?void 0:B.status)==="connected"},{onDone:z=>{z&&O()}});return()=>{A=!0,N&&clearInterval(N),j(),u.current||fetch(f,{method:"DELETE"}).catch(()=>{})}},[e,n,x]);const T=()=>{fetch(f,{method:"DELETE"}).catch(()=>{}),o()},g=async()=>{const A=y.trim();if(A){w(!0);try{const O=await(await fetch(`${p}/api-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n,apiKey:A})})).json();O.ok?(v(""),I("API key saved","success"),ve(!0)):I(O.error??"Could not save the API key","error")}catch{I("Could not save the API key","error")}finally{w(!1)}}},$=(i==null?void 0:i.status)==="exited";return l("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:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[l("h3",{style:{fontSize:"14px",fontWeight:650},children:["Connect ",e," on ",k]}),t("span",{class:"flex-1"}),t(L,{label:"Cancel",variant:"secondary",size:"sm",onClick:T})]}),!i&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Starting the login…"}),i&&!$&&l(G,{children:[l("div",{class:"flex flex-wrap items-center",style:{gap:"12px"},children:[i.url&&l("a",{href:i.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"}})]}),i.code&&l(G,{children:[t("span",{class:"mono",style:{fontSize:"19px",fontWeight:650,letterSpacing:".12em"},children:i.code}),t(L,{label:"Copy",variant:"secondary",size:"sm",onClick:()=>Jn(i.code??"","Code")})]})]}),i.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:i.url||i.code?"Checks every 3 s. The status turns Connected on its own.":"Waiting for the login URL…"})]}),$&&s&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Checking the connection…"}),$&&!s&&l("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(L,{label:"Retry",variant:"secondary",size:"sm",onClick:()=>h(A=>A+1)})]}),i&&i.output.length>0&&l("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:i.output.join(`
28
+ `)})]}),a&&l("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"}),l("div",{class:"flex items-center",style:{gap:"8px"},children:[t("input",{type:"password",autocomplete:"off","aria-label":"API key",value:y,onInput:A=>v(A.target.value),placeholder:"sk-…",class:"field mono flex-1 min-w-0"}),t(L,{label:"Save",variant:"secondary",size:"sm",loading:S,disabled:!y.trim(),onClick:g})]}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:"Sent to cw over stdin. Forge never stores or shows it."})]})]})},Ot={display:"block",fontSize:"12px",color:"var(--ink-2)",marginBottom:"5px"},ls=({response:e,onCancel:n,onCreated:a})=>{const[r,o]=b(""),[i,c]=b(""),[s,d]=b(""),[x,h]=b(""),[y,v]=b(!1),S=bt(),w=r.trim(),k=io.test(w),p=e!=null&&e.available?e.doctor.harnesses.map(u=>u.name).filter(u=>u!=="claude"):[],f=!!i&&Fe(e,i,"custom_provider"),m=async()=>{if(!(!k||y)){v(!0);try{const T=await(await fetch("/api/cw/accounts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,harness:i||void 0,provider:f&&s.trim()||void 0,model:f&&x.trim()||void 0})})).json();T.ok?(I(`Account "${w}" created`,"success"),a()):I(T.error??"Failed to create account","error")}catch{I("Failed to create account","error")}finally{v(!1)}}};return l("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"}),l("div",{style:{maxWidth:"360px"},children:[t("label",{style:Ot,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}),w&&!k&&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&&l("div",{children:[t("span",{style:Ot,children:"Default harness"}),t(le,{label:"Default harness",tabs:[{id:"",label:"Claude Code"},...p.map(u=>({id:u,label:he(u).label}))],active:i,onChange:c}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)",marginTop:"5px"},children:"The default harness cannot be changed later."})]}),f&&l("div",{class:"grid",style:{gridTemplateColumns:"1fr 1fr",gap:"10px",maxWidth:"520px"},children:[l("div",{children:[t("label",{style:Ot,children:"Provider · optional"}),t("input",{type:"text",value:s,onInput:u=>d(u.target.value),placeholder:"zai, ollama, openrouter",class:"field"})]}),l("div",{children:[t("label",{style:Ot,children:"Model · optional"}),t("input",{type:"text",value:x,onInput:u=>h(u.target.value),placeholder:"glm-5.1",class:"field"})]})]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(L,{label:y?"Creating…":"Add account",variant:"primary",loading:y,disabled:!k,onClick:m}),t(L,{label:"Cancel",variant:"secondary",onClick:n})]})]})},is=new Set(["localhost","127.0.0.1","::1","[::1]"]),Ra={...Me,overflow:"hidden"},ss=({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?(I(`Account "${e}" removed`,"info"),n()):I(c.error??"Failed to remove account","error")}catch{I("Failed to remove account","error")}finally{r(!1)}};return a?l("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(L,{label:"Remove account",variant:"destructive",size:"sm",onClick:o}),t(L,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>r(!1)})]}):t(L,{label:"Remove",variant:"danger",size:"sm",onClick:()=>r(!0)})},cs=({projects:e,onOpenSession:n,onAccountsChanged:a})=>{const[r,o]=b(null),[i,c]=b(!1);F(()=>{ve()},[]),F(()=>Ga(),[]);const s=Zt.value,d=!is.has(window.location.hostname),x=s!=null&&s.available?s.doctor:null,h=()=>{r&&(fetch(`/api/cw/accounts/${encodeURIComponent(r.account)}/login/${encodeURIComponent(r.harness)}`,{method:"DELETE"}).catch(()=>{}),o(null))},y=async(p,f)=>{if(Fe(s,f,"headless_login")){o({account:p,harness:f});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:f})})).json();u.ok&&u.session?n(u.session):I(u.error??"Could not open the login","error")}catch{I("Could not open the login","error")}},v=x?x.accounts.reduce((p,f)=>p+f.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 · ${v} need${v===1?"s":""} connecting`:"Reading cw doctor…",w=p=>Object.values(e).filter(f=>f.account===p).length,k=(p,f)=>{if(!x)return null;const[m,u]=Ea(f),T=w(p.name),g=Pe(x,p.name,p.default_harness),$=[he(p.default_harness).label,g&&g.provider!=="native"?g.provider:null].filter(Boolean).join(" · ");return l("section",{style:{...Ra,animation:`riseIn .36s var(--ease) ${f*90}ms both`},"aria-label":p.name,children:[l("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}),l("span",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:["Default ",$," · ",T," project",T===1?"":"s"]}),t("span",{class:"flex-1"}),t(ss,{account:p.name,onRemoved:()=>{ve(!0),a()}})]}),x.harnesses.map(A=>{const N=Pe(x,p.name,A.name),O=(r==null?void 0:r.account)===p.name&&r.harness===A.name,R=he(A.name),j=N?es(N,O):null;return l("div",{style:{borderBottom:"1px solid var(--hair)"},children:[l("div",{class:"flex items-center flex-wrap",style:{gap:"12px",padding:"11px 15px"},children:[l("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:R.color}}),R.label]}),t("span",{class:"flex-1",style:{minWidth:"140px",fontSize:"12.5px",color:"var(--ink-2)"},children:N&&j?ts(j,A.version,Fe(s,A.name,"headless_login"),N):"Not configured for this account"}),j&&t(ns,{view:j,onConnect:()=>{y(p.name,A.name)},onCancel:h})]}),N&&t(as,{account:p.name,harness:A.name}),O&&t("div",{style:{padding:"0 15px 13px"},children:t(os,{account:p.name,harness:A.name,canUseApiKey:Fe(s,A.name,"api_key_login"),onConnected:()=>o(null),onClose:()=>o(null)},`${p.name}::${A.name}`)})]},A.name)})]},p.name)};return l(G,{children:[l(Ve,{title:"Accounts",subtitle:S,children:[t(L,{label:"Refresh",variant:"secondary",onClick:()=>{ve(!0)}}),t(L,{label:"Add account",variant:"primary",onClick:()=>c(!0)})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[i&&t(ls,{response:s,onCancel:()=>c(!1),onCreated:()=>{c(!1),ve(!0),a()}}),s&&!s.available&&l("section",{style:{...Ra,padding:"16px 18px"},children:[l("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(L,{label:"Retry",variant:"secondary",size:"sm",onClick:()=>{ve(!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(k)]})]})},Ta="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev",ds=({sessions:e,openTabKeys:n,onOpenSession:a,onNewTask:r,onClose:o,position:i})=>{const c=oe(null);F(()=>{const d=h=>{c.current&&!c.current.contains(h.target)&&o()},x=h=>{h.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 l("div",{ref:c,class:"popover fixed z-[60] flex flex-col",style:{top:`${i.top}px`,left:`${i.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"}),Ge.map(d=>l("button",{type:"button",class:Ta,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{r(d.key),o()},children:[t(In,{type:d.sessionType,size:22,radius:7,font:10}),t("span",{class:"flex-1",children:Hn(d.key)})]},d.key)),s.length>0&&l(G,{children:[t("div",{style:{padding:"9px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:"Resume"}),s.map(d=>l("button",{type:"button",class:Ta,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{a(d),o()},children:[t(In,{type:d.type,size:22,radius:7,font:10}),t("span",{class:"flex-1 truncate",children:ue(d)}),t("span",{class:"mono truncate",style:{fontSize:"10.5px",color:"var(--ink-3)",maxWidth:"110px"},children:ie(d)})]},q(d)))]})]})},ps=({tabs:e,activeIndex:n,onActivate:a,onClose:r,onBack:o,allSessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d})=>{const[x,h]=b(!1),y=oe(null),[v,S]=b({top:0,left:0}),w=J(()=>h(!1),[]),k=()=>{if(!x&&y.current){const p=y.current.getBoundingClientRect();S({top:p.bottom+6,left:Math.max(8,Math.min(p.left,window.innerWidth-328))})}h(!x)};return l(G,{children:[l("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(Xn,{}),t(hl,{onClick:o}),e.map((p,f)=>{const m=f===n,u=Ae.value[q(p)],T=!m&&Ke(u);return l("div",{role:"tab",tabIndex:0,"aria-selected":m,title:[T?Ut(u):null,f<5?`⌘${f+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(f),onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),a(f))},children:[t($e,{size:6,live:p.status==="active",color:T?`var(${Wt(u)})`:void 0}),t("span",{style:{fontWeight:600,color:m?"var(--ink)":"var(--ink-2)"},children:ue(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:g=>{g.stopPropagation(),r(f)},title:"Close tab (⌘W)","aria-label":`Close ${ue(p)}`,children:t("span",{class:"i-lucide-x",style:{width:"13px",height:"13px"}})})]},q(p))}),t("button",{ref:y,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:k,"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(ds,{sessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d,onClose:w,position:v})]})};function us(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?xt(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 hs=({request:e,onCancel:n,onConfirm:a})=>{if(!e)return null;const r=e.state?e.state.closeWarnings:["state-unknown"],o=r.includes("uncommitted");return l(Le,{open:!0,title:"Close this task?",onClose:n,footer:l(G,{children:[t("span",{class:"flex-1"}),t(L,{label:"Cancel",variant:"secondary",onClick:n}),t(L,{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:us(c,e.state)},c))}),e.error&&t("p",{style:{marginTop:"10px",fontSize:"12.5px",color:"var(--ink-2)"},children:e.error})]})},wn="forge-open-tabs";function fs({spaces:e,loading:n,onFetchData:a}){const[r,o]=b([]),[i,c]=b(0),[s,d]=b(!0),x=oe(!1),h=oe(r);h.current=r,F(()=>{if(!(n||e.length===0||x.current)){x.current=!0;try{const p=sessionStorage.getItem(wn);if(!p)return;const{keys:f,activeIndex:m}=JSON.parse(p),u=[];for(const T of f){const g=e.find($=>q($)===T);g&&u.push(g)}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(wn,JSON.stringify({keys:p,activeIndex:i}))}else sessionStorage.removeItem(wn)},[r,i]);const y=J(p=>{const f=q(p),m=r.findIndex(u=>q(u)===f);m>=0?c(m):(o(u=>[...u,p]),c(r.length)),d(!1)},[r]),v=J(async p=>{const f=h.current.find(g=>q(g)===p);if(!f)return;const m=f.sessionDir??(f.type==="review"?`review-pr-${f.pr}`:`task-${f.task}`);try{await fetch("/api/cw/terminal/kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:f.project,sessionDir:m})})}catch{}const u=h.current.findIndex(g=>q(g)===p);if(u<0)return;yo(p);const T=h.current.length-1;o(g=>g.filter($=>q($)!==p)),T===0?(d(!0),c(0),a()):c(g=>g>u?g-1:Math.min(g,T-1))},[a]),S=J(p=>{const f=r[p];return f?v(q(f)):Promise.resolve()},[r,v]),w=J(()=>{d(!0),a()},[a]);F(()=>{const p=f=>{if(r.length===0||s)return;const m=f.metaKey||f.ctrlKey;if(m&&f.key>="1"&&f.key<="5"){const u=parseInt(f.key)-1;u<r.length&&(f.preventDefault(),c(u));return}if(m&&(f.key==="ArrowLeft"||f.key==="ArrowRight")){f.preventDefault(),c(u=>f.key==="ArrowLeft"?u>0?u-1:r.length-1:u<r.length-1?u+1:0);return}if(m&&f.key==="w"){f.preventDefault(),S(i);return}m&&f.key==="l"&&(f.preventDefault(),w())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,s,i,S,w]);const k=ee(()=>new Set(r.map(q)),[r]);return{openTabs:r,activeTabIndex:i,setActiveTabIndex:c,showList:s,openTab:y,closeTab:S,closeTabByKey:v,goToList:w,openTabKeys:k}}function gs({spaces:e,accounts:n,projects:a}){const[r,o]=b(null),[i,c]=b(null),[s,d]=b(null),[x,h]=b(null),[y,v]=b(!1),S=ee(()=>Array.from(new Set(e.map(m=>m.harness??"claude"))).sort(),[e]),w=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]),k=ee(()=>{const m=new Set;for(const u of e)r&&u.account!==r||ie(u)&&m.add(u.project);for(const[u,T]of Object.entries(a))r&&T.account!==r||m.add(u);return Array.from(m).sort()},[e,a,r]),p=m=>{if(o(m),m&&i){const u=a[i];u&&u.account!==m&&c(null)}},f=ee(()=>e.filter(m=>!(r&&m.account!==r||i&&m.project!==i||x&&(m.harness??"claude")!==x||s&&m.type!==ao(s)||!y&&m.status==="done")),[e,r,i,s,x,y]);return{filterAccount:r,setFilterAccount:p,filterProject:i,setFilterProject:c,filterType:s,setFilterType:d,filterHarness:x,setFilterHarness:h,showDone:y,setShowDone:v,accountNames:w,projectNames:k,harnessNames:S,filteredSpaces:f}}function xs(){const[e,n]=b([]),[a,r]=b({}),[o,i]=b([]),[c,s]=b(!0),[d,x]=b("list"),[h,y]=b(!1),[v,S]=b(null),[w,k]=b(!1);F(()=>{ve(),cr(),fetch("/api/liveframe/frames").then(C=>C.json()).then(C=>S(C.length)).catch(()=>{})},[]);const p=J(async()=>{try{const[C,W,K]=await Promise.all([fetch("/api/cw/spaces"),fetch("/api/cw/projects"),fetch("/api/cw/accounts")]);n(await C.json()),r(await W.json()),i(await K.json()),Zo()}catch{I("Failed to connect to server","error")}finally{s(!1)}},[]),f=J(()=>{setTimeout(p,500),setTimeout(p,2500)},[p]);F(()=>{p()},[p]);const m=fs({spaces:e,loading:c,onFetchData:p}),u=gs({spaces:e,accounts:o,projects:a}),T=Object.keys(a).length>0,g=C=>{const W=Ge.find(K=>K.key===C);W&&(Ue.value=W.key),y(!0)},[$,A]=b(null),N=J(async(C,W)=>{try{const V=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(V.ok)I("Task closed","info"),W==null||W(),f();else{const ae=V.error??"cw --done failed";console.error(`[forge] closing ${C.project}/${C.task??C.pr} failed:
29
+ ${ae}`),I(ae.split(`
30
+ `)[0],"error")}}catch{I("Failed to close the task","error")}},[f]),O=J(async(C,W)=>{const K=await An(C,!0);if(K.state&&K.state.closeWarnings.length===0){await N(C,W);return}A({session:C,state:K.state,error:K.error,onClosed:W})},[N]),R=t(hs,{request:$,onCancel:()=>A(null),onConfirm:async()=>{const C=$;if(C)try{await N(C.session,C.onClosed)}finally{A(null)}}}),j=J(C=>{ze.value=!1,m.showList||m.goToList(),y(!1),x(C)},[m.showList,m.goToList]),z=J(()=>j("list"),[j]),B=J(()=>y(!1),[]),P=J(C=>{u.setFilterProject(u.filterProject===C?null:C),j(d==="memory"?"memory":"list")},[u.filterProject,u.setFilterProject,j,d]),D=J(C=>{u.setFilterProject(C),j("memory")},[u.setFilterProject,j]),M=J(C=>{ze.value=!1,y(!1),m.openTab(C)},[m.openTab]),[H,ce]=b(!1),E=J(()=>ce(!1),[]),Q=J(()=>ce(!0),[]);F(()=>{const C=W=>{const K=W.metaKey||W.ctrlKey,V=W.key.toLowerCase();if(K&&V==="j"){W.preventDefault(),ra();return}if(K&&V==="k"){W.preventDefault(),H?ce(!1):Q();return}const ae=W.target;ae!=null&&ae.closest('input, textarea, select, [contenteditable="true"]')||K||W.altKey||H||h||w||(W.key==="/"?(W.preventDefault(),Q()):V==="n"?(W.preventDefault(),y(!0)):V==="p"&&(W.preventDefault(),k(!0)))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[H,h,w,Q]);const te=J(async(C,W,K,V)=>{try{const X=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"general",account:W,project:K,description:C})})).json();X.ok&&X.session?(M(X.session),f(),I(V,"success")):I(X.error??"Failed to start session","error")}catch{I("Failed to start session","error")}},[M,f]),we=J((C,W)=>{const K=C==="project"&&a[W]?W:void 0;return{account:C==="account"?W:K?a[K].account:o[0]||"default",project:K}},[o,a]),wt=J((C,W,K)=>{const{account:V,project:ae}=we(C,W),X=C==="global"?"~/.claude/skills/":C==="account"?`~/.cw/accounts/${W}/skills/`:`${ae?a[ae].path:"<project>"}/.claude/skills/`,Ye=["Use the skill-creator skill to create a new Claude Code skill.","",`The user wants: ${K}`,`Target scope: ${C}${C!=="global"?` (${W})`:""}`,`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(Ye,V,ae,"AI skill creation session started")},[a,we,te]),Se=J(C=>{const{account:W,project:K}=we(C.scope,C.scopeRef);te(`Use the ${C.name} skill.`,W,K,`Session started with ${C.name}`)},[we,te]),St=J(async(C,W,K,V)=>{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:Il(W),description:Ll(C,W,K),account:V,harness:"claude"})})).json();if(X.ok&&X.session)return M(X.session),f(),I(`Proposing a skill in ${C.project}`,"success"),!0;I(X.error??"Failed to start session","error")}catch{I("Failed to start session","error")}return!1},[M,f]);F(()=>{c||Fa().catch(()=>{})},[c]);const Ce=ee(()=>e.filter(C=>C.status==="active"),[e]),Ne=ee(()=>m.openTabs.filter(C=>C.status==="active"&&C.type!=="login").map(C=>({key:q(C),session:C})),[m.openTabs]),fe=!m.showList&&m.openTabs.length>0;F(()=>{const C=fe?m.openTabs[m.activeTabIndex]:void 0;sa.value=C?q(C):null},[fe,m.openTabs,m.activeTabIndex]);const Ct=oe({openTabs:m.openTabs,spaces:e,openSession:M});Ct.current={openTabs:m.openTabs,spaces:e,openSession:M},F(()=>$o((C,W)=>{if(document.visibilityState==="visible"&&C===sa.value)return;const{openTabs:K,spaces:V,openSession:ae}=Ct.current,X=K.find(Ye=>q(Ye)===C)??V.find(Ye=>q(Ye)===C);X&&ca(`${ue(X)}: ${Ut(W).toLowerCase()}`,ie(X)||X.account,C,()=>ae(X))}),[]),F(()=>jo(),[]);const $t=oe(j);$t.current=j,F(()=>Io(C=>{var K;const W=((K=be.value.find(V=>V.id===C.moduleId))==null?void 0:K.displayName)??C.moduleId;ca(`${W}: ${C.title}`,C.body??"",`module:${C.moduleId}:${C.key}`,()=>$t.current(`module:${C.moduleId}`))}),[]);const Je=Object.values(Ae.value).filter(Ke).length;F(()=>{document.title=Je>0?`(${Je}) Forge Console`:"Forge Console"},[Je]);const na=ee(()=>{const C=new Map(Object.entries(a).map(([W,K])=>[W,K.account]));for(const W of e)ie(W)&&!C.has(W.project)&&C.set(W.project,W.account);return Array.from(C,([W,K])=>({name:W,account:K||"unassigned",count:Ce.filter(V=>V.project===W).length,live:Ne.some(V=>V.session.project===W)}))},[a,e,Ce,Ne]);F(()=>{u.filterProject&&(Be.value=u.filterProject)},[u.filterProject]);const zt=ee(()=>Object.keys(a),[a]),Rt=J(C=>{u.setFilterProject(C),j("list")},[u.setFilterProject,j]),tn=fe?"list":d,nn=ee(()=>[{id:"new-task",label:"New task",hint:"N",glyph:"+",token:"--blue",run:()=>g()},{id:"add-project",label:"Add project",hint:"P",glyph:"P",token:"--green",run:()=>k(!0)},...rr.map(C=>({id:C.view,label:C.label,hint:C.view==="list"?"⌘L":"",glyph:C.glyph,token:C.token,run:()=>j(C.view)})),...Za(be.value).map(C=>({id:`module:${C.id}`,label:C.displayName,hint:"",glyph:C.displayName.charAt(0).toUpperCase(),token:null,run:()=>j(`module:${C.id}`)})),{id:"add-module",label:"Add a module",hint:"",glyph:"+",token:null,run:()=>{Mt.value=!0}},{id:"appearance",label:"Toggle appearance",hint:"⌘J",glyph:"◐",token:null,run:ra}],[j,be.value]),Tt=t(Do,{view:tn,counts:{list:Ce.length,accounts:u.accountNames.length,prototypes:v},projects:na,accounts:u.accountNames,selectedProject:u.filterProject,live:Ne,onNavigate:j,onSelectProject:P,onAddProject:()=>{ze.value=!1,k(!0)},onOpenLive:M,onSearch:Q}),_=c?t("div",{class:"py-20 text-center text-ink2",children:"Loading…"}):d==="list"&&!T?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:()=>k(!0)}})}):d==="list"?t(ml,{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:M,onMarkDone:O,onNewTask:()=>g(),onCreateProject:()=>k(!0),onRefresh:()=>p(),onStarted:C=>{C&&M(C),f()}}):d.startsWith("module:")?t(Qi,{moduleId:d.slice(7),cwProject:u.filterProject,onBack:z},d):d==="qa"?t(Pi,{projects:a,preferred:u.filterProject??void 0}):d==="memory"?t(_i,{project:u.filterProject,onProject:u.setFilterProject}):d==="prototypes"?t(Ai,{accounts:u.accountNames,onOpenSession:M,onFramesChanged:S}):d==="accounts"?t(cs,{projects:a,onOpenSession:M,onAccountsChanged:()=>{p()}}):t(Zl,{accounts:u.accountNames,projects:a,onCreateWithAI:wt,onRunSkill:Se,onProposeSkill:St});return l(Xr,{sidebar:Tt,children:[!fe&&_,m.openTabs.length>0&&l("div",{class:"flex flex-col","aria-hidden":!fe,style:fe?{height:"100vh"}:{position:"absolute",top:0,left:0,right:0,height:"100vh",visibility:"hidden",pointerEvents:"none",zIndex:-1},children:[t(ps,{tabs:m.openTabs,activeIndex:m.activeTabIndex,onActivate:m.setActiveTabIndex,onClose:m.closeTab,onBack:z,allSessions:Ce,openTabKeys:m.openTabKeys,onOpenSession:M,onNewTask:C=>{z(),g(C)}}),t("div",{class:"flex-1 min-h-0 relative",children:m.openTabs.map((C,W)=>{const K=W===m.activeTabIndex,V=K&&fe;return t("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",visibility:V?"visible":"hidden",zIndex:K?1:0,pointerEvents:V?"auto":"none"},children:t(Cl,{session:C,active:V,onDone:()=>O(C,()=>{m.closeTabByKey(q(C))}),onOpenMemory:D})},q(C))})})]}),h&&t(Pl,{projects:a,accounts:u.accountNames,initialAccount:u.filterAccount??(Gt.value||void 0),initialProject:Be.value||void 0,onClose:B,onCreated:C=>{y(!1),C&&M(C),f()},onOpenAccounts:()=>j("accounts")}),H&&t(Mo,{openTabs:m.openTabs,sessions:e,projects:zt,commands:nn,onOpenSession:M,onSelectProject:Rt,onClose:E}),t(Xi,{open:w,accounts:u.accountNames,onClose:()=>k(!1),onCreated:C=>{k(!1),C&&M(C),f()}}),R,t(Ui,{}),Mt.value&&t(Zi,{onClose:()=>{Mt.value=!1},onInstalled:C=>{C.view&&j(`module:${C.id}`)}})]})}Gr(t(xs,{}),document.getElementById("app"));