forge-cw 0.1.17 → 0.1.19

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 no=Object.defineProperty;var ao=(e,n,a)=>n in e?no(e,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[n]=a;var fa=(e,n,a)=>ao(e,typeof n!="symbol"?n+"":n,a);import{jsxs as l,jsx as t,Fragment as H}from"preact/jsx-runtime";import{Fragment as ro,Component as oo,render as lo}from"preact";import{useState as v,useMemo as ee,useEffect as M,useRef as ie,useCallback as J}from"preact/hooks";import{signal as Y,computed as Fa}from"@preact/signals";import{ToastContainer as io,Tabs as de,UsageMeter as Ba,ToggleSwitch as rn,showToast as j,ActionButton as I,ForgeTerminal as so,Drawer as Ze,Modal as Re,EmptyState as Oe,Badge as He}from"@forge-dev/ui";import{createPortal as co}from"preact/compat";import{definePanel as po,ModuleRequestError as Qt}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 _a="forge-theme",uo=()=>{try{return localStorage.getItem(_a)==="light"?"light":"dark"}catch{return"dark"}},Ct=Y(uo());document.documentElement.setAttribute("data-theme",Ct.value);const Ka=e=>{Ct.value=e,document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(_a,e)}catch{}},Te=Y(!1),ga=()=>Ka(Ct.value==="dark"?"light":"dark"),ho=({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${Te.value?" open":""}`,onClick:()=>{Te.value=!1}}),t("div",{class:"min-w-0 flex flex-col relative",style:{minHeight:"100vh"},children:n}),t(io,{})]}),xa=[["--blue","--purple"],["--teal","--blue"],["--orange","--red"],["--green","--teal"]],Ua=e=>xa[e%xa.length],Q=(e,n=18)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,Le={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)"},oe={padding:"10px 14px",borderRadius:"12px",fontSize:"12.5px"},fo={personal:"--blue",project:"--green",client:"--green",team:"--purple"},Ve=e=>fo[e??""]??"--ink-2",go={decision:"--purple",context:"--teal",playbook:"--green",memory:"--orange",instinct:"--red",rule:"--blue",skill:"--ink-2"},ma=e=>go[e]??"--ink-3",Ot=[{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:[]}],Ke=(e,n,a)=>({label:e,glyph:n,token:a,ink:`var(${a})`,fill:Q(a)}),Nn={task:Ke("Dev","D","--orange"),review:Ke("Review","R","--blue"),loop:Ke("Loop","L","--purple"),general:Ke("General","G","--green")},xo={create:Ke("Create","C","--teal"),login:Ke("Login","A","--ink-2")},na=e=>Nn[e]??xo[e]??Nn.task,Xe=[{key:"dev",sessionType:"task"},{key:"review",sessionType:"review"},{key:"loop",sessionType:"loop"},{key:"general",sessionType:"general"}],aa=e=>{var n;return Nn[((n=Xe.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"].label},mo=e=>{var n;return((n=Xe.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"},ra={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}},Je=e=>!!(e&&(ra[e.state].attention||e.state==="exited"&&(e.exitCode??0)!==0)),Zt=e=>e.state==="exited"&&e.exitCode?`Exited with code ${e.exitCode}`:ra[e.state].label,Ut=e=>e.state==="exited"&&e.exitCode?"--red":ra[e.state].token,G=e=>e.sessionDir?`${e.project}::${e.sessionDir}`:`${e.project}::${e.task??e.pr}`,se=e=>e.project==="__general"?"":e.project,Me=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} · ${ge(e.harness).label}`:e.task??"unknown",vo={linear:"Linear",notion:"Notion"},oa=e=>{var a;const n=e.source?vo[e.source]:void 0;return n&&((a=e.source_url)!=null&&a.startsWith("https://"))?{label:n,url:e.source_url}:null},$t=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`},Wt=(e,n)=>({label:e,color:`var(--forge-harness-${n})`,bg:Q(`--forge-harness-${n}`)}),yo={claude:Wt("Claude Code","claude"),codex:Wt("Codex","codex"),pi:Wt("Pi","pi"),opencode:Wt("OpenCode","opencode")},ge=e=>yo[e??"claude"]??{label:e??"claude",color:"var(--ink-3)",bg:"var(--elev)"},Ha=e=>{const n=ge(e.harness).label;return e.provider&&e.provider!=="native"?`${n} · ${e.model||e.provider}`:n},bo=[{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"}],qa=(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"},We=(e,n,a)=>{var r;return(r=e.accounts.find(o=>o.name===n))==null?void 0:r.harnesses.find(o=>o.harness===a)},ko=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,wo=new Intl.DateTimeFormat(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}),Ga=(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 ${wo.format(Math.round(a/6e4)*6e4)}`;const i=r%60;return`resets in ${o} h${i?` ${i} m`:""}`},Va=e=>e.map(n=>({label:n.label,percent:n.percent,severity:n.severity,scope:n.scope,reset:Ga(n.resetsAt)})),Ja=Y(null);async function So(){const e=await fetch("/api/health");Ja.value=(await e.json()).version??null}const ht=Y(null);async function Ya(){const e=await fetch("/api/skills");if(!e.ok)throw new Error("fetch failed");ht.value=await e.json()}const ze=({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"}})},gn=5,Qa="forge-sidebar-collapsed",Co=()=>{try{const e=localStorage.getItem(Qa);return e?JSON.parse(e):[]}catch{return[]}},$o=(e,n)=>Number(n.live)-Number(e.live)||n.count-e.count||e.name.localeCompare(n.name),zo=({projects:e,accounts:n,selected:a,onSelect:r,onAdd:o})=>{const[i,c]=v(""),[s,d]=v(Co),[f,g]=v([]),y=i.trim().toLowerCase(),m=ee(()=>{const k=[...n,...e.map(b=>b.account).filter(b=>!n.includes(b))];return Array.from(new Set(k)).map((b,p)=>({account:b,index:p,items:e.filter(x=>x.account===b&&(!y||x.name.toLowerCase().includes(y))).sort($o),active:e.filter(x=>x.account===b).reduce((x,S)=>x+S.count,0)})).filter(b=>b.items.length>0)},[e,n,y]),w=k=>{const b=s.includes(k)?s.filter(p=>p!==k):[...s,k];d(b);try{localStorage.setItem(Qa,JSON.stringify(b))}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 b=y!==""||!s.includes(k.account),p=y!==""||f.includes(k.account)||k.items.some((u,z)=>z>=gn&&u.name===a),x=p?k.items:k.items.slice(0,gn),[S,h]=Ua(k.index),C=k.items.some(u=>u.live);return l("div",{class:"flex flex-col shrink-0",style:{gap:"1px"},children:[l("button",{type:"button","aria-expanded":b,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:()=>w(k.account),children:[t("span",{class:"i-lucide-chevron-right shrink-0",style:{width:"11px",height:"11px",color:"var(--ink-3)",transform:b?"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(${S}), var(${h}))`,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}),C&&t(ze,{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})]}),b&&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:[x.map(u=>{const z=a===u.name;return l("button",{type:"button","aria-pressed":z,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 ${z?"var(--hair)":"transparent"}`,background:z?"var(--card)":"transparent",boxShadow:z?"var(--shadow-s)":"none"},onClick:()=>r(u.name),children:[t(ze,{size:6,live:u.live}),t("span",{class:"flex-1 truncate",style:{fontWeight:z?600:450,opacity:u.count>0||u.live||z?1:.62},children:u.name}),u.count>0&&t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:u.count})]},u.name)}),k.items.length>gn&&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:()=>g(p?f.filter(u=>u!==k.account):[...f,k.account]),children:p?"Show less":`Show all ${k.items.length}`})]})]},k.account)})]})]})},Za={context:null,tokens:null,cost:null},Ro=250,Xt=new Map,To=/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g,at=(e,n)=>{let a=null;for(const r of e.matchAll(n))a=r;return a},xn=e=>{const n=parseFloat(e),a=e.slice(-1).toLowerCase();return a==="k"?n*1e3:a==="m"?n*1e6:n};function jo(e){const n={},a=at(e,/(?:ctx|context)[:\s]*(\d{1,3}(?:\.\d+)?)\s*%/gi)??at(e,/[▓█▒░]+\s*(\d{1,3}(?:\.\d+)?)\s*%/g);a&&(n.context=Math.min(100,parseFloat(a[1])));const r=at(e,/(\d+(?:\.\d+)?[kKmM]?)\s*↑\s*(\d+(?:\.\d+)?[kKmM]?)\s*↓/g),o=at(e,/\((\d+(?:\.\d+)?[kKmM])\s*\/\s*\d+(?:\.\d+)?[kKmM]\)/g);r?n.tokens=xn(r[1])+xn(r[2]):o&&(n.tokens=xn(o[1]));const i=at(e,/\$(\d+\.\d{2})\b/g);return i&&(n.cost=parseFloat(i[1])),n}const Xa=e=>{let n=Xt.get(e);return n||(n={tail:"",timer:null,metrics:Y(Za)},Xt.set(e,n)),n},er=e=>Xa(e).metrics,Po=e=>{e.timer=null;const n=e.metrics.value,a={...n,...jo(e.tail)};(a.context!==n.context||a.tokens!==n.tokens||a.cost!==n.cost)&&(e.metrics.value=a)};function Ao(e,n){const a=Xa(e);a.tail=(a.tail+n.slice(-4e3*2).replace(To,"")).slice(-4e3),a.timer||(a.timer=setTimeout(()=>Po(a),Ro))}function Io(e){const n=Xt.get(e);n&&(n.timer&&clearTimeout(n.timer),n.metrics.value=Za,Xt.delete(e))}const tr=e=>e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e),nr=e=>`$${e.toFixed(2)}`,mt=Y(null),Lo=6e4;let rt=null,ot=null,mn=0;function va(e=!1){return rt||(rt=fetch(`/api/cw/usage${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(mt.value=n,rt=null,n)),rt)}function ar(){return mn+=1,va(),ot||(ot=setInterval(()=>{document.visibilityState==="visible"&&va()},Lo)),()=>{mn-=1,mn===0&&ot&&(clearInterval(ot),ot=null)}}const Eo=(e,n)=>{var a;return((a=mt.value)!=null&&a.available?mt.value.usage.find(r=>r.account===e&&r.harness===n):null)??null},Ae=Y({}),ya=Y(null),rr=2e3,No=15e3;let lt=null,or=0,vn=!1;const Ht=new Set,Oo=(e,n)=>!!e&&Je(n)&&(e.state!==n.state||e.since!==n.since);async function lr(){if(!vn){vn=!0,or=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(Oo(a[r],o))for(const i of Ht)i(r,o)}catch{}finally{vn=!1}}}const Wo=()=>{const e=document.visibilityState==="visible"?rr:No;Date.now()-or>=e-100&&lr()};function Do(e){return Ht.add(e),lt||(lr(),lt=setInterval(Wo,rr)),()=>{Ht.delete(e),Ht.size===0&&lt&&(clearInterval(lt),lt=null)}}const ir="forge.notify-sessions",on=typeof window<"u"&&"Notification"in window,Mo=()=>{try{return on&&Notification.permission==="granted"&&localStorage.getItem(ir)==="1"}catch{return!1}},la=Y(Mo());async function Fo(e){if(e&&(!on||(Notification.permission==="default"?await Notification.requestPermission():Notification.permission)!=="granted"))return!1;la.value=e;try{localStorage.setItem(ir,e?"1":"0")}catch{}return!0}function ba(e,n,a,r){if(!la.value||!on||Notification.permission!=="granted")return;const o=new Notification(e,{body:n,tag:a});o.onclick=()=>{window.focus(),r(),o.close()}}const ke=Y([]),qt=Y(!1),Bo=1e4;let it=null,yn=0;async function vt(){try{const e=await fetch("/api/modules");e.ok&&(ke.value=await e.json())}catch{}}const ka=()=>{vt()};function _o(){return yn++,it||(vt(),it=setInterval(()=>{vt()},Bo),window.addEventListener("focus",ka)),()=>{yn--,yn===0&&it&&(clearInterval(it),it=null,window.removeEventListener("focus",ka))}}const sr=e=>e.filter(n=>n.state!=="legacy"&&(n.view||n.state==="disabled")),cr=e=>e.lastDenial?`Denied ${e.lastDenial.permission}: ${e.lastDenial.value}`:e.lastJobError??e.lastEventError??null,yt=Y([]),dr=Fa(()=>{var n;const e={};for(const a of yt.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}),pr=5e3,Ko=15e3;let st=null,ur=0,wa=!1,bn=!1;const Gt=new Set,Sa=e=>`${e.moduleId}\0${e.key}\0${e.createdAt}`;async function hr(){if(!bn){bn=!0,ur=Date.now();try{const e=await fetch("/api/modules/notifications");if(!e.ok)return;const{items:n}=await e.json(),a=new Set(yt.value.map(Sa));if(yt.value=n,wa){for(const r of n)if(r.kind==="attention"&&!r.seen&&!a.has(Sa(r)))for(const o of Gt)o(r)}wa=!0}catch{}finally{bn=!1}}}const Uo=()=>{const e=document.visibilityState==="visible"?pr:Ko;Date.now()-ur>=e-100&&hr()};function Ho(e){return Gt.add(e),st||(hr(),st=setInterval(Uo,pr)),()=>{Gt.delete(e),Gt.size===0&&st&&(clearInterval(st),st=null)}}async function qo(e){yt.value=yt.value.map(n=>n.moduleId===e?{...n,seen:!0}:n),await fetch(`/api/modules/${encodeURIComponent(e)}/notifications/seen`,{method:"POST"}).catch(()=>{})}const fr=[{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"}],On="flex items-center w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",Wn=e=>({borderRadius:"9px",border:`1px solid ${e?"var(--hair)":"transparent"}`,background:e?"var(--card)":"transparent",boxShadow:e?"var(--shadow-s)":"none",color:"var(--ink)"}),gr="flex flex-col text-left cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m",Dn={gap:"6px",padding:"9px 10px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",color:"var(--ink)"},Mn={fontSize:"10.5px",color:"var(--ink-3)"},Fn=({children:e})=>t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)",letterSpacing:".02em"},children:e}),Go=({id:e,session:n,index:a,onOpen:r})=>{const o=er(e).value,i=Ae.value[e],c=Je(i),s=n.type==="loop",d=(o==null?void 0:o.context)??null,[f,g]=a%2===0?["var(--blue)","var(--purple)"]:["var(--purple)","var(--blue)"],y=c?Zt(i):s?n.loop_interval?`every ${n.loop_interval}`:"self-paced":o&&(o.tokens!==null||o.cost!==null)?[o.tokens!==null?`${tr(o.tokens)} tokens`:null,o.cost!==null?nr(o.cost):null].filter(Boolean).join(" · "):se(n)||n.account;return l("button",{type:"button",class:gr,style:c?{...Dn,borderColor:`var(${Ut(i)})`}:Dn,onClick:r,title:i?Zt(i):void 0,children:[l("span",{class:"flex items-center w-full",style:{gap:"6px"},children:[t(ze,{size:6,color:i?`var(${Ut(i)})`:f,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, ${f}, ${g})`,transition:"width .6s var(--ease)"}}),t("span",{class:"absolute inset-y-0 left-0",style:{width:"30%",background:"linear-gradient(90deg, transparent, rgba(255,255,255,.22), transparent)",animation:"sweep 2.6s ease-in-out infinite"}})]}),t("span",{class:"mono truncate w-full",style:c?{...Mn,color:`var(${Ut(i)})`,fontWeight:600}:Mn,children:y})]})},Vo=({view:e,onNavigate:n})=>{const a=sr(ke.value),r=dr.value,o=()=>{Te.value=!1,qt.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(Fn,{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:On,style:{...Wn(!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",f=d?null:cr(i),g=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??""}`:f??i.displayName,class:On,style:{...Wn(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}),f&&t("span",{class:"sb-label","aria-label":"Has a warning",style:{width:"6px",height:"6px",borderRadius:"50%",background:"var(--orange)"}}),g&&g.attention>0&&t("span",{class:"mono sb-label","aria-label":`${g.attention} need you`,style:{fontSize:"10.5px",fontWeight:700,padding:"0 6px",borderRadius:"99px",color:"#fff",background:"var(--red)"},children:g.attention}),g&&g.badge>0&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:g.badge})]},`${i.id}-${i.source}`)})]})},Jo=()=>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(rn,{checked:la.value,label:"Notify me when a session or module needs me",onChange:e=>{Fo(e).then(n=>{n||j("The browser blocked notifications for Forge","error")})}})]}),Yo=({account:e,harness:n,windows:a,stale:r,onOpen:o})=>{const i=a.reduce((s,d)=>d.percent>s.percent?d:s),c=ge(n).label;return l("button",{type:"button",class:gr,style:Dn,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(Ba,{bars:Va(a),size:"sm"}),t("span",{class:"mono truncate w-full",style:Mn,children:r?"last known values":Ga(i.resetsAt)})]})},Qo=({view:e,counts:n,projects:a,accounts:r,selectedProject:o,live:i,onNavigate:c,onSelectProject:s,onAddProject:d,onOpenLive:f,onSearch:g})=>{var b;const y=Ja.value,m=fr.map(p=>{var x;return{...p,count:p.view==="skills"?((x=ht.value)==null?void 0:x.length)??null:n[p.view]??null}});M(()=>ar(),[]),M(()=>{So().catch(()=>{})},[]);const w=[...i].sort((p,x)=>Number(Je(Ae.value[x.key]))-Number(Je(Ae.value[p.key]))),k=(b=mt.value)!=null&&b.available?mt.value.usage.filter(p=>p.state==="ok"&&p.windows.some(x=>!x.scope)):[];return l("aside",{class:`forge-sidebar flex flex-col${Te.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})]}),g&&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:g,"aria-label":"Search (⌘K)",children:[t("span",{class:"i-lucide-search shrink-0",style:{width:"13px",height:"13px",opacity:.7}}),t("span",{class:"flex-1 sb-label",children:"Search"}),t("kbd",{class:"sb-label",style:{fontSize:"10px",padding:"1px 5px",borderRadius:"5px",background:"var(--elev)",border:"1px solid var(--hair)"},children:"⌘K"})]}),t("nav",{class:"flex flex-col",style:{gap:"2px"},"aria-label":"Sections",children:m.map(p=>{const x=e===p.view;return l("button",{type:"button","aria-current":x?"page":void 0,title:p.label,class:On,style:{...Wn(x),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:x?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:x?Q(p.token):"var(--elev)",color:x?`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(Vo,{view:e,onNavigate:c}),t(zo,{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(Fn,{children:"Live now"})}),w.map((p,x)=>t(Go,{id:p.key,session:p.session,index:x,onOpen:()=>f(p.session)},p.key))]}),k.length>0&&l("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(Fn,{children:"Limits"})}),k.map(p=>t(Yo,{account:p.account,harness:p.harness,windows:p.windows.filter(x=>!x.scope),stale:p.stale,onOpen:()=>c("accounts")},`${p.account}/${p.harness}`))]}),on&&t("div",{class:"sb-section",children:t(Jo,{})}),t("div",{class:"sb-section",children:t(de,{fill:!0,size:"xs",label:"Appearance",tabs:[{id:"light",label:"Light"},{id:"dark",label:"Dark"}],active:Ct.value,onChange:p=>Ka(p==="light"?"light":"dark")})})]})]})};function zt(){const e=ie(null);return M(()=>{var n;(n=e.current)==null||n.focus()},[]),e}const Ca=(e,n,a)=>{const r=na(e.type);return{id:G(e),label:se(e)?`${ue(e)} · ${se(e)}`:ue(e),hint:n,glyph:r.glyph,token:r.token,run:()=>a(e)}},Zo=({openTabs:e,sessions:n,projects:a,commands:r,onOpenSession:o,onSelectProject:i,onClose:c})=>{const[s,d]=v(""),[f,g]=v(0),y=ie(null),m=zt(),w=ee(()=>{const h=s.trim().toLowerCase(),C=O=>!h||O.label.toLowerCase().includes(h),u=new Set(e.map(G)),z=e.map((O,T)=>Ca(O,T<5?`⌘${T+1}`:"open",o)),L=n.filter(O=>O.status==="active"&&!u.has(G(O))).map(O=>Ca(O,"resume",o)),N=h?a.map(O=>({id:`project:${O}`,label:O,hint:"project",glyph:"P",token:"--green",run:()=>i(O)})):[];return[{name:"Live now",items:z.filter(C)},{name:"Tasks",items:L.filter(C).slice(0,h?12:6)},{name:"Projects",items:N.filter(C).slice(0,6)},{name:"Commands",items:r.filter(C)}].filter(O=>O.items.length>0)},[s,e,n,a,r,o,i]),k=w.flatMap(h=>h.items),b=Math.min(f,k.length-1);M(()=>{var h,C;(C=(h=y.current)==null?void 0:h.querySelector('[data-active="true"]'))==null||C.scrollIntoView({block:"nearest"})},[b]);const p=h=>{h&&(c(),h.run())},x=ie({flat:k,current:b,activate:p});x.current={flat:k,current:b,activate:p},M(()=>{const h=C=>{const{flat:u,current:z,activate:L}=x.current,N=u.length;C.key==="ArrowDown"?(C.preventDefault(),g(O=>N?(Math.min(O,N-1)+1)%N:0)):C.key==="ArrowUp"?(C.preventDefault(),g(O=>N?(Math.min(O,N-1)-1+N)%N:0)):C.key==="Enter"?(C.preventDefault(),L(u[z])):C.key==="Escape"&&(C.preventDefault(),c())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[c]);let S=-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:h=>h.stopPropagation(),children:[t("input",{ref:m,role:"combobox","aria-expanded":"true","aria-controls":"palette-list","aria-activedescendant":k[b]?`palette-${k[b].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:h=>{d(h.target.value),g(0)}}),l("div",{id:"palette-list",role:"listbox",ref:y,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,"”."]}),w.map(h=>l("div",{role:"group","aria-label":h.name,children:[t("div",{style:{padding:"7px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:h.name}),h.items.map(C=>{S+=1;const u=S,z=u===b;return l("button",{id:`palette-${C.id}`,type:"button",role:"option","aria-selected":z,"data-active":z,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"10px",padding:"8px 10px",borderRadius:"10px",border:0,background:z?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px",transition:"background .14s"},onMouseMove:()=>{z||g(u)},onClick:()=>p(C),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"22px",height:"22px",borderRadius:"7px",fontSize:"10px",fontWeight:700,background:C.token?Q(C.token):"var(--elev)",color:C.token?`var(${C.token})`:"var(--ink-2)"},children:C.glyph}),t("span",{class:"flex-1 min-w-0 truncate",children:C.label}),t("span",{class:"mono shrink-0",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:C.hint})]},C.id)})]},h.name))]}),t("div",{class:"flex shrink-0",style:{gap:"14px",padding:"8px 14px",borderTop:"1px solid var(--hair)"},children:["↑↓ move","↵ open","esc close"].map(h=>t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:h},h))})]})})},ln=Y(null),Xo=3e3;let ct=null;function ye(e=!1){return ct||(ct=fetch(`/api/cw/harnesses${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(ln.value=n,ct=null,n)),ct)}const bt=new Set;let ft=null;const xr=()=>{bt.size===0&&ft&&(clearInterval(ft),ft=null)},el=async()=>{const e=await ye(!0),n=Date.now();for(const a of bt){const r=e.available&&a.check(e.doctor);(r||n>a.deadline)&&(bt.delete(a),a.onDone(r))}xr()};function tl(e,{timeoutMs:n=6e5,onDone:a=()=>{}}={}){const r={check:e,deadline:Date.now()+n,onDone:a};return bt.add(r),ft||(ft=setInterval(el,Xo)),()=>{bt.delete(r),xr()}}const qe=(e,n,a)=>{var r;return!!(e!=null&&e.available&&((r=e.capabilities[n])!=null&&r.includes(a)))},mr=e=>/linear\.app/.test(e)?"linear":/notion\.(so|site)/.test(e)?"notion":null,vr=(e,n,a)=>{const r=mr(a);return!!(e!=null&&e.available&&r&&!qe(e,n,"mcp")&&!e.contextTokens[r])},Bn=Y(null);let kn=null;function yr(){return kn||(kn=fetch("/api/cw/editors").then(e=>e.json()).then(e=>{Bn.value=e}).catch(()=>{Bn.value={enabled:!1,editors:[]}})),kn}async function nl(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:Me(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 kt=e=>e.unpushed??e.commits??0,br={OPEN:"open",MERGED:"merged",CLOSED:"closed"},al={passing:"✓",failing:"✗",pending:"…",none:""};function rl(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=kt(e);if(a>0&&n.push(`${a} unpushed`),e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":br[e.pr.state];n.push(`PR #${e.pr.number} ${r}`),e.pr.checks!=="none"&&n.push(`checks ${al[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 ol={passing:"checks pass",failing:"checks failing",pending:"checks running",none:""},$a=(e,n)=>`${e} ${n}${e===1?"":"s"}`;function ll(e){if(e.workspace==="missing")return"not created yet";if(e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":br[e.pr.state];return[`PR #${e.pr.number} ${r}`,ol[e.pr.checks]].filter(Boolean).join(" · ")}const n=[];e.diff&&e.diff.files>0&&n.push($a(e.diff.files,"file")),e.commits&&n.push($a(e.commits,"commit"));const a=kt(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 Rt(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 ce=(e,n)=>Rt("POST",e,n),le=e=>e instanceof Error?e.message:String(e);function sn(e,n){navigator.clipboard.writeText(e).then(()=>j(`${n} copied`,"info"),()=>j(`Could not copy the ${n.toLowerCase()}`,"error"))}const il=({session:e,muted:n})=>{const a=ge(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}}),Ha(e)]})},be=Y(null),wt=Y(null),ia=Y(null),sl=6e4;let dt=null,pt=null,wn=0;function je(e=!1){return dt&&!e||(dt=fetch(`/api/kioku/status${e?"?fresh=1":""}`).then(n=>n.json()).then(n=>{JSON.stringify(n)!==JSON.stringify(be.value)&&(be.value=n)}).catch(()=>{be.value??(be.value={installed:!1,version:null,brains:[],projects:{},activity:[],viewer:null})}).finally(()=>{dt=null})),dt}async function kr(e=!1){wt.value=await Rt("GET",`/api/kioku/releases${e?"?fresh=1":""}`).catch(()=>wt.value)}async function cl(){ia.value=await Rt("GET","/api/kioku/labs").catch(()=>null)}const _n=(e=!1,n=!0)=>Promise.all([kr(e),n&&cl()]);function wr(){return wn+=1,be.value||je(),pt||(pt=setInterval(()=>{document.visibilityState==="visible"&&je()},sl)),()=>{wn-=1,wn===0&&pt&&(clearInterval(pt),pt=null)}}const re=e=>e.name??e.key,en=e=>e.reduce((n,a)=>n+a.pages,0);function sa(e){const n=be.value;return n!=null&&n.installed?(n.projects[e]??[]).flatMap(a=>n.brains.find(r=>re(r)===a.name)??[]):[]}function Sr(e){return M(()=>wr(),[]),sa(e)}const dl=({project:e})=>{const[n,a]=v(null),r=Sr(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(${Ve(o.tier)})`,border:"2px solid var(--card)",marginLeft:i===0?0:"-4px"}},o.key))}),t("span",{class:"mono",children:en(r)}),n&&co(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(ze,{color:`var(${Ve(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)]})},Kn=Y({}),Cr=Y(0),pl=6e4,Dt=new Map,$r=e=>`${e.project}::${Me(e)}`;function Un(e,n=!1){const a=$r(e),r=Dt.get(a);if(r&&!n)return r;const o=`/api/cw/review-state/${encodeURIComponent(e.project)}/${encodeURIComponent(Me(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=>(Kn.value={...Kn.value,[a]:c},Dt.get(a)===i&&Dt.delete(a),c));return Dt.set(a,i),i}function ul(){Cr.value++}function zr(e,{poll:n=!1}={}){const a=$r(e),r=Cr.value;return M(()=>{if(Un(e),!n)return;const o=setInterval(()=>{Un(e,!0)},pl);return()=>clearInterval(o)},[a,n,r]),Kn.value[a]??null}const Hn=({type:e,size:n=28,radius:a=9,font:r=11})=>{const o=na(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})},hl=()=>l("span",{class:"inline-flex items-center shrink-0",style:{gap:"5px",padding:"1px 8px",borderRadius:"99px",background:Q("--green"),color:"var(--green)",fontSize:"11px",fontWeight:600},children:[t(ze,{size:5,color:"var(--green)",live:!0,glow:!1}),"live"]}),Rr=({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})},Tr=({session:e})=>{const n=oa(e);return n&&t(Rr,{label:n.label,href:n.url})},fl=({session:e})=>oa(e)?t(Tr,{session:e}):e.source?t("span",{class:"task-chip contents",children:t(Rr,{label:e.source,href:e.source_url})}):null,jr=e=>e.type==="review"?`review/pr-${e.pr}`:e.type==="loop"?`loop/${e.task??"loop"}`:e.type==="task"?`task/${e.task}`:null,gl=({session:e,project:n})=>{var i;const a=zr(e),r=((i=a==null?void 0:a.state)==null?void 0:i.branch)??jr(e),o=a?a.error!==null?"changes unknown":ll(a.state):"checking…";return t(Pr,{branch:r,status:o,project:n})},Pr=({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(),sn(e,"Branch")},onKeyDown:r=>r.stopPropagation(),children:e}),t("span",{class:"whitespace-nowrap truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:n})]}),xl=e=>e.type==="loop"?e.loop_interval?`every ${e.loop_interval}`:"self-paced":`${e.opens} session${e.opens===1?"":"s"}`,Ar=({session:e,isOpenInTab:n,onSelect:a,onMarkDone:r,showProject:o})=>{const i=o?se(e)||"no project":void 0,[c,s]=v(!1),d=e.type==="task"||e.type==="review",f=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:g=>{g.target===g.currentTarget&&(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),a())},children:[t(Hn,{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(hl,{}),t(fl,{session:e})]}),d?t(gl,{session:e,project:i}):t(Pr,{branch:jr(e),status:xl(e),project:i})]}),t(dl,{project:se(e)}),t(il,{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:$t(e.last_opened)}),r&&t("button",{type:"button",class:`task-done grid place-items-center shrink-0 cursor-pointer transition-all duration-180 ease-spring hover:text-green disabled:cursor-wait ${c?"":"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"}`,style:{width:"28px",height:"28px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink-2)"},onClick:g=>{g.stopPropagation(),f()},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"})]})},ml=({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:se(e)})]}),t(Tr,{session:e}),t("span",{class:"mono shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:$t(e.closed??e.last_opened)})]}),vl=({project:e,account:n,accounts:a,onDeleted:r,onMoved:o})=>{const[i,c]=v(null),[s,d]=v(null),[f,g]=v(!1),[y,m]=v(!1),[w,k]=v(""),[b,p]=v(!1),x=(a??[]).filter(R=>R!==n);M(()=>{let R=!1;return fetch(`/api/cw/mcps?project=${encodeURIComponent(e)}`).then(B=>B.json()).catch(()=>null).then(B=>{R||c(B)}),()=>{R=!0}},[e]);const S=i?Object.keys(i.global):[],h=(i==null?void 0:i.project)??[],C=(i==null?void 0:i.cw)??[],u=(i==null?void 0:i.plugins)??[],z=[...h.map(R=>`${R} (project)`),...S,...C.map(R=>`${R} (CW)`)],L=R=>{d(s===R?null:R),k(""),g(!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:f})})).json()).ok&&(j(`Project "${e}" deleted${f?" (files removed)":""}`,"info"),r==null||r())}catch{j("Failed to delete project","error")}finally{m(!1),d(null)}},O=async()=>{if(w){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:w})})).json();B.ok?(j(`Project "${e}" moved to "${w}"`,"success"),d(null),k(""),o==null||o()):j(B.error??"Failed to move project","error")}catch{j("Failed to move project","error")}finally{p(!1)}}};if(!i)return null;const T={padding:"12px 15px",borderTop:"1px solid var(--hair)",display:"flex",flexDirection:"column",gap:"10px"},P=(R,B)=>({padding:"5px 11px",borderRadius:"9px",border:"1px solid var(--hair)",fontSize:"12.5px",fontWeight:500,background:B?"var(--elev)":"var(--card)",color:R==="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:[z.length>0&&l("span",{class:"truncate",title:z.join(", "),children:["MCP · ",z.join(", ")]}),u.length>0&&l("span",{class:"truncate",title:u.join(", "),children:["Plugins · ",u.join(", ")]}),z.length===0&&u.length===0&&t("span",{children:"No MCPs or plugins for this project"})]}),x.length>0&&t("button",{type:"button",class:"cursor-pointer",style:P("ink",s==="move"),"aria-expanded":s==="move",onClick:()=>L("move"),children:"Move to account"}),t("button",{type:"button",class:"cursor-pointer",style:P("red",s==="delete"),"aria-expanded":s==="delete",onClick:()=>L("delete"),children:"Delete project"})]}),s==="move"&&l("div",{style:T,children:[l("p",{style:{fontSize:"13px"},children:['Move "',e,'" to a different account.']}),l("select",{class:"field",value:w,onChange:R=>k(R.target.value),children:[t("option",{value:"",children:"Select account…"}),x.map(R=>t("option",{value:R,children:R},R))]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:b?"Moving…":"Move project",variant:"primary",size:"sm",loading:b,disabled:!w,onClick:O}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),k("")}})]})]}),s==="delete"&&l("div",{style:T,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:f,onChange:R=>g(R.target.checked)}),"Also delete project files from disk"]}),f&&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:y?"Deleting…":f?"Delete project and files":"Unregister project",variant:"destructive",size:"sm",loading:y,onClick:N}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),g(!1)}})]})]})]})},Ir=e=>e.trim().replace(/\s+/g,"-").toLowerCase();function cn(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:Ir(n)}:null}const yl="A PR link becomes a review. A Linear or Notion link becomes a dev task with its notes.";function bl(e,n){const a=cn(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:yl,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 ca=(e,n)=>{var a;return n??((a=cn(e))==null?void 0:a.type)??"dev"},we=Y(""),Ye=Y(null),Ge=Y(""),tn=Y(""),nn=e=>{we.value=e,Ye.value=null},da=(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,kl=(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":"")},wl=({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=We(e,n,s.name),f=da(s.name,d,o),g=ge(s.name),y=a===s.name,m=(d==null?void 0:d.status)==="not_logged_in",w=kl(e,s.name,d,s.name===r,f);return l("div",{role:"radio","aria-checked":y,tabIndex:f?-1:0,"aria-disabled":!!f,title:f??void 0,class:`flex items-start transition-all duration-180 ease-spring ${f?"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?Q("--blue"):"var(--card)",boxShadow:y?"var(--shadow-s)":"none",opacity:f?.45:1},onClick:()=>{f||i(s.name)},onKeyDown:k=>{!f&&(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:g.color,boxShadow:y?`0 0 8px ${g.color}`:"none"}}),l("span",{class:"flex flex-col min-w-0",children:[t("span",{style:{fontSize:"12.5px",fontWeight:600},children:g.label}),t("span",{class:"truncate",style:{fontSize:"11.5px",color:"var(--ink-2)"},title:w,children:w}),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)})})]}),Sl=({options:e,value:n,label:a,onPick:r,onClose:o})=>{const[i,c]=v(""),[s,d]=v(0),f=zt(),g=ie(null),y=i.trim().toLowerCase(),m=ee(()=>e.filter(b=>{var p;return!y||b.label.toLowerCase().includes(y)||((p=b.group)==null?void 0:p.toLowerCase().includes(y))}),[e,y]);M(()=>{const b=m.findIndex(p=>p.value===n);d(b>=0&&!y?b:0)},[y]),M(()=>{var b,p;(p=(b=g.current)==null?void 0:b.querySelector('[data-active="true"]'))==null||p.scrollIntoView({block:"nearest"})},[s]);const w=b=>{if(b.key==="ArrowDown")b.preventDefault(),d(p=>Math.min(p+1,m.length-1));else if(b.key==="ArrowUp")b.preventDefault(),d(p=>Math.max(p-1,0));else if(b.key==="Enter"){b.preventDefault();const p=m[s];p&&r(p.value)}else b.key==="Escape"&&(b.preventDefault(),b.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:w,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:f,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:b=>c(b.target.value)})]}),l("div",{ref:g,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((b,p)=>{const x=b.group&&b.group!==k?b.group:null;k=b.group;const S=p===s,h=b.value===n;return l("div",{children:[x&&t("div",{style:{padding:"7px 9px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:x}),l("button",{type:"button",role:"option","aria-selected":h,"data-active":S,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"8px",padding:"6px 9px",borderRadius:"8px",border:0,background:S?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px"},onMouseMove:()=>{S||d(p)},onClick:()=>r(b.value),children:[t("span",{class:"flex-1 truncate",style:{fontWeight:h?600:400,color:b.value?"var(--ink)":"var(--ink-2)"},children:b.label}),h&&t("span",{class:"i-lucide-check shrink-0",style:{width:"13px",height:"13px",color:"var(--blue)"}})]})]},b.value||"__empty")})]})]})},Lr=({label:e,value:n,options:a,onChange:r,placeholder:o="Choose…",size:i="sm",width:c})=>{const[s,d]=v(!1),f=ie(null),g=a.find(m=>m.value===n);return M(()=>{if(!s)return;const m=w=>{f.current&&!f.current.contains(w.target)&&d(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[s]),l("div",{ref:f,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:g&&g.value?"var(--ink)":"var(--ink-2)"},children:(g==null?void 0:g.label)??o}),t("span",{class:"i-lucide-chevrons-up-down shrink-0",style:{width:"12px",height:"12px",color:"var(--ink-3)"}})]}),s&&t(Sl,{options:a,value:n,label:e,onPick:m=>{r(m),d(!1)},onClose:()=>d(!1)})]})},qn=(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}))},Er=({ctx:e,size:n="md"})=>{const{text:a,ready:r}=bl(we.value,{...e,harness:ge(e.harness).label}),o=r&&(e.type==="general"||cn(we.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:Q("--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})]})},Nr=({fill:e})=>t(de,{fill:e,label:"Task type",tabs:Xe.map(n=>({id:n.key,label:aa(n.key)})),active:ca(we.value,Ye.value),onChange:n=>{Ye.value=n}}),Cl={width:"auto",maxWidth:"180px",height:"30px",padding:"0 26px 0 10px",borderRadius:"9px",fontSize:"12.5px",background:"var(--bg-2)"},$l=({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:Cl,value:n,onChange:o=>a(o.target.value),children:r.map(o=>t("option",{value:o.value,children:o.label},o.value))})]}),zl=({projects:e,accounts:n,onStarted:a,onOpenDrawer:r})=>{var h,C;const[o,i]=v(!1),c=ln.value,s=c!=null&&c.available?c.doctor:null,d=ca(we.value,Ye.value),f=d==="general",g=Ge.value,y=Object.keys(e).sort(),m=f?tn.value||((h=e[g])==null?void 0:h.account)||n[0]||"":((C=e[g])==null?void 0:C.account)??"",w=y.filter(u=>e[u].account===m),k=d==="loop"?"claude":s?qa(g||void 0,m,e,s):"claude",b=we.value.trim(),p=o||(f?!m:!b||!g),x=async()=>{if(p)return;const u=s?We(s,m,k):void 0,z=s?da(k,u,d==="loop"):null,L=!f&&vr(c,k,b);if(d==="loop"||z||L||(u==null?void 0:u.status)==="not_logged_in"){r();return}i(!0);try{const T=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f?{type:d,account:m,project:g||void 0,harness:s?k:void 0}:{type:d,project:g,task:b,account:m||void 0,harness:s?k:void 0})})).json();T.ok?(j(f?"Session started":d==="review"?"Review started":"Task started","success"),f||nn(""),a(T.session)):j(T.error??"Failed to start","error")}catch{j("Failed to start","error")}finally{i(!1)}},S=u=>{var z;tn.value=u,g&&((z=e[g])==null?void 0:z.account)!==u&&(Ge.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:f?"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:we.value,onInput:u=>nn(u.target.value),onKeyDown:u=>{u.key==="Enter"&&x()}}),t(Nr,{}),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 x(),children:o?"Starting…":f?"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(Er,{ctx:{type:d,project:g,account:m,harness:k}})}),f&&t($l,{label:"Account",value:m,onChange:S,options:n.map(u=>({value:u,label:u}))}),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(Lr,{label:"Project",value:g,onChange:u=>{Ge.value=u},placeholder:f?"No project":"Choose…",options:f?[{value:"",label:"No project"},...qn(e,n,w)]:qn(e,n,y)})]})]})]})},et=({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(pa,{}),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})]}),Rl=({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]}),pa=()=>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:()=>{Te.value=!0},children:t("span",{class:"i-lucide-menu",style:{width:"15px",height:"15px"}})}),Gn=Y({}),za=new Set;function Tl(e){!e||za.has(e)||(za.add(e),fetch(`/api/cw/detect/${encodeURIComponent(e)}`).then(n=>n.ok?n.json():null).catch(()=>null).then(n=>{Gn.value={...Gn.value,[e]:n}}))}const Or=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 Wr(e){return M(()=>{Tl(e)},[e]),Gn.value[e]}const Ra=10,Dr="forge-task-layout",jl=()=>{try{return localStorage.getItem(Dr)==="project"?"project":"recent"}catch{return"recent"}},Vt={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",overflow:"hidden"},Jt={padding:"11px 15px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},Pl=({project:e,account:n,sessions:a,index:r,openTabKeys:o,onSelectTask:i,onMarkDone:c})=>{const s=Or(Wr(e)),d=a.some(f=>o.has(G(f)));return l("section",{style:{...Vt,animation:`riseIn .4s var(--ease) ${r*70}ms both`},"aria-label":e||"No project",children:[l("div",{class:"flex items-center flex-wrap",style:{...Jt,gap:"10px"},children:[t(ze,{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(f=>t(Ar,{session:f,isOpenInTab:o.has(G(f)),onSelect:()=>i(f),onMarkDone:f.type==="login"?void 0:()=>c(f)},G(f)))]})},Al=({spaces:e,allSpaces:n,projects:a,accountNames:r,filterAccount:o,filterProject:i,onFilterProject:c,filterType:s,onFilterType:d,harnessNames:f,filterHarness:g,onFilterHarness:y,showDone:m,onShowDone:w,openTabKeys:k,onSelectTask:b,onMarkDone:p,onNewTask:x,onCreateProject:S,onRefresh:h,onStarted:C})=>{var q,he;const[u,z]=v(jl),L=E=>{z(E);try{localStorage.setItem(Dr,E)}catch{}},N=ee(()=>e.filter(E=>E.status==="active"),[e]),O=ee(()=>e.filter(E=>E.status==="done"),[e]),T=ee(()=>n.filter(E=>E.status==="active").length,[n]),P=ee(()=>n.filter(E=>E.status==="done").length,[n]),R=ee(()=>n.filter(E=>E.status==="active"&&k.has(G(E))).length,[n,k]),B=ee(()=>n.filter(E=>E.status==="active"&&(!o||E.account===o)&&(!i||E.project===i)&&(!g||(E.harness??"claude")===g)),[n,o,i,g]),A=ee(()=>{const E=new Map;for(const Z of N){const te=se(Z),Se=E.get(te)??[];Se.push(Z),E.set(te,Se)}return Array.from(E,([Z,te])=>({project:Z,sessions:te}))},[N]),D=i?((q=a[i])==null?void 0:q.account)??((he=N[0])==null?void 0:he.account):void 0,F=i?`${D?`${D} · `:""}${B.length} active`:`${T} active · ${P} done · ${R} agent${R===1?"":"s"} working`;return l(H,{children:[l(et,{title:i??"Tasks",subtitle:F,children:[t(I,{label:"Add project",variant:"secondary",onClick:S}),t(I,{label:"New task",variant:"primary",onClick:x})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"16px",maxWidth:"1180px"},children:[t(zl,{projects:a,accounts:r,onStarted:C,onOpenDrawer:x}),l("div",{class:"flex items-center flex-wrap",style:{gap:"12px"},children:[t(de,{label:"Filter by type",tabs:[{id:"all",label:"All",count:B.length},...Xe.map(E=>({id:E.key,label:aa(E.key),count:B.filter(Z=>Z.type===E.sessionType).length}))],active:s??"all",onChange:E=>d(E==="all"?null:E)}),f.length>1&&t(de,{label:"Filter by harness",tabs:[{id:"all",label:"Any harness"},...f.map(E=>({id:E,label:ge(E).label}))],active:g??"all",onChange:E=>y(E==="all"?null:E)}),t("span",{class:"flex-1"}),!i&&t(de,{size:"sm",label:"Order tasks",tabs:[{id:"recent",label:"Recent"},{id:"project",label:"By project"}],active:u,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:()=>w(!m),children:m?"Hide done":"Show done"})]}),i&&t(vl,{project:i,account:D,accounts:r,onDeleted:()=>{c(null),h()},onMoved:h}),u==="recent"&&!i&&N.length>0&&l("section",{style:{...Vt,animation:"riseIn .4s var(--ease) both"},"aria-label":"Recently opened",children:[l("div",{class:"flex items-center",style:{...Jt,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(Ar,{session:E,showProject:!0,isOpenInTab:k.has(G(E)),onSelect:()=>b(E),onMarkDone:E.type==="login"?void 0:()=>p(E)},G(E)))]}),(u==="project"||i)&&A.map((E,Z)=>{var te;return t(Pl,{project:E.project,account:((te=a[E.project])==null?void 0:te.account)??E.sessions[0].account,sessions:E.sessions,index:Z,openTabKeys:k,onSelectTask:b,onMarkDone:p},E.project)}),A.length===0&&l("section",{style:{...Vt,animation:"riseIn .4s var(--ease) both"},children:[i&&l("div",{class:"flex items-center",style:{...Jt,gap:"10px"},children:[t(ze,{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||g?"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:x})]})]}),m&&O.length>0&&l("section",{style:{...Vt,boxShadow:"var(--shadow-s)"},"aria-label":"Done",children:[l("div",{style:{...Jt,padding:"10px 15px",fontSize:"13px",fontWeight:600,color:"var(--ink-2)"},children:["Done · last ",Math.min(Ra,O.length)," of ",O.length]}),O.slice(0,Ra).map(E=>t(ml,{session:E,onSelect:()=>b(E)},G(E)))]})]})]})},De={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"},Qe="inline-flex items-center gap-1 cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m hover:text-ink",Mr={...De,color:"var(--ink-3)",boxShadow:"none"},Fr=({href:e,title:n,children:a})=>l("a",{class:Qe,style:De,href:e,target:"_blank",rel:"noopener noreferrer",title:n,children:[a," ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),Il=({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:Mr,disabled:!0,title:r,children:["GitHub ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]})}return t(Fr,{href:n.url,title:n.label,children:"GitHub"})},Ll=({session:e})=>{const n=oa(e);return n&&t(Fr,{href:n.url,title:n.url,children:n.label})},El=({session:e,entry:n})=>{var f;const[a,r]=v(!1),o=ie(null);M(()=>{yr()},[]),M(()=>{if(!a)return;const g=y=>{o.current&&!o.current.contains(y.target)&&r(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a]);const i=Bn.value,c=i!=null&&i.enabled?i.editors:[];if(c.length===0)return null;const s=(f=n==null?void 0:n.state)==null?void 0:f.workspace;if(s!=="ready")return l("button",{type:"button",class:"cursor-not-allowed",style:Mr,disabled:!0,title:n?s==="missing"?"Workspace not created yet":"This session has no worktree":"Checking the worktree…",children:["Open in ",c.length===1?c[0].label:"editor"]});const d=async g=>{r(!1);try{await nl(e,g)}catch(y){j(y.message,"error")}};return c.length===1?l("button",{type:"button",class:Qe,style:De,onClick:()=>d(c[0].id),children:["Open in ",c[0].label]}):l("div",{class:"relative",ref:o,children:[l("button",{type:"button",class:Qe,style:De,"aria-expanded":a,onClick:()=>r(g=>!g),children:["Open in editor ",t("span",{class:"i-lucide-chevron-down",style:{width:"12px",height:"12px"}})]}),a&&t("div",{class:"popover absolute right-0 top-full z-30 flex flex-col",style:{marginTop:"6px",minWidth:"160px",padding:"5px",borderRadius:"12px"},children:c.map(g=>t("button",{type:"button",class:"text-left cursor-pointer hover:bg-elev",style:{padding:"7px 10px",borderRadius:"8px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>d(g.id),children:g.label},g.id))})]})},Nl={"--orange":"--red","--blue":"--purple","--purple":"--blue","--green":"--teal"},ut=({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)"}})})]}),Ol=({value:e,onChange:n,onSend:a,onCancel:r})=>{const o=zt();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})]})},Wl=({session:e,onOpen:n})=>{const a=se(e),r=Sr(a),[o,i]=v(null);if(r.length===0)return null;const c=e.harness==="claude"&&e.status==="active",s=async()=>{if(o!=null&&o.trim())try{await ce("/api/kioku/remember",{project:a,sessionDir:Me(e),text:o}),j("Sent to the agent to remember","success"),i(null)}catch(d){j(le(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 · ",en(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(Ol,{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,f)=>l("span",{class:"inline-flex items-center",style:{gap:"4px"},children:[f>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:Q(Ve(d.tier)),color:`var(${Ve(d.tier)})`},title:`${d.tier??"brain"} · ${d.pages} pages`,onClick:()=>n==null?void 0:n(a),children:re(d)})]},d.key))})]})},Sn=({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?Q(a):"var(--elev)",color:a&&!o.muted?`var(${a})`:"var(--ink-2)",opacity:o.muted?.6:1},children:o.name},o.name))]})]}),Dl=({session:e,active:n,onDone:a,onOpenMemory:r})=>{const[o,i]=v(""),[c,s]=v(!1),[d,f]=v(!1),[g,y]=v(0),[m,w]=v(null),[k,b]=v(!1),p=G(e),x=Me(e),S=e.type==="task"||e.type==="review",h=zr(e,{poll:n&&e.type==="task"}),C=na(e.type),u=e.type==="login",z=Or(Wr(u?"":se(e))),L=er(p).value,N=encodeURIComponent(e.project),O=encodeURIComponent(x),P=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal/${N}/${O}?k=${g}`;M(()=>{if(u)return;let E=!1;return Promise.all([fetch(`/api/cw/tools?project=${N}`).then(Z=>Z.json()).catch(()=>null),fetch(`/api/cw/git/branch/${N}/${O}`).then(Z=>Z.json()).catch(()=>null)]).then(([Z,te])=>{E||(Z&&w(Z),i((te==null?void 0:te.branch)||e.task||e.pr||""))}),()=>{E=!0}},[p]);const R=()=>{s(!1),y(E=>E+1)},B=(m==null?void 0:m.mcps)??[],A=(m==null?void 0:m.plugins)??[],D=(h==null?void 0:h.state)??null,F=(D==null?void 0:D.branch)??o,q=h?h.error!==null?"Changes unknown":rl(h.state):"Checking changes…",he=[se(e)||"no project",e.account,[Ha(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(${C.token}), var(${Nl[C.token]??C.token}))`,boxShadow:"var(--shadow-m)",color:"#fff",fontSize:"13px",fontWeight:700},"aria-hidden":"true",children:C.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:he}),!u&&t("p",{class:"mono truncate",style:{marginTop:"2px",fontSize:"11.5px",color:"var(--ink-3)"},title:q,children:q})]}),t("span",{style:{flex:"1 1 60px"}}),l("div",{class:"flex flex-wrap items-center",style:{gap:"7px"},children:[!u&&t("button",{type:"button",class:Qe,style:De,"aria-expanded":k,onClick:()=>b(E=>!E),children:k?"Hide context":`Context · ${B.length} MCP, ${A.length} plugins`}),!u&&t(Ll,{session:e}),!u&&t(Il,{entry:h}),!u&&t(El,{session:e,entry:h}),c&&t(I,{label:"Restart",variant:"secondary",size:"sm",onClick:R}),e.status==="active"&&!u&&t(I,{label:"Mark done",variant:"primary",size:"sm",onClick:a})]})]}),!u&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(138px, 1fr))",gap:"9px"},children:[t(ut,{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(ut,{index:1,label:"Tokens",children:(L==null?void 0:L.tokens)!=null?tr(L.tokens):"—"}),t(ut,{index:2,label:"Cost",color:"var(--green)",children:(L==null?void 0:L.cost)!=null?nr(L.cost):"—"}),S&&t(ut,{index:3,label:"Commits",children:(D==null?void 0:D.commits)??"—"}),S&&t(ut,{index:4,label:"Unpushed",color:D&&kt(D)>0?"var(--orange)":"var(--ink)",children:D?kt(D):"—"}),t(Wl,{session:e,onOpen:r}),F&&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:()=>sn(F,"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:F})]})]}),k&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:"9px",animation:"riseIn .3s var(--ease) both"},children:[t(Sn,{title:`MCP · ${B.length}`,tone:"--blue",empty:"No MCP servers",items:B.map(E=>({name:E.name,title:`${E.type} · ${E.source}`}))}),t(Sn,{title:`Plugins · ${A.length}`,tone:"--green",empty:"No plugins",items:A.map(E=>({name:E.name,muted:!E.enabled,title:`${E.enabled?"enabled":"disabled"} · ${E.marketplace}${E.hasMcp?` · MCP ${E.mcpName??""}`:""}`}))}),t(Sn,{title:"Stack",tone:null,empty:"Nothing detected",items:z.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:[F||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(so,{wsUrl:P,theme:Ct.value,focused:n,onOutput:E=>Ao(p,E),onExit:()=>s(!0),onGiveUp:()=>s(!0),onConnectionChange:f}),!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…"})})]})]})})]})},ve={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:ve,children:e}),a]}),Ml={dev:"New dev task",review:"Review a pull request",loop:"New loop",general:"New session"},Fl={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."},Bl={dev:"Task name or ticket URL",review:"Pull request number or URL",loop:"Loop prompt",general:""},_l={dev:"fix-auth or https://linear.app/…",review:"42 or https://github.com/…/pull/42",loop:"Babysit my open PRs…",general:""},Kl=[{id:"",label:"Auto"},{id:"feature",label:"feature"},{id:"bugfix",label:"bugfix"},{id:"refactor",label:"refactor"}],Cn={boxShadow:"var(--shadow-s)"},Mt=e=>/^[\w./:#-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Ul=({projects:e,accounts:n,initialAccount:a,initialProject:r,onClose:o,onCreated:i,onOpenAccounts:c})=>{var Nt;const s=ca(we.value,Ye.value),[d,f]=v(""),[g,y]=v(""),[m,w]=v(""),[k,b]=v(""),[p,x]=v(""),[S,h]=v(!1),[C,u]=v(!1),[z,L]=v(""),[N,O]=v("claude"),T=zt();M(()=>{ye()},[]);const P=ln.value,R=P!=null&&P.available?P.doctor:null,B=Object.keys(e),A=s==="general",D=s==="review",F=s==="loop",q=we.value,he=!z.trim()||/^\d+[smh]$/.test(z.trim()),E=n.length>0?n:Array.from(new Set(Object.values(e).map(_=>_.account).filter(Boolean))).sort(),Z=d?B.filter(_=>{var $;return(($=e[_])==null?void 0:$.account)===d}):B;M(()=>{const _=r&&!a&&e[r]?e[r].account:void 0,$=a??_,W=$&&E.includes($)?$:E[0]??"";f(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:!A&&K.length>0?K[0]:"";V&&y(V)},[]);const te=ie(!1);M(()=>{if(!te.current){te.current=!0;return}!A&&!g&&Z.length>0&&y(Z[0])},[A]);const Se=_=>{f(_);const $=B.filter(W=>{var K;return((K=e[W])==null?void 0:K.account)===_});!A&&$.length>0&&!$.includes(g)?y($[0]):A&&g&&!$.includes(g)&&y("")},jt=R?qa(g||void 0,d,e,R):"claude";M(()=>{!R||!d||O(F?"claude":jt)},[P==null?void 0:P.available,d,g,F]);const Ce=R?We(R,d,N):void 0,Pt=!R||qe(P,N,"skip_permissions"),$e=!R||N==="claude",Be=$e||!A,xe=R?da(N,Ce,F):null,At=ge(N).label;M(()=>{Pt||h(!1),x($e?"":(Ce==null?void 0:Ce.model)??"")},[N]),M(()=>{$e||x((Ce==null?void 0:Ce.model)??"")},[d]);const It=mr(q),tt=vr(P,N,q),Lt=!A&&!q.trim()||F&&!he||!A&&!g||!!xe,Et=async()=>{if(!Lt){u(!0);try{const _={type:s,account:d||void 0,skipPermissions:S||void 0};R&&(_.harness=N),F?(_.project=g,_.loopPrompt=q.trim(),_.loopInterval=z.trim()||void 0):A?g&&(_.project=g):(_.project=g,_.task=q.trim(),_.description=m.trim()||void 0,_.workflow=k||void 0),_.model=Be&&p||void 0;const W=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)})).json();W.ok?(j(A?"Session started":F?"Loop started":"Task started","success"),A||nn(""),i(W.session)):j(W.error??"Failed to start","error")}catch{j("Failed to start","error")}finally{u(!1)}}},hn=d||E[0]||"default",fn=A?`cw launch ${Mt(hn)}`:F?`cw loop ${g||"<project>"} ${Mt(q.trim()||"<prompt>")}${z.trim()?` --every ${z.trim()}`:""}`:D?`cw review ${g||"<project>"} ${Mt(q.trim()||"<pr>")}`:`cw work ${g||"<project>"} ${q.trim()?Mt(((Nt=cn(q))==null?void 0:Nt.kind)==="name"?Ir(q):q.trim()):"<task>"}`;return l(Ze,{title:Ml[s],onClose:o,children:[t(Nr,{fill:!0}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",lineHeight:1.5},children:Fl[s]}),!A&&l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t(U,{label:Bl[s],children:t("input",{class:"field",style:{...Cn,fontSize:"14px"},placeholder:_l[s],value:q,ref:T,onInput:_=>{const $=_.target.value;F?we.value=$:nn($)},onKeyDown:_=>{_.key==="Enter"&&Et()}})}),!F&&t(Er,{ctx:{type:s,project:g,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 $=_.target.value;Se($),tn.value=$},children:E.map(_=>t("option",{value:_,children:_},_))})}),t(U,{plain:!0,label:A?"Project · optional":"Project",children:t(Lr,{label:"Project",size:"md",width:"100%",value:g,placeholder:A?"No project":"Choose…",onChange:_=>{y(_),Ge.value=_},options:[...A?[{value:"",label:"No project"}]:[],...qn(e,E,Z)]})})]}),F&&l(U,{label:"Interval · optional",children:[t("input",{class:"field mono",style:{...Cn,borderColor:he?void 0:"var(--red)"},value:z,placeholder:"auto — Claude decides the pace",onInput:_=>L(_.target.value)}),!he&&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:Cn,placeholder:"Context the agent reads first…",value:m,onInput:_=>w(_.target.value)})}),R&&t(wl,{doctor:R,account:d,value:N,defaultHarness:jt,isLoop:F,onChange:O,onOpenAccounts:c}),Be&&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:ve,children:"Model"}),$e?t(de,{fill:!0,size:"sm",label:"Model",tabs:bo.map(_=>({id:_.id,label:_.label})),active:p,onChange:x}):t("input",{class:"field mono",style:{height:"32px",fontSize:"12.5px"},value:p,placeholder:"the account's model","aria-label":"Model",onInput:_=>x(_.target.value)})]}),s==="dev"&&l("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:ve,children:"Workflow"}),t(de,{fill:!0,size:"sm",label:"Workflow",tabs:Kl,active:k,onChange:b})]})]}),Pt&&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(rn,{checked:S,onChange:h,label:"Bypass permissions"})]}),tt&&l("p",{style:{fontSize:"12.5px",padding:"10px 12px",borderRadius:"12px",background:Q("--orange"),color:"var(--ink)"},children:[At," has no MCP and CW has no ",It==="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:C?"Starting…":A?"Launch session":F?"Start loop":D?"Start review":"Start task",variant:"primary",size:"lg",block:!0,loading:C,disabled:Lt,onClick:Et}),xe&&t("p",{style:{fontSize:"12px",color:"var(--red)",textAlign:"center"},children:xe}),t("p",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)",textAlign:"center",overflowWrap:"anywhere"},children:fn})]})},ua=e=>`/api/skills/plugins/${encodeURIComponent(e)}`;async function dn(e,n){try{return await ce(e,n)}catch(a){return j(le(a),"error"),null}}const Ee=Y(null),Vn=Y(null);async function pn(){const e=await fetch("/api/skills/plugins");if(!e.ok)throw new Error("fetch failed");Ee.value=await e.json()}async function Jn(){const e=await fetch("/api/skills/marketplaces");if(!e.ok)throw new Error("fetch failed");Vn.value=await e.json()}const Fe=({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]}),Ie={fontSize:"11.5px",color:"var(--ink-3)"},Hl={fontSize:"11.5px",fontWeight:600,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},ql=e=>{const n=e.indexOf(" ");return n<0?{name:e,hint:""}:{name:e.slice(0,n),hint:e.slice(n+1).trim()}},Yt=e=>`${e.project}::${Me(e)}`;function Gl(e,n){var o;const a=new Set((o=(Ee.value??[]).find(i=>i.name===n))==null?void 0:o.installs.filter(i=>i.scope==="account"&&i.enabled).map(i=>i.scopeRef)),r=Ae.value;return e.filter(i=>i.harness==="claude"&&i.status==="active"&&a.has(i.account)&&r[Yt(i)])}const Vl=({command:e,plugin:n,note:a,onClose:r})=>{const{name:o,hint:i}=ql(e),[c,s]=v(null),[d,f]=v(null),[g,y]=v(""),[m,w]=v(!1);M(()=>{Promise.all([Rt("GET","/api/cw/spaces"),Ee.value?null:pn()]).then(([C])=>s(C),()=>s([]))},[]);const k=c?Gl(c,n):[],b=k.find(C=>Yt(C)===d)??k[0],p=g.trim()?`${o} ${g.trim()}`:o,x=i.startsWith("<")&&!g.trim(),h=l(H,{children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:r}),t(I,{label:m?"Sending…":"Run",variant:"primary",disabled:!b||x||m,onClick:async()=>{if(b){w(!0);try{await ce("/api/cw/terminal/command",{project:b.project,sessionDir:Me(b),line:p}),j(`Sent ${o} to ${ue(b)}`,"success"),r()}catch(C){j(le(C),"error")}finally{w(!1)}}}})]});return t(Re,{open:!0,title:`Run ${o}`,onClose:r,footer:h,children:l("div",{class:"flex flex-col",style:{gap:"12px",fontSize:"13px"},children:[i&&l("label",{class:"flex flex-col",style:{gap:"4px"},children:[l("span",{style:Ie,children:[o," ",i]}),t("input",{type:"text",class:"field",value:g,placeholder:i.replace(/[<>[\]]/g,""),onInput:C=>y(C.target.value)})]}),c===null&&t("p",{style:Ie,children:"Looking for open sessions…"}),c&&k.length===0&&l("p",{style:Ie,children:["No Claude Code session of an account with ",n," is open in Forge. Start one from Tasks, then run it here."]}),k.length>0&&l("div",{class:"flex flex-col",style:{gap:"4px"},children:[t("span",{style:Ie,children:"Session"}),k.map(C=>l("label",{class:"flex items-center cursor-pointer",style:{gap:"8px"},children:[t("input",{type:"radio",name:"session",checked:b===C,onChange:()=>f(Yt(C))}),t("span",{style:{fontWeight:500},children:ue(C)}),t("span",{style:Ie,children:[se(C),C.account].filter(Boolean).join(" · ")})]},Yt(C)))]}),t("code",{style:{fontSize:"11.5px",color:"var(--ink-2)"},children:p}),a&&t("p",{style:Ie,children:a}),t("p",{style:Ie,children:"Forge types it into the session's terminal, as if you had."})]})})},Br=({command:e,plugin:n,note:a,disabled:r})=>{const[o,i]=v(!1);return l(H,{children:[t("button",{type:"button",style:{...Hl,opacity:r?.5:1,cursor:r?"default":"pointer"},disabled:r,onClick:()=>i(!0),children:"Run…"}),o&&t(Vl,{command:e,plugin:n,note:a,onClose:()=>i(!1)})]})};function Jl(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 Yl(e){return`add-skill-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,30).replace(/-+$/,"")||Date.now()}`}function Ql(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
- `)}async function _r(e,n,a){await dn("/api/skills/plugins/install",{id:e,account:a})&&(j(`${n} installed in ${a} · applies to new sessions`,"success"),await Promise.all([pn(),Jn()]).catch(()=>{}))}const Kr=(e,n)=>n?e.skills.filter(a=>a.name.toLowerCase().includes(n)||a.description.toLowerCase().includes(n)):e.skills,Zl={padding:"6px 11px",fontSize:"11px",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase",color:"var(--ink-3)"},Xl=e=>/^[0-9a-f]{12,}$/.test(e)?e.slice(0,7):e,ei=e=>{var n;return(n=e.installs.find(a=>a.update))==null?void 0:n.latest},ti=({list:e,query:n,selected:a,onSelect:r})=>{const o=e.filter(c=>!n||Kr(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(H,{children:[...i].map(([c,s])=>l("div",{style:{marginBottom:"8px"},children:[t("p",{class:"truncate",style:Zl,children:c}),s.map(d=>{const f=a===d.id,g=ei(d),y=[...new Set(d.installs.map(m=>Xl(m.version)))].join(" · ");return l("button",{type:"button","aria-current":f?"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 ${f?"var(--hair)":"transparent"}`,background:f?"var(--card)":"transparent",boxShadow:f?"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}),g&&l("span",{class:"mono shrink-0",title:`Update to ${g} 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:["↑ ",g]})]}),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))})},$n={fontSize:"12px",fontWeight:600,color:"var(--ink-2)",margin:"0 0 8px"},Ur={gap:"10px",padding:"9px 12px",borderRadius:"11px",border:"1px solid var(--hair)",background:"var(--card)"},ni=({plugin:e,install:n})=>{const[a,r]=v(!1),o=n.scope==="global"?"global":n.scopeRef,i=async()=>{r(!0);const s=await dn(`${ua(e.id)}/update`,{scope:n.scope,scopeRef:n.scopeRef});r(!1),s&&(j(`${e.name} ${s.version??""} · applies to new sessions`,"success"),pn().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:Ur,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(I,{label:a?"Updating…":n.update?`Update to ${n.latest}`:"Check & update",variant:n.update?"primary":"secondary",size:"sm",loading:a,onClick:i})]})},ai=({plugin:e,account:n})=>{const[a,r]=v(!1);return l("div",{class:"flex items-center",style:Ur,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 _r(e.id,e.name,n),r(!1)}})]})},ri=({plugin:e,name:n,onBack:a})=>{const[r,o]=v(null),[i,c]=v(!1);return M(()=>{let s=!1;return o(null),c(!1),fetch(`${ua(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(H,{children:[t(Fe,{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})]})]})},oi=({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(H,{children:[l(Fe,{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:$n,children:"Accounts · versions"}),l("div",{class:"flex flex-col",style:{gap:"6px"},children:[e.installs.map(s=>t(ni,{plugin:e,install:s},`${s.scope}/${s.scopeRef}`)),c.map(s=>t(ai,{plugin:e,account:s},s))]})]}),e.commands.length>0&&l("section",{children:[l("h3",{style:$n,children:["Commands (",e.commands.length,")"]}),t("div",{class:"flex flex-col",style:{gap:"4px"},children:e.commands.map(s=>l("div",{class:"flex items-center",style:{gap:"10px",padding:"8px 11px"},children:[l("span",{class:"mono shrink-0",style:{fontSize:"12.5px",fontWeight:600},children:[s.name,s.argumentHint?` ${s.argumentHint}`:""]}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:s.description}),t(Br,{command:s.argumentHint?`${s.name} ${s.argumentHint}`:s.name,plugin:e.name})]},s.name))})]}),l("section",{children:[l("h3",{style:$n,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:Kr(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))})]})]})})]})},li=({accounts:e})=>{const[n,a]=v(""),r=e.includes(n)?n:e[0]??"",[o,i]=v(""),[c,s]=v(""),[d,f]=v(""),[g,y]=v(!1),[m,w]=v(null);M(()=>{Vn.value===null&&Jn().catch(()=>j("Failed to load marketplaces","error"))},[]);const k=Vn.value,b=(k==null?void 0:k.find(u=>u.name===o))??(k==null?void 0:k[0]),p=new Set((Ee.value??[]).flatMap(u=>u.installs.some(z=>z.scope==="account"&&z.scopeRef===r)?[u.id]:[])),x=c.trim().toLowerCase(),S=((b==null?void 0:b.plugins)??[]).filter(u=>!x||u.name.toLowerCase().includes(x)||u.description.toLowerCase().includes(x)),h=async()=>{y(!0);const u=await dn("/api/skills/marketplaces",{source:d.trim(),account:r});y(!1),u&&(j(`Marketplace added to ${r}`,"success"),f(""),await Jn().catch(()=>{}))},C=async(u,z)=>{w(u),await _r(u,z,r),w(null)};return l(H,{children:[t(Fe,{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:u=>a(u.target.value),children:e.map(u=>t("option",{value:u,children:u},u))})}),k&&k.length>0&&t(U,{label:"Marketplace",children:t("select",{class:"field",value:b==null?void 0:b.name,onChange:u=>i(u.target.value),children:k.map(u=>l("option",{value:u.name,children:[u.name," · ",u.source]},u.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:u=>f(u.target.value),onKeyDown:u=>{u.key==="Enter"&&d.trim()&&h()}}),t(I,{label:g?"Adding…":"Add",variant:"secondary",size:"sm",loading:g,disabled:!d.trim()||!r,onClick:h})]})}),b&&b.plugins.length>0&&t("input",{class:"field",type:"search","aria-label":"Filter plugins",value:c,placeholder:`Filter ${b.plugins.length} plugins`,onInput:u=>s(u.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."}),b&&S.length===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:x?"No plugin matches.":"This marketplace lists no plugins."}),S.map((u,z)=>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(z,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:u.name}),u.category&&t("span",{class:"mono shrink-0",style:{fontSize:"11px",color:"var(--ink-3)"},children:u.category})]}),u.description&&t("div",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-2)"},title:u.description,children:u.description})]}),p.has(u.id)?t("span",{style:{fontSize:"12px",color:"var(--green)"},children:"Installed"}):t(I,{label:m===u.id?"Installing…":"Install",variant:"secondary",size:"sm",loading:m===u.id,disabled:m!==null||!r,onClick:()=>C(u.id,u.name)})]},u.id))]})]})},ii=({plugin:e,accounts:n,onSubmit:a,onCancel:r})=>{const o=Jl(e),i=e.installs.filter(p=>p.scope==="account").map(p=>p.scopeRef),c=n.find(p=>i.includes(p))??n[0]??"",[s,d]=v(""),[f,g]=v(o[0]??""),[y,m]=v(c),[w,k]=v(!1),b=async()=>{k(!0);try{await a(s.trim(),o.length>1?f:void 0,y)}finally{k(!1)}};return l(H,{children:[t(Fe,{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:f,onChange:p=>g(p.target.value),children:o.map(p=>t("option",{value:p,children:p},p))})}),n.length>0&&t(U,{label:"Account",children:t("select",{class:"field",value:y,onChange:p=>m(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(I,{label:w?"Starting…":"Start task",variant:"primary",loading:w,disabled:!s.trim()||!y,onClick:b}),t(I,{label:"Cancel",variant:"secondary",onClick:r})]})]})})]})},si={global:"--blue",account:"--orange",project:"--green"},Ft=e=>`${e.scope}/${e.scopeRef}/${e.dirName}`;function ci(e,n){return e==="global"?"global":e==="account"?`account/${encodeURIComponent(n)}`:`project/${encodeURIComponent(n)}`}const gt=e=>e.scope==="global"?"Global":`${e.scope==="account"?"Account":"Project"} · ${e.scopeRef}`,di=e=>e.scope==="global"?`~/.claude/skills/${e.dirName}`:e.scope==="account"?`~/.cw/accounts/${e.scopeRef}/skills/${e.dirName}`:`<${e.scopeRef}>/.claude/skills/${e.dirName}`,pi={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."},Hr=e=>e[0]?{scope:"account",scopeRef:e[0]}:{scope:"global",scopeRef:"global"},Yn=e=>e.scope==="global"||e.scopeRef!=="",qr=({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(H,{children:[l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:ve,children:"Scope"}),t(de,{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:pi[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))})})]})},ui=(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),Gr=(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(...Gr(o,n+" "))):a.push(`${n}${r}: ${String(o??"")}`);return a},hi=({skill:e,accounts:n,projects:a,onDeleted:r,onCopied:o,onRun:i})=>{const[c,s]=v(null),[d,f]=v(!0),[g,y]=v("SKILL.md"),[m,w]=v(""),[k,b]=v({}),[p,x]=v(!1),S=`/api/skills/${ci(e.scope,e.scopeRef)}/${encodeURIComponent(e.dirName)}`;M(()=>{let T=!1;return f(!0),y("SKILL.md"),fetch(S).then(P=>{if(!P.ok)throw new Error("fetch failed");return P.json()}).then(P=>{if(T)return;s(P);const R=Gr(P.frontmatter);w(R.length>0?`---
1
+ var no=Object.defineProperty;var ao=(e,n,a)=>n in e?no(e,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[n]=a;var ga=(e,n,a)=>ao(e,typeof n!="symbol"?n+"":n,a);import{jsxs as l,jsx as t,Fragment as H}from"preact/jsx-runtime";import{Fragment as ro,Component as oo,render as lo}from"preact";import{useState as v,useMemo as ee,useEffect as D,useRef as ie,useCallback as J}from"preact/hooks";import{signal as Y,computed as Ba}from"@preact/signals";import{ToastContainer as io,Tabs as de,UsageMeter as _a,ToggleSwitch as cn,showToast as j,ActionButton as I,ForgeTerminal as so,Drawer as Ze,Modal as Re,EmptyState as Oe,Badge as He}from"@forge-dev/ui";import{createPortal as co}from"preact/compat";import{definePanel as po,ModuleRequestError as Xt}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 Ka="forge-theme",uo=()=>{try{return localStorage.getItem(Ka)==="light"?"light":"dark"}catch{return"dark"}},zt=Y(uo());document.documentElement.setAttribute("data-theme",zt.value);const Ua=e=>{zt.value=e,document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(Ka,e)}catch{}},je=Y(!1),xa=()=>Ua(zt.value==="dark"?"light":"dark"),ho=({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${je.value?" open":""}`,onClick:()=>{je.value=!1}}),t("div",{class:"min-w-0 flex flex-col relative",style:{minHeight:"100vh"},children:n}),t(io,{})]}),ma=[["--blue","--purple"],["--teal","--blue"],["--orange","--red"],["--green","--teal"]],Ha=e=>ma[e%ma.length],Q=(e,n=18)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,Ee={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)"},oe={padding:"10px 14px",borderRadius:"12px",fontSize:"12.5px"},fo={personal:"--blue",project:"--green",client:"--green",team:"--purple"},Ve=e=>fo[e??""]??"--ink-2",go={decision:"--purple",context:"--teal",playbook:"--green",memory:"--orange",instinct:"--red",rule:"--blue",skill:"--ink-2"},va=e=>go[e]??"--ink-3",Dt=[{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:[]}],Ke=(e,n,a)=>({label:e,glyph:n,token:a,ink:`var(${a})`,fill:Q(a)}),Wn={task:Ke("Dev","D","--orange"),review:Ke("Review","R","--blue"),loop:Ke("Loop","L","--purple"),general:Ke("General","G","--green")},xo={create:Ke("Create","C","--teal"),login:Ke("Login","A","--ink-2")},ra=e=>Wn[e]??xo[e]??Wn.task,Xe=[{key:"dev",sessionType:"task"},{key:"review",sessionType:"review"},{key:"loop",sessionType:"loop"},{key:"general",sessionType:"general"}],oa=e=>{var n;return Wn[((n=Xe.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"].label},mo=e=>{var n;return((n=Xe.find(a=>a.key===e))==null?void 0:n.sessionType)??"task"},la={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}},Je=e=>!!(e&&(la[e.state].attention||e.state==="exited"&&(e.exitCode??0)!==0)),en=e=>e.state==="exited"&&e.exitCode?`Exited with code ${e.exitCode}`:la[e.state].label,qt=e=>e.state==="exited"&&e.exitCode?"--red":la[e.state].token,G=e=>e.sessionDir?`${e.project}::${e.sessionDir}`:`${e.project}::${e.task??e.pr}`,se=e=>e.project==="__general"?"":e.project,Me=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} · ${ge(e.harness).label}`:e.task??"unknown",vo={linear:"Linear",notion:"Notion"},ia=e=>{var a;const n=e.source?vo[e.source]:void 0;return n&&((a=e.source_url)!=null&&a.startsWith("https://"))?{label:n,url:e.source_url}:null},Rt=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`},Mt=(e,n)=>({label:e,color:`var(--forge-harness-${n})`,bg:Q(`--forge-harness-${n}`)}),yo={claude:Mt("Claude Code","claude"),codex:Mt("Codex","codex"),pi:Mt("Pi","pi"),opencode:Mt("OpenCode","opencode")},ge=e=>yo[e??"claude"]??{label:e??"claude",color:"var(--ink-3)",bg:"var(--elev)"},qa=e=>{const n=ge(e.harness).label;return e.provider&&e.provider!=="native"?`${n} · ${e.model||e.provider}`:n},bo=[{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"}],Ga=(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"},We=(e,n,a)=>{var r;return(r=e.accounts.find(o=>o.name===n))==null?void 0:r.harnesses.find(o=>o.harness===a)},ko=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,wo=new Intl.DateTimeFormat(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}),Va=(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 ${wo.format(Math.round(a/6e4)*6e4)}`;const i=r%60;return`resets in ${o} h${i?` ${i} m`:""}`},Ja=e=>e.map(n=>({label:n.label,percent:n.percent,severity:n.severity,scope:n.scope,reset:Va(n.resetsAt)})),Ya=Y(null);async function So(){const e=await fetch("/api/health");Ya.value=(await e.json()).version??null}const ht=Y(null);async function Qa(){const e=await fetch("/api/skills");if(!e.ok)throw new Error("fetch failed");ht.value=await e.json()}const ze=({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"}})},mn=5,Za="forge-sidebar-collapsed",Co=()=>{try{const e=localStorage.getItem(Za);return e?JSON.parse(e):[]}catch{return[]}},$o=(e,n)=>Number(n.live)-Number(e.live)||n.count-e.count||e.name.localeCompare(n.name),zo=({projects:e,accounts:n,selected:a,onSelect:r,onAdd:o})=>{const[i,c]=v(""),[s,d]=v(Co),[f,g]=v([]),y=i.trim().toLowerCase(),m=ee(()=>{const k=[...n,...e.map(b=>b.account).filter(b=>!n.includes(b))];return Array.from(new Set(k)).map((b,p)=>({account:b,index:p,items:e.filter(x=>x.account===b&&(!y||x.name.toLowerCase().includes(y))).sort($o),active:e.filter(x=>x.account===b).reduce((x,S)=>x+S.count,0)})).filter(b=>b.items.length>0)},[e,n,y]),w=k=>{const b=s.includes(k)?s.filter(p=>p!==k):[...s,k];d(b);try{localStorage.setItem(Za,JSON.stringify(b))}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 b=y!==""||!s.includes(k.account),p=y!==""||f.includes(k.account)||k.items.some((u,z)=>z>=mn&&u.name===a),x=p?k.items:k.items.slice(0,mn),[S,h]=Ha(k.index),C=k.items.some(u=>u.live);return l("div",{class:"flex flex-col shrink-0",style:{gap:"1px"},children:[l("button",{type:"button","aria-expanded":b,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:()=>w(k.account),children:[t("span",{class:"i-lucide-chevron-right shrink-0",style:{width:"11px",height:"11px",color:"var(--ink-3)",transform:b?"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(${S}), var(${h}))`,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}),C&&t(ze,{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})]}),b&&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:[x.map(u=>{const z=a===u.name;return l("button",{type:"button","aria-pressed":z,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 ${z?"var(--hair)":"transparent"}`,background:z?"var(--card)":"transparent",boxShadow:z?"var(--shadow-s)":"none"},onClick:()=>r(u.name),children:[t(ze,{size:6,live:u.live}),t("span",{class:"flex-1 truncate",style:{fontWeight:z?600:450,opacity:u.count>0||u.live||z?1:.62},children:u.name}),u.count>0&&t("span",{class:"mono",style:{fontSize:"11px",color:"var(--ink-3)"},children:u.count})]},u.name)}),k.items.length>mn&&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:()=>g(p?f.filter(u=>u!==k.account):[...f,k.account]),children:p?"Show less":`Show all ${k.items.length}`})]})]},k.account)})]})]})},Xa={context:null,tokens:null,cost:null},Ro=250,tn=new Map,To=/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g,at=(e,n)=>{let a=null;for(const r of e.matchAll(n))a=r;return a},vn=e=>{const n=parseFloat(e),a=e.slice(-1).toLowerCase();return a==="k"?n*1e3:a==="m"?n*1e6:n};function jo(e){const n={},a=at(e,/(?:ctx|context)[:\s]*(\d{1,3}(?:\.\d+)?)\s*%/gi)??at(e,/[▓█▒░]+\s*(\d{1,3}(?:\.\d+)?)\s*%/g);a&&(n.context=Math.min(100,parseFloat(a[1])));const r=at(e,/(\d+(?:\.\d+)?[kKmM]?)\s*↑\s*(\d+(?:\.\d+)?[kKmM]?)\s*↓/g),o=at(e,/\((\d+(?:\.\d+)?[kKmM])\s*\/\s*\d+(?:\.\d+)?[kKmM]\)/g);r?n.tokens=vn(r[1])+vn(r[2]):o&&(n.tokens=vn(o[1]));const i=at(e,/\$(\d+\.\d{2})\b/g);return i&&(n.cost=parseFloat(i[1])),n}const er=e=>{let n=tn.get(e);return n||(n={tail:"",timer:null,metrics:Y(Xa)},tn.set(e,n)),n},tr=e=>er(e).metrics,Po=e=>{e.timer=null;const n=e.metrics.value,a={...n,...jo(e.tail)};(a.context!==n.context||a.tokens!==n.tokens||a.cost!==n.cost)&&(e.metrics.value=a)};function Ao(e,n){const a=er(e);a.tail=(a.tail+n.slice(-4e3*2).replace(To,"")).slice(-4e3),a.timer||(a.timer=setTimeout(()=>Po(a),Ro))}function Io(e){const n=tn.get(e);n&&(n.timer&&clearTimeout(n.timer),n.metrics.value=Xa,tn.delete(e))}const nr=e=>e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e),ar=e=>`$${e.toFixed(2)}`,mt=Y(null),Lo=6e4;let rt=null,ot=null,yn=0;function ya(e=!1){return rt||(rt=fetch(`/api/cw/usage${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(mt.value=n,rt=null,n)),rt)}function rr(){return yn+=1,ya(),ot||(ot=setInterval(()=>{document.visibilityState==="visible"&&ya()},Lo)),()=>{yn-=1,yn===0&&ot&&(clearInterval(ot),ot=null)}}const Eo=(e,n)=>{var a;return((a=mt.value)!=null&&a.available?mt.value.usage.find(r=>r.account===e&&r.harness===n):null)??null},Ie=Y({}),ba=Y(null),or=2e3,No=15e3;let lt=null,lr=0,bn=!1;const Gt=new Set,Oo=(e,n)=>!!e&&Je(n)&&(e.state!==n.state||e.since!==n.since);async function ir(){if(!bn){bn=!0,lr=Date.now();try{const e=await fetch("/api/cw/session-states");if(!e.ok)return;const{states:n}=await e.json(),a=Ie.value;Ie.value=n;for(const[r,o]of Object.entries(n))if(Oo(a[r],o))for(const i of Gt)i(r,o)}catch{}finally{bn=!1}}}const Wo=()=>{const e=document.visibilityState==="visible"?or:No;Date.now()-lr>=e-100&&ir()};function Do(e){return Gt.add(e),lt||(ir(),lt=setInterval(Wo,or)),()=>{Gt.delete(e),Gt.size===0&&lt&&(clearInterval(lt),lt=null)}}const sr="forge.notify-sessions",dn=typeof window<"u"&&"Notification"in window,Mo=()=>{try{return dn&&Notification.permission==="granted"&&localStorage.getItem(sr)==="1"}catch{return!1}},sa=Y(Mo());async function Fo(e){if(e&&(!dn||(Notification.permission==="default"?await Notification.requestPermission():Notification.permission)!=="granted"))return!1;sa.value=e;try{localStorage.setItem(sr,e?"1":"0")}catch{}return!0}function ka(e,n,a,r){if(!sa.value||!dn||Notification.permission!=="granted")return;const o=new Notification(e,{body:n,tag:a});o.onclick=()=>{window.focus(),r(),o.close()}}const ke=Y([]),Vt=Y(!1),Bo=1e4;let it=null,kn=0;async function vt(){try{const e=await fetch("/api/modules");e.ok&&(ke.value=await e.json())}catch{}}const wa=()=>{vt()};function _o(){return kn++,it||(vt(),it=setInterval(()=>{vt()},Bo),window.addEventListener("focus",wa)),()=>{kn--,kn===0&&it&&(clearInterval(it),it=null,window.removeEventListener("focus",wa))}}const cr=e=>e.filter(n=>n.state!=="legacy"&&(n.view||n.state==="disabled")),dr=e=>e.lastDenial?`Denied ${e.lastDenial.permission}: ${e.lastDenial.value}`:e.lastJobError??e.lastEventError??null,yt=Y([]),pr=Ba(()=>{var n;const e={};for(const a of yt.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}),ur=5e3,Ko=15e3;let st=null,hr=0,Sa=!1,wn=!1;const Jt=new Set,Ca=e=>`${e.moduleId}\0${e.key}\0${e.createdAt}`;async function fr(){if(!wn){wn=!0,hr=Date.now();try{const e=await fetch("/api/modules/notifications");if(!e.ok)return;const{items:n}=await e.json(),a=new Set(yt.value.map(Ca));if(yt.value=n,Sa){for(const r of n)if(r.kind==="attention"&&!r.seen&&!a.has(Ca(r)))for(const o of Jt)o(r)}Sa=!0}catch{}finally{wn=!1}}}const Uo=()=>{const e=document.visibilityState==="visible"?ur:Ko;Date.now()-hr>=e-100&&fr()};function Ho(e){return Jt.add(e),st||(fr(),st=setInterval(Uo,ur)),()=>{Jt.delete(e),Jt.size===0&&st&&(clearInterval(st),st=null)}}async function qo(e){yt.value=yt.value.map(n=>n.moduleId===e?{...n,seen:!0}:n),await fetch(`/api/modules/${encodeURIComponent(e)}/notifications/seen`,{method:"POST"}).catch(()=>{})}const gr=[{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"}],Dn="flex items-center w-full text-left cursor-pointer transition-all duration-180 ease-spring hover:bg-elev",Mn=e=>({borderRadius:"9px",border:`1px solid ${e?"var(--hair)":"transparent"}`,background:e?"var(--card)":"transparent",boxShadow:e?"var(--shadow-s)":"none",color:"var(--ink)"}),xr="flex flex-col text-left cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m",Fn={gap:"6px",padding:"9px 10px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-s)",color:"var(--ink)"},Bn={fontSize:"10.5px",color:"var(--ink-3)"},_n=({children:e})=>t("span",{style:{fontSize:"11px",fontWeight:600,color:"var(--ink-3)",letterSpacing:".02em"},children:e}),Go=({id:e,session:n,index:a,onOpen:r})=>{const o=tr(e).value,i=Ie.value[e],c=Je(i),s=n.type==="loop",d=(o==null?void 0:o.context)??null,[f,g]=a%2===0?["var(--blue)","var(--purple)"]:["var(--purple)","var(--blue)"],y=c?en(i):s?n.loop_interval?`every ${n.loop_interval}`:"self-paced":o&&(o.tokens!==null||o.cost!==null)?[o.tokens!==null?`${nr(o.tokens)} tokens`:null,o.cost!==null?ar(o.cost):null].filter(Boolean).join(" · "):se(n)||n.account;return l("button",{type:"button",class:xr,style:c?{...Fn,borderColor:`var(${qt(i)})`}:Fn,onClick:r,title:i?en(i):void 0,children:[l("span",{class:"flex items-center w-full",style:{gap:"6px"},children:[t(ze,{size:6,color:i?`var(${qt(i)})`:f,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, ${f}, ${g})`,transition:"width .6s var(--ease)"}}),t("span",{class:"absolute inset-y-0 left-0",style:{width:"30%",background:"linear-gradient(90deg, transparent, rgba(255,255,255,.22), transparent)",animation:"sweep 2.6s ease-in-out infinite"}})]}),t("span",{class:"mono truncate w-full",style:c?{...Bn,color:`var(${qt(i)})`,fontWeight:600}:Bn,children:y})]})},Vo=({view:e,onNavigate:n})=>{const a=cr(ke.value),r=pr.value,o=()=>{je.value=!1,Vt.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(_n,{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:Dn,style:{...Mn(!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",f=d?null:dr(i),g=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??""}`:f??i.displayName,class:Dn,style:{...Mn(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}),f&&t("span",{class:"sb-label","aria-label":"Has a warning",style:{width:"6px",height:"6px",borderRadius:"50%",background:"var(--orange)"}}),g&&g.attention>0&&t("span",{class:"mono sb-label","aria-label":`${g.attention} need you`,style:{fontSize:"10.5px",fontWeight:700,padding:"0 6px",borderRadius:"99px",color:"#fff",background:"var(--red)"},children:g.attention}),g&&g.badge>0&&t("span",{class:"mono sb-label",style:{fontSize:"11px",color:"var(--ink-3)"},children:g.badge})]},`${i.id}-${i.source}`)})]})},Jo=()=>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(cn,{checked:sa.value,label:"Notify me when a session or module needs me",onChange:e=>{Fo(e).then(n=>{n||j("The browser blocked notifications for Forge","error")})}})]}),Yo=({account:e,harness:n,windows:a,stale:r,onOpen:o})=>{const i=a.reduce((s,d)=>d.percent>s.percent?d:s),c=ge(n).label;return l("button",{type:"button",class:xr,style:Fn,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(_a,{bars:Ja(a),size:"sm"}),t("span",{class:"mono truncate w-full",style:Bn,children:r?"last known values":Va(i.resetsAt)})]})},Qo=({view:e,counts:n,projects:a,accounts:r,selectedProject:o,live:i,onNavigate:c,onSelectProject:s,onAddProject:d,onOpenLive:f,onSearch:g})=>{var b;const y=Ya.value,m=gr.map(p=>{var x;return{...p,count:p.view==="skills"?((x=ht.value)==null?void 0:x.length)??null:n[p.view]??null}});D(()=>rr(),[]),D(()=>{So().catch(()=>{})},[]);const w=[...i].sort((p,x)=>Number(Je(Ie.value[x.key]))-Number(Je(Ie.value[p.key]))),k=(b=mt.value)!=null&&b.available?mt.value.usage.filter(p=>p.state==="ok"&&p.windows.some(x=>!x.scope)):[];return l("aside",{class:`forge-sidebar flex flex-col${je.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})]}),g&&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:g,"aria-label":"Search (⌘K)",children:[t("span",{class:"i-lucide-search shrink-0",style:{width:"13px",height:"13px",opacity:.7}}),t("span",{class:"flex-1 sb-label",children:"Search"}),t("kbd",{class:"sb-label",style:{fontSize:"10px",padding:"1px 5px",borderRadius:"5px",background:"var(--elev)",border:"1px solid var(--hair)"},children:"⌘K"})]}),t("nav",{class:"flex flex-col",style:{gap:"2px"},"aria-label":"Sections",children:m.map(p=>{const x=e===p.view;return l("button",{type:"button","aria-current":x?"page":void 0,title:p.label,class:Dn,style:{...Mn(x),gap:"9px",height:"32px",padding:"0 9px",fontSize:"13.5px",fontWeight:x?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:x?Q(p.token):"var(--elev)",color:x?`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(Vo,{view:e,onNavigate:c}),t(zo,{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(_n,{children:"Live now"})}),w.map((p,x)=>t(Go,{id:p.key,session:p.session,index:x,onOpen:()=>f(p.session)},p.key))]}),k.length>0&&l("div",{class:"flex flex-col sb-section",style:{gap:"8px"},children:[t("span",{style:{padding:"0 9px"},children:t(_n,{children:"Limits"})}),k.map(p=>t(Yo,{account:p.account,harness:p.harness,windows:p.windows.filter(x=>!x.scope),stale:p.stale,onOpen:()=>c("accounts")},`${p.account}/${p.harness}`))]}),dn&&t("div",{class:"sb-section",children:t(Jo,{})}),t("div",{class:"sb-section",children:t(de,{fill:!0,size:"xs",label:"Appearance",tabs:[{id:"light",label:"Light"},{id:"dark",label:"Dark"}],active:zt.value,onChange:p=>Ua(p==="light"?"light":"dark")})})]})]})};function Tt(){const e=ie(null);return D(()=>{var n;(n=e.current)==null||n.focus()},[]),e}const $a=(e,n,a)=>{const r=ra(e.type);return{id:G(e),label:se(e)?`${ue(e)} · ${se(e)}`:ue(e),hint:n,glyph:r.glyph,token:r.token,run:()=>a(e)}},Zo=({openTabs:e,sessions:n,projects:a,commands:r,onOpenSession:o,onSelectProject:i,onClose:c})=>{const[s,d]=v(""),[f,g]=v(0),y=ie(null),m=Tt(),w=ee(()=>{const h=s.trim().toLowerCase(),C=O=>!h||O.label.toLowerCase().includes(h),u=new Set(e.map(G)),z=e.map((O,T)=>$a(O,T<5?`⌘${T+1}`:"open",o)),L=n.filter(O=>O.status==="active"&&!u.has(G(O))).map(O=>$a(O,"resume",o)),N=h?a.map(O=>({id:`project:${O}`,label:O,hint:"project",glyph:"P",token:"--green",run:()=>i(O)})):[];return[{name:"Live now",items:z.filter(C)},{name:"Tasks",items:L.filter(C).slice(0,h?12:6)},{name:"Projects",items:N.filter(C).slice(0,6)},{name:"Commands",items:r.filter(C)}].filter(O=>O.items.length>0)},[s,e,n,a,r,o,i]),k=w.flatMap(h=>h.items),b=Math.min(f,k.length-1);D(()=>{var h,C;(C=(h=y.current)==null?void 0:h.querySelector('[data-active="true"]'))==null||C.scrollIntoView({block:"nearest"})},[b]);const p=h=>{h&&(c(),h.run())},x=ie({flat:k,current:b,activate:p});x.current={flat:k,current:b,activate:p},D(()=>{const h=C=>{const{flat:u,current:z,activate:L}=x.current,N=u.length;C.key==="ArrowDown"?(C.preventDefault(),g(O=>N?(Math.min(O,N-1)+1)%N:0)):C.key==="ArrowUp"?(C.preventDefault(),g(O=>N?(Math.min(O,N-1)-1+N)%N:0)):C.key==="Enter"?(C.preventDefault(),L(u[z])):C.key==="Escape"&&(C.preventDefault(),c())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[c]);let S=-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:h=>h.stopPropagation(),children:[t("input",{ref:m,role:"combobox","aria-expanded":"true","aria-controls":"palette-list","aria-activedescendant":k[b]?`palette-${k[b].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:h=>{d(h.target.value),g(0)}}),l("div",{id:"palette-list",role:"listbox",ref:y,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,"”."]}),w.map(h=>l("div",{role:"group","aria-label":h.name,children:[t("div",{style:{padding:"7px 10px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:h.name}),h.items.map(C=>{S+=1;const u=S,z=u===b;return l("button",{id:`palette-${C.id}`,type:"button",role:"option","aria-selected":z,"data-active":z,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"10px",padding:"8px 10px",borderRadius:"10px",border:0,background:z?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px",transition:"background .14s"},onMouseMove:()=>{z||g(u)},onClick:()=>p(C),children:[t("span",{class:"grid place-items-center shrink-0",style:{width:"22px",height:"22px",borderRadius:"7px",fontSize:"10px",fontWeight:700,background:C.token?Q(C.token):"var(--elev)",color:C.token?`var(${C.token})`:"var(--ink-2)"},children:C.glyph}),t("span",{class:"flex-1 min-w-0 truncate",children:C.label}),t("span",{class:"mono shrink-0",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:C.hint})]},C.id)})]},h.name))]}),t("div",{class:"flex shrink-0",style:{gap:"14px",padding:"8px 14px",borderTop:"1px solid var(--hair)"},children:["↑↓ move","↵ open","esc close"].map(h=>t("span",{class:"mono",style:{fontSize:"10.5px",color:"var(--ink-3)"},children:h},h))})]})})},pn=Y(null),Xo=3e3;let ct=null;function ye(e=!1){return ct||(ct=fetch(`/api/cw/harnesses${e?"?fresh=1":""}`).then(n=>n.json()).catch(()=>({available:!1,reason:"Could not reach the Forge server"})).then(n=>(pn.value=n,ct=null,n)),ct)}const bt=new Set;let ft=null;const mr=()=>{bt.size===0&&ft&&(clearInterval(ft),ft=null)},el=async()=>{const e=await ye(!0),n=Date.now();for(const a of bt){const r=e.available&&a.check(e.doctor);(r||n>a.deadline)&&(bt.delete(a),a.onDone(r))}mr()};function tl(e,{timeoutMs:n=6e5,onDone:a=()=>{}}={}){const r={check:e,deadline:Date.now()+n,onDone:a};return bt.add(r),ft||(ft=setInterval(el,Xo)),()=>{bt.delete(r),mr()}}const qe=(e,n,a)=>{var r;return!!(e!=null&&e.available&&((r=e.capabilities[n])!=null&&r.includes(a)))},vr=e=>/linear\.app/.test(e)?"linear":/notion\.(so|site)/.test(e)?"notion":null,yr=(e,n,a)=>{const r=vr(a);return!!(e!=null&&e.available&&r&&!qe(e,n,"mcp")&&!e.contextTokens[r])},Kn=Y(null);let Sn=null;function br(){return Sn||(Sn=fetch("/api/cw/editors").then(e=>e.json()).then(e=>{Kn.value=e}).catch(()=>{Kn.value={enabled:!1,editors:[]}})),Sn}async function nl(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:Me(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 kt=e=>e.unpushed??e.commits??0,kr={OPEN:"open",MERGED:"merged",CLOSED:"closed"},al={passing:"✓",failing:"✗",pending:"…",none:""};function rl(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=kt(e);if(a>0&&n.push(`${a} unpushed`),e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":kr[e.pr.state];n.push(`PR #${e.pr.number} ${r}`),e.pr.checks!=="none"&&n.push(`checks ${al[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 ol={passing:"checks pass",failing:"checks failing",pending:"checks running",none:""},za=(e,n)=>`${e} ${n}${e===1?"":"s"}`;function ll(e){if(e.workspace==="missing")return"not created yet";if(e.pr.status==="found"){const r=e.pr.state==="OPEN"&&e.pr.isDraft?"draft":kr[e.pr.state];return[`PR #${e.pr.number} ${r}`,ol[e.pr.checks]].filter(Boolean).join(" · ")}const n=[];e.diff&&e.diff.files>0&&n.push(za(e.diff.files,"file")),e.commits&&n.push(za(e.commits,"commit"));const a=kt(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 jt(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 ce=(e,n)=>jt("POST",e,n),le=e=>e instanceof Error?e.message:String(e);function un(e,n){navigator.clipboard.writeText(e).then(()=>j(`${n} copied`,"info"),()=>j(`Could not copy the ${n.toLowerCase()}`,"error"))}const il=({session:e,muted:n})=>{const a=ge(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}}),qa(e)]})},be=Y(null),wt=Y(null),ca=Y(null),sl=6e4;let dt=null,pt=null,Cn=0;function Pe(e=!1){return dt&&!e||(dt=fetch(`/api/kioku/status${e?"?fresh=1":""}`).then(n=>n.json()).then(n=>{JSON.stringify(n)!==JSON.stringify(be.value)&&(be.value=n)}).catch(()=>{be.value??(be.value={installed:!1,version:null,brains:[],projects:{},activity:[],viewer:null})}).finally(()=>{dt=null})),dt}async function wr(e=!1){wt.value=await jt("GET",`/api/kioku/releases${e?"?fresh=1":""}`).catch(()=>wt.value)}async function cl(){ca.value=await jt("GET","/api/kioku/labs").catch(()=>null)}const Un=(e=!1,n=!0)=>Promise.all([wr(e),n&&cl()]);function Sr(){return Cn+=1,be.value||Pe(),pt||(pt=setInterval(()=>{document.visibilityState==="visible"&&Pe()},sl)),()=>{Cn-=1,Cn===0&&pt&&(clearInterval(pt),pt=null)}}const re=e=>e.name??e.key,nn=e=>e.reduce((n,a)=>n+a.pages,0);function da(e){const n=be.value;return n!=null&&n.installed?(n.projects[e]??[]).flatMap(a=>n.brains.find(r=>re(r)===a.name)??[]):[]}function Cr(e){return D(()=>Sr(),[]),da(e)}const dl=({project:e})=>{const[n,a]=v(null),r=Cr(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(${Ve(o.tier)})`,border:"2px solid var(--card)",marginLeft:i===0?0:"-4px"}},o.key))}),t("span",{class:"mono",children:nn(r)}),n&&co(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(ze,{color:`var(${Ve(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)]})},Hn=Y({}),$r=Y(0),pl=6e4,Ft=new Map,zr=e=>`${e.project}::${Me(e)}`;function qn(e,n=!1){const a=zr(e),r=Ft.get(a);if(r&&!n)return r;const o=`/api/cw/review-state/${encodeURIComponent(e.project)}/${encodeURIComponent(Me(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=>(Hn.value={...Hn.value,[a]:c},Ft.get(a)===i&&Ft.delete(a),c));return Ft.set(a,i),i}function ul(){$r.value++}function Rr(e,{poll:n=!1}={}){const a=zr(e),r=$r.value;return D(()=>{if(qn(e),!n)return;const o=setInterval(()=>{qn(e,!0)},pl);return()=>clearInterval(o)},[a,n,r]),Hn.value[a]??null}const Gn=({type:e,size:n=28,radius:a=9,font:r=11})=>{const o=ra(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})},hl=()=>l("span",{class:"inline-flex items-center shrink-0",style:{gap:"5px",padding:"1px 8px",borderRadius:"99px",background:Q("--green"),color:"var(--green)",fontSize:"11px",fontWeight:600},children:[t(ze,{size:5,color:"var(--green)",live:!0,glow:!1}),"live"]}),Tr=({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})},jr=({session:e})=>{const n=ia(e);return n&&t(Tr,{label:n.label,href:n.url})},fl=({session:e})=>ia(e)?t(jr,{session:e}):e.source?t("span",{class:"task-chip contents",children:t(Tr,{label:e.source,href:e.source_url})}):null,Pr=e=>e.type==="review"?`review/pr-${e.pr}`:e.type==="loop"?`loop/${e.task??"loop"}`:e.type==="task"?`task/${e.task}`:null,gl=({session:e,project:n})=>{var i;const a=Rr(e),r=((i=a==null?void 0:a.state)==null?void 0:i.branch)??Pr(e),o=a?a.error!==null?"changes unknown":ll(a.state):"checking…";return t(Ar,{branch:r,status:o,project:n})},Ar=({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(),un(e,"Branch")},onKeyDown:r=>r.stopPropagation(),children:e}),t("span",{class:"whitespace-nowrap truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:n})]}),xl=e=>e.type==="loop"?e.loop_interval?`every ${e.loop_interval}`:"self-paced":`${e.opens} session${e.opens===1?"":"s"}`,Ir=({session:e,isOpenInTab:n,onSelect:a,onMarkDone:r,showProject:o})=>{const i=o?se(e)||"no project":void 0,[c,s]=v(!1),d=e.type==="task"||e.type==="review",f=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:g=>{g.target===g.currentTarget&&(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),a())},children:[t(Gn,{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(hl,{}),t(fl,{session:e})]}),d?t(gl,{session:e,project:i}):t(Ar,{branch:Pr(e),status:xl(e),project:i})]}),t(dl,{project:se(e)}),t(il,{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:Rt(e.last_opened)}),r&&t("button",{type:"button",class:`task-done grid place-items-center shrink-0 cursor-pointer transition-all duration-180 ease-spring hover:text-green disabled:cursor-wait ${c?"":"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"}`,style:{width:"28px",height:"28px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink-2)"},onClick:g=>{g.stopPropagation(),f()},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"})]})},ml=({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:se(e)})]}),t(jr,{session:e}),t("span",{class:"mono shrink-0",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:Rt(e.closed??e.last_opened)})]}),vl=({project:e,account:n,accounts:a,onDeleted:r,onMoved:o})=>{const[i,c]=v(null),[s,d]=v(null),[f,g]=v(!1),[y,m]=v(!1),[w,k]=v(""),[b,p]=v(!1),x=(a??[]).filter(R=>R!==n);D(()=>{let R=!1;return fetch(`/api/cw/mcps?project=${encodeURIComponent(e)}`).then(B=>B.json()).catch(()=>null).then(B=>{R||c(B)}),()=>{R=!0}},[e]);const S=i?Object.keys(i.global):[],h=(i==null?void 0:i.project)??[],C=(i==null?void 0:i.cw)??[],u=(i==null?void 0:i.plugins)??[],z=[...h.map(R=>`${R} (project)`),...S,...C.map(R=>`${R} (CW)`)],L=R=>{d(s===R?null:R),k(""),g(!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:f})})).json()).ok&&(j(`Project "${e}" deleted${f?" (files removed)":""}`,"info"),r==null||r())}catch{j("Failed to delete project","error")}finally{m(!1),d(null)}},O=async()=>{if(w){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:w})})).json();B.ok?(j(`Project "${e}" moved to "${w}"`,"success"),d(null),k(""),o==null||o()):j(B.error??"Failed to move project","error")}catch{j("Failed to move project","error")}finally{p(!1)}}};if(!i)return null;const T={padding:"12px 15px",borderTop:"1px solid var(--hair)",display:"flex",flexDirection:"column",gap:"10px"},P=(R,B)=>({padding:"5px 11px",borderRadius:"9px",border:"1px solid var(--hair)",fontSize:"12.5px",fontWeight:500,background:B?"var(--elev)":"var(--card)",color:R==="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:[z.length>0&&l("span",{class:"truncate",title:z.join(", "),children:["MCP · ",z.join(", ")]}),u.length>0&&l("span",{class:"truncate",title:u.join(", "),children:["Plugins · ",u.join(", ")]}),z.length===0&&u.length===0&&t("span",{children:"No MCPs or plugins for this project"})]}),x.length>0&&t("button",{type:"button",class:"cursor-pointer",style:P("ink",s==="move"),"aria-expanded":s==="move",onClick:()=>L("move"),children:"Move to account"}),t("button",{type:"button",class:"cursor-pointer",style:P("red",s==="delete"),"aria-expanded":s==="delete",onClick:()=>L("delete"),children:"Delete project"})]}),s==="move"&&l("div",{style:T,children:[l("p",{style:{fontSize:"13px"},children:['Move "',e,'" to a different account.']}),l("select",{class:"field",value:w,onChange:R=>k(R.target.value),children:[t("option",{value:"",children:"Select account…"}),x.map(R=>t("option",{value:R,children:R},R))]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:b?"Moving…":"Move project",variant:"primary",size:"sm",loading:b,disabled:!w,onClick:O}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),k("")}})]})]}),s==="delete"&&l("div",{style:T,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:f,onChange:R=>g(R.target.checked)}),"Also delete project files from disk"]}),f&&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:y?"Deleting…":f?"Delete project and files":"Unregister project",variant:"destructive",size:"sm",loading:y,onClick:N}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:()=>{d(null),g(!1)}})]})]})]})},Lr=e=>e.trim().replace(/\s+/g,"-").toLowerCase();function hn(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:Lr(n)}:null}const yl="A PR link becomes a review. A Linear or Notion link becomes a dev task with its notes.";function bl(e,n){const a=hn(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:yl,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 pa=(e,n)=>{var a;return n??((a=hn(e))==null?void 0:a.type)??"dev"},we=Y(""),Ye=Y(null),Ge=Y(""),an=Y(""),rn=e=>{we.value=e,Ye.value=null},ua=(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,kl=(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":"")},wl=({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=We(e,n,s.name),f=ua(s.name,d,o),g=ge(s.name),y=a===s.name,m=(d==null?void 0:d.status)==="not_logged_in",w=kl(e,s.name,d,s.name===r,f);return l("div",{role:"radio","aria-checked":y,tabIndex:f?-1:0,"aria-disabled":!!f,title:f??void 0,class:`flex items-start transition-all duration-180 ease-spring ${f?"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?Q("--blue"):"var(--card)",boxShadow:y?"var(--shadow-s)":"none",opacity:f?.45:1},onClick:()=>{f||i(s.name)},onKeyDown:k=>{!f&&(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:g.color,boxShadow:y?`0 0 8px ${g.color}`:"none"}}),l("span",{class:"flex flex-col min-w-0",children:[t("span",{style:{fontSize:"12.5px",fontWeight:600},children:g.label}),t("span",{class:"truncate",style:{fontSize:"11.5px",color:"var(--ink-2)"},title:w,children:w}),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)})})]}),Sl=({options:e,value:n,label:a,onPick:r,onClose:o})=>{const[i,c]=v(""),[s,d]=v(0),f=Tt(),g=ie(null),y=i.trim().toLowerCase(),m=ee(()=>e.filter(b=>{var p;return!y||b.label.toLowerCase().includes(y)||((p=b.group)==null?void 0:p.toLowerCase().includes(y))}),[e,y]);D(()=>{const b=m.findIndex(p=>p.value===n);d(b>=0&&!y?b:0)},[y]),D(()=>{var b,p;(p=(b=g.current)==null?void 0:b.querySelector('[data-active="true"]'))==null||p.scrollIntoView({block:"nearest"})},[s]);const w=b=>{if(b.key==="ArrowDown")b.preventDefault(),d(p=>Math.min(p+1,m.length-1));else if(b.key==="ArrowUp")b.preventDefault(),d(p=>Math.max(p-1,0));else if(b.key==="Enter"){b.preventDefault();const p=m[s];p&&r(p.value)}else b.key==="Escape"&&(b.preventDefault(),b.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:w,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:f,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:b=>c(b.target.value)})]}),l("div",{ref:g,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((b,p)=>{const x=b.group&&b.group!==k?b.group:null;k=b.group;const S=p===s,h=b.value===n;return l("div",{children:[x&&t("div",{style:{padding:"7px 9px 3px",fontSize:"11px",fontWeight:600,color:"var(--ink-3)"},children:x}),l("button",{type:"button",role:"option","aria-selected":h,"data-active":S,tabIndex:-1,class:"flex items-center w-full text-left cursor-pointer",style:{gap:"8px",padding:"6px 9px",borderRadius:"8px",border:0,background:S?"var(--elev)":"transparent",color:"var(--ink)",fontSize:"13px"},onMouseMove:()=>{S||d(p)},onClick:()=>r(b.value),children:[t("span",{class:"flex-1 truncate",style:{fontWeight:h?600:400,color:b.value?"var(--ink)":"var(--ink-2)"},children:b.label}),h&&t("span",{class:"i-lucide-check shrink-0",style:{width:"13px",height:"13px",color:"var(--blue)"}})]})]},b.value||"__empty")})]})]})},Er=({label:e,value:n,options:a,onChange:r,placeholder:o="Choose…",size:i="sm",width:c})=>{const[s,d]=v(!1),f=ie(null),g=a.find(m=>m.value===n);return D(()=>{if(!s)return;const m=w=>{f.current&&!f.current.contains(w.target)&&d(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[s]),l("div",{ref:f,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:g&&g.value?"var(--ink)":"var(--ink-2)"},children:(g==null?void 0:g.label)??o}),t("span",{class:"i-lucide-chevrons-up-down shrink-0",style:{width:"12px",height:"12px",color:"var(--ink-3)"}})]}),s&&t(Sl,{options:a,value:n,label:e,onPick:m=>{r(m),d(!1)},onClose:()=>d(!1)})]})},Vn=(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}))},Nr=({ctx:e,size:n="md"})=>{const{text:a,ready:r}=bl(we.value,{...e,harness:ge(e.harness).label}),o=r&&(e.type==="general"||hn(we.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:Q("--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})]})},Or=({fill:e})=>t(de,{fill:e,label:"Task type",tabs:Xe.map(n=>({id:n.key,label:oa(n.key)})),active:pa(we.value,Ye.value),onChange:n=>{Ye.value=n}}),Cl={width:"auto",maxWidth:"180px",height:"30px",padding:"0 26px 0 10px",borderRadius:"9px",fontSize:"12.5px",background:"var(--bg-2)"},$l=({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:Cl,value:n,onChange:o=>a(o.target.value),children:r.map(o=>t("option",{value:o.value,children:o.label},o.value))})]}),zl=({projects:e,accounts:n,onStarted:a,onOpenDrawer:r})=>{var h,C;const[o,i]=v(!1),c=pn.value,s=c!=null&&c.available?c.doctor:null,d=pa(we.value,Ye.value),f=d==="general",g=Ge.value,y=Object.keys(e).sort(),m=f?an.value||((h=e[g])==null?void 0:h.account)||n[0]||"":((C=e[g])==null?void 0:C.account)??"",w=y.filter(u=>e[u].account===m),k=d==="loop"?"claude":s?Ga(g||void 0,m,e,s):"claude",b=we.value.trim(),p=o||(f?!m:!b||!g),x=async()=>{if(p)return;const u=s?We(s,m,k):void 0,z=s?ua(k,u,d==="loop"):null,L=!f&&yr(c,k,b);if(d==="loop"||z||L||(u==null?void 0:u.status)==="not_logged_in"){r();return}i(!0);try{const T=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f?{type:d,account:m,project:g||void 0,harness:s?k:void 0}:{type:d,project:g,task:b,account:m||void 0,harness:s?k:void 0})})).json();T.ok?(j(f?"Session started":d==="review"?"Review started":"Task started","success"),f||rn(""),a(T.session)):j(T.error??"Failed to start","error")}catch{j("Failed to start","error")}finally{i(!1)}},S=u=>{var z;an.value=u,g&&((z=e[g])==null?void 0:z.account)!==u&&(Ge.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:f?"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:we.value,onInput:u=>rn(u.target.value),onKeyDown:u=>{u.key==="Enter"&&x()}}),t(Or,{}),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 x(),children:o?"Starting…":f?"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(Nr,{ctx:{type:d,project:g,account:m,harness:k}})}),f&&t($l,{label:"Account",value:m,onChange:S,options:n.map(u=>({value:u,label:u}))}),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(Er,{label:"Project",value:g,onChange:u=>{Ge.value=u},placeholder:f?"No project":"Choose…",options:f?[{value:"",label:"No project"},...Vn(e,n,w)]:Vn(e,n,y)})]})]})]})},et=({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(ha,{}),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})]}),Rl=({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]}),ha=()=>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:()=>{je.value=!0},children:t("span",{class:"i-lucide-menu",style:{width:"15px",height:"15px"}})}),Jn=Y({}),Ra=new Set;function Tl(e){!e||Ra.has(e)||(Ra.add(e),fetch(`/api/cw/detect/${encodeURIComponent(e)}`).then(n=>n.ok?n.json():null).catch(()=>null).then(n=>{Jn.value={...Jn.value,[e]:n}}))}const Wr=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 Dr(e){return D(()=>{Tl(e)},[e]),Jn.value[e]}const Ta=10,Mr="forge-task-layout",jl=()=>{try{return localStorage.getItem(Mr)==="project"?"project":"recent"}catch{return"recent"}},Yt={borderRadius:"16px",background:"var(--card)",border:"1px solid var(--hair)",boxShadow:"var(--shadow-m)",overflow:"hidden"},Qt={padding:"11px 15px",borderBottom:"1px solid var(--hair)",background:"var(--elev)"},Pl=({project:e,account:n,sessions:a,index:r,openTabKeys:o,onSelectTask:i,onMarkDone:c})=>{const s=Wr(Dr(e)),d=a.some(f=>o.has(G(f)));return l("section",{style:{...Yt,animation:`riseIn .4s var(--ease) ${r*70}ms both`},"aria-label":e||"No project",children:[l("div",{class:"flex items-center flex-wrap",style:{...Qt,gap:"10px"},children:[t(ze,{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(f=>t(Ir,{session:f,isOpenInTab:o.has(G(f)),onSelect:()=>i(f),onMarkDone:f.type==="login"?void 0:()=>c(f)},G(f)))]})},Al=({spaces:e,allSpaces:n,projects:a,accountNames:r,filterAccount:o,filterProject:i,onFilterProject:c,filterType:s,onFilterType:d,harnessNames:f,filterHarness:g,onFilterHarness:y,showDone:m,onShowDone:w,openTabKeys:k,onSelectTask:b,onMarkDone:p,onNewTask:x,onCreateProject:S,onRefresh:h,onStarted:C})=>{var q,he;const[u,z]=v(jl),L=E=>{z(E);try{localStorage.setItem(Mr,E)}catch{}},N=ee(()=>e.filter(E=>E.status==="active"),[e]),O=ee(()=>e.filter(E=>E.status==="done"),[e]),T=ee(()=>n.filter(E=>E.status==="active").length,[n]),P=ee(()=>n.filter(E=>E.status==="done").length,[n]),R=ee(()=>n.filter(E=>E.status==="active"&&k.has(G(E))).length,[n,k]),B=ee(()=>n.filter(E=>E.status==="active"&&(!o||E.account===o)&&(!i||E.project===i)&&(!g||(E.harness??"claude")===g)),[n,o,i,g]),A=ee(()=>{const E=new Map;for(const Z of N){const te=se(Z),Se=E.get(te)??[];Se.push(Z),E.set(te,Se)}return Array.from(E,([Z,te])=>({project:Z,sessions:te}))},[N]),M=i?((q=a[i])==null?void 0:q.account)??((he=N[0])==null?void 0:he.account):void 0,F=i?`${M?`${M} · `:""}${B.length} active`:`${T} active · ${P} done · ${R} agent${R===1?"":"s"} working`;return l(H,{children:[l(et,{title:i??"Tasks",subtitle:F,children:[t(I,{label:"Add project",variant:"secondary",onClick:S}),t(I,{label:"New task",variant:"primary",onClick:x})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"16px",maxWidth:"1180px"},children:[t(zl,{projects:a,accounts:r,onStarted:C,onOpenDrawer:x}),l("div",{class:"flex items-center flex-wrap",style:{gap:"12px"},children:[t(de,{label:"Filter by type",tabs:[{id:"all",label:"All",count:B.length},...Xe.map(E=>({id:E.key,label:oa(E.key),count:B.filter(Z=>Z.type===E.sessionType).length}))],active:s??"all",onChange:E=>d(E==="all"?null:E)}),f.length>1&&t(de,{label:"Filter by harness",tabs:[{id:"all",label:"Any harness"},...f.map(E=>({id:E,label:ge(E).label}))],active:g??"all",onChange:E=>y(E==="all"?null:E)}),t("span",{class:"flex-1"}),!i&&t(de,{size:"sm",label:"Order tasks",tabs:[{id:"recent",label:"Recent"},{id:"project",label:"By project"}],active:u,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:()=>w(!m),children:m?"Hide done":"Show done"})]}),i&&t(vl,{project:i,account:M,accounts:r,onDeleted:()=>{c(null),h()},onMoved:h}),u==="recent"&&!i&&N.length>0&&l("section",{style:{...Yt,animation:"riseIn .4s var(--ease) both"},"aria-label":"Recently opened",children:[l("div",{class:"flex items-center",style:{...Qt,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(Ir,{session:E,showProject:!0,isOpenInTab:k.has(G(E)),onSelect:()=>b(E),onMarkDone:E.type==="login"?void 0:()=>p(E)},G(E)))]}),(u==="project"||i)&&A.map((E,Z)=>{var te;return t(Pl,{project:E.project,account:((te=a[E.project])==null?void 0:te.account)??E.sessions[0].account,sessions:E.sessions,index:Z,openTabKeys:k,onSelectTask:b,onMarkDone:p},E.project)}),A.length===0&&l("section",{style:{...Yt,animation:"riseIn .4s var(--ease) both"},children:[i&&l("div",{class:"flex items-center",style:{...Qt,gap:"10px"},children:[t(ze,{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||g?"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:x})]})]}),m&&O.length>0&&l("section",{style:{...Yt,boxShadow:"var(--shadow-s)"},"aria-label":"Done",children:[l("div",{style:{...Qt,padding:"10px 15px",fontSize:"13px",fontWeight:600,color:"var(--ink-2)"},children:["Done · last ",Math.min(Ta,O.length)," of ",O.length]}),O.slice(0,Ta).map(E=>t(ml,{session:E,onSelect:()=>b(E)},G(E)))]})]})]})},De={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"},Qe="inline-flex items-center gap-1 cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px hover:shadow-m hover:text-ink",Fr={...De,color:"var(--ink-3)",boxShadow:"none"},Br=({href:e,title:n,children:a})=>l("a",{class:Qe,style:De,href:e,target:"_blank",rel:"noopener noreferrer",title:n,children:[a," ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]}),Il=({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:Fr,disabled:!0,title:r,children:["GitHub ",t("span",{class:"i-lucide-external-link",style:{width:"12px",height:"12px"}})]})}return t(Br,{href:n.url,title:n.label,children:"GitHub"})},Ll=({session:e})=>{const n=ia(e);return n&&t(Br,{href:n.url,title:n.url,children:n.label})},El=({session:e,entry:n})=>{var f;const[a,r]=v(!1),o=ie(null);D(()=>{br()},[]),D(()=>{if(!a)return;const g=y=>{o.current&&!o.current.contains(y.target)&&r(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a]);const i=Kn.value,c=i!=null&&i.enabled?i.editors:[];if(c.length===0)return null;const s=(f=n==null?void 0:n.state)==null?void 0:f.workspace;if(s!=="ready")return l("button",{type:"button",class:"cursor-not-allowed",style:Fr,disabled:!0,title:n?s==="missing"?"Workspace not created yet":"This session has no worktree":"Checking the worktree…",children:["Open in ",c.length===1?c[0].label:"editor"]});const d=async g=>{r(!1);try{await nl(e,g)}catch(y){j(y.message,"error")}};return c.length===1?l("button",{type:"button",class:Qe,style:De,onClick:()=>d(c[0].id),children:["Open in ",c[0].label]}):l("div",{class:"relative",ref:o,children:[l("button",{type:"button",class:Qe,style:De,"aria-expanded":a,onClick:()=>r(g=>!g),children:["Open in editor ",t("span",{class:"i-lucide-chevron-down",style:{width:"12px",height:"12px"}})]}),a&&t("div",{class:"popover absolute right-0 top-full z-30 flex flex-col",style:{marginTop:"6px",minWidth:"160px",padding:"5px",borderRadius:"12px"},children:c.map(g=>t("button",{type:"button",class:"text-left cursor-pointer hover:bg-elev",style:{padding:"7px 10px",borderRadius:"8px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>d(g.id),children:g.label},g.id))})]})},Nl={"--orange":"--red","--blue":"--purple","--purple":"--blue","--green":"--teal"},ut=({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)"}})})]}),Ol=({value:e,onChange:n,onSend:a,onCancel:r})=>{const o=Tt();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})]})},Wl=({session:e,onOpen:n})=>{const a=se(e),r=Cr(a),[o,i]=v(null);if(r.length===0)return null;const c=e.harness==="claude"&&e.status==="active",s=async()=>{if(o!=null&&o.trim())try{await ce("/api/kioku/remember",{project:a,sessionDir:Me(e),text:o}),j("Sent to the agent to remember","success"),i(null)}catch(d){j(le(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 · ",nn(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(Ol,{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,f)=>l("span",{class:"inline-flex items-center",style:{gap:"4px"},children:[f>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:Q(Ve(d.tier)),color:`var(${Ve(d.tier)})`},title:`${d.tier??"brain"} · ${d.pages} pages`,onClick:()=>n==null?void 0:n(a),children:re(d)})]},d.key))})]})},$n=({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?Q(a):"var(--elev)",color:a&&!o.muted?`var(${a})`:"var(--ink-2)",opacity:o.muted?.6:1},children:o.name},o.name))]})]}),Dl=({session:e,active:n,onDone:a,onOpenMemory:r})=>{const[o,i]=v(""),[c,s]=v(!1),[d,f]=v(!1),[g,y]=v(0),[m,w]=v(null),[k,b]=v(!1),p=G(e),x=Me(e),S=e.type==="task"||e.type==="review",h=Rr(e,{poll:n&&e.type==="task"}),C=ra(e.type),u=e.type==="login",z=Wr(Dr(u?"":se(e))),L=tr(p).value,N=encodeURIComponent(e.project),O=encodeURIComponent(x),P=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal/${N}/${O}?k=${g}`;D(()=>{if(u)return;let E=!1;return Promise.all([fetch(`/api/cw/tools?project=${N}`).then(Z=>Z.json()).catch(()=>null),fetch(`/api/cw/git/branch/${N}/${O}`).then(Z=>Z.json()).catch(()=>null)]).then(([Z,te])=>{E||(Z&&w(Z),i((te==null?void 0:te.branch)||e.task||e.pr||""))}),()=>{E=!0}},[p]);const R=()=>{s(!1),y(E=>E+1)},B=(m==null?void 0:m.mcps)??[],A=(m==null?void 0:m.plugins)??[],M=(h==null?void 0:h.state)??null,F=(M==null?void 0:M.branch)??o,q=h?h.error!==null?"Changes unknown":rl(h.state):"Checking changes…",he=[se(e)||"no project",e.account,[qa(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(${C.token}), var(${Nl[C.token]??C.token}))`,boxShadow:"var(--shadow-m)",color:"#fff",fontSize:"13px",fontWeight:700},"aria-hidden":"true",children:C.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:he}),!u&&t("p",{class:"mono truncate",style:{marginTop:"2px",fontSize:"11.5px",color:"var(--ink-3)"},title:q,children:q})]}),t("span",{style:{flex:"1 1 60px"}}),l("div",{class:"flex flex-wrap items-center",style:{gap:"7px"},children:[!u&&t("button",{type:"button",class:Qe,style:De,"aria-expanded":k,onClick:()=>b(E=>!E),children:k?"Hide context":`Context · ${B.length} MCP, ${A.length} plugins`}),!u&&t(Ll,{session:e}),!u&&t(Il,{entry:h}),!u&&t(El,{session:e,entry:h}),c&&t(I,{label:"Restart",variant:"secondary",size:"sm",onClick:R}),e.status==="active"&&!u&&t(I,{label:"Mark done",variant:"primary",size:"sm",onClick:a})]})]}),!u&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(138px, 1fr))",gap:"9px"},children:[t(ut,{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(ut,{index:1,label:"Tokens",children:(L==null?void 0:L.tokens)!=null?nr(L.tokens):"—"}),t(ut,{index:2,label:"Cost",color:"var(--green)",children:(L==null?void 0:L.cost)!=null?ar(L.cost):"—"}),S&&t(ut,{index:3,label:"Commits",children:(M==null?void 0:M.commits)??"—"}),S&&t(ut,{index:4,label:"Unpushed",color:M&&kt(M)>0?"var(--orange)":"var(--ink)",children:M?kt(M):"—"}),t(Wl,{session:e,onOpen:r}),F&&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:()=>un(F,"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:F})]})]}),k&&l("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:"9px",animation:"riseIn .3s var(--ease) both"},children:[t($n,{title:`MCP · ${B.length}`,tone:"--blue",empty:"No MCP servers",items:B.map(E=>({name:E.name,title:`${E.type} · ${E.source}`}))}),t($n,{title:`Plugins · ${A.length}`,tone:"--green",empty:"No plugins",items:A.map(E=>({name:E.name,muted:!E.enabled,title:`${E.enabled?"enabled":"disabled"} · ${E.marketplace}${E.hasMcp?` · MCP ${E.mcpName??""}`:""}`}))}),t($n,{title:"Stack",tone:null,empty:"Nothing detected",items:z.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:[F||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(so,{wsUrl:P,theme:zt.value,focused:n,onOutput:E=>Ao(p,E),onExit:()=>s(!0),onGiveUp:()=>s(!0),onConnectionChange:f}),!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…"})})]})]})})]})},ve={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:ve,children:e}),a]}),Ml={dev:"New dev task",review:"Review a pull request",loop:"New loop",general:"New session"},Fl={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."},Bl={dev:"Task name or ticket URL",review:"Pull request number or URL",loop:"Loop prompt",general:""},_l={dev:"fix-auth or https://linear.app/…",review:"42 or https://github.com/…/pull/42",loop:"Babysit my open PRs…",general:""},Kl=[{id:"",label:"Auto"},{id:"feature",label:"feature"},{id:"bugfix",label:"bugfix"},{id:"refactor",label:"refactor"}],zn={boxShadow:"var(--shadow-s)"},Bt=e=>/^[\w./:#-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Ul=({projects:e,accounts:n,initialAccount:a,initialProject:r,onClose:o,onCreated:i,onOpenAccounts:c})=>{var Wt;const s=pa(we.value,Ye.value),[d,f]=v(""),[g,y]=v(""),[m,w]=v(""),[k,b]=v(""),[p,x]=v(""),[S,h]=v(!1),[C,u]=v(!1),[z,L]=v(""),[N,O]=v("claude"),T=Tt();D(()=>{ye()},[]);const P=pn.value,R=P!=null&&P.available?P.doctor:null,B=Object.keys(e),A=s==="general",M=s==="review",F=s==="loop",q=we.value,he=!z.trim()||/^\d+[smh]$/.test(z.trim()),E=n.length>0?n:Array.from(new Set(Object.values(e).map(_=>_.account).filter(Boolean))).sort(),Z=d?B.filter(_=>{var $;return(($=e[_])==null?void 0:$.account)===d}):B;D(()=>{const _=r&&!a&&e[r]?e[r].account:void 0,$=a??_,W=$&&E.includes($)?$:E[0]??"";f(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:!A&&K.length>0?K[0]:"";V&&y(V)},[]);const te=ie(!1);D(()=>{if(!te.current){te.current=!0;return}!A&&!g&&Z.length>0&&y(Z[0])},[A]);const Se=_=>{f(_);const $=B.filter(W=>{var K;return((K=e[W])==null?void 0:K.account)===_});!A&&$.length>0&&!$.includes(g)?y($[0]):A&&g&&!$.includes(g)&&y("")},At=R?Ga(g||void 0,d,e,R):"claude";D(()=>{!R||!d||O(F?"claude":At)},[P==null?void 0:P.available,d,g,F]);const Ce=R?We(R,d,N):void 0,It=!R||qe(P,N,"skip_permissions"),$e=!R||N==="claude",Be=$e||!A,xe=R?ua(N,Ce,F):null,Lt=ge(N).label;D(()=>{It||h(!1),x($e?"":(Ce==null?void 0:Ce.model)??"")},[N]),D(()=>{$e||x((Ce==null?void 0:Ce.model)??"")},[d]);const Et=vr(q),tt=yr(P,N,q),Nt=!A&&!q.trim()||F&&!he||!A&&!g||!!xe,Ot=async()=>{if(!Nt){u(!0);try{const _={type:s,account:d||void 0,skipPermissions:S||void 0};R&&(_.harness=N),F?(_.project=g,_.loopPrompt=q.trim(),_.loopInterval=z.trim()||void 0):A?g&&(_.project=g):(_.project=g,_.task=q.trim(),_.description=m.trim()||void 0,_.workflow=k||void 0),_.model=Be&&p||void 0;const W=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)})).json();W.ok?(j(A?"Session started":F?"Loop started":"Task started","success"),A||rn(""),i(W.session)):j(W.error??"Failed to start","error")}catch{j("Failed to start","error")}finally{u(!1)}}},gn=d||E[0]||"default",xn=A?`cw launch ${Bt(gn)}`:F?`cw loop ${g||"<project>"} ${Bt(q.trim()||"<prompt>")}${z.trim()?` --every ${z.trim()}`:""}`:M?`cw review ${g||"<project>"} ${Bt(q.trim()||"<pr>")}`:`cw work ${g||"<project>"} ${q.trim()?Bt(((Wt=hn(q))==null?void 0:Wt.kind)==="name"?Lr(q):q.trim()):"<task>"}`;return l(Ze,{title:Ml[s],onClose:o,children:[t(Or,{fill:!0}),t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)",lineHeight:1.5},children:Fl[s]}),!A&&l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t(U,{label:Bl[s],children:t("input",{class:"field",style:{...zn,fontSize:"14px"},placeholder:_l[s],value:q,ref:T,onInput:_=>{const $=_.target.value;F?we.value=$:rn($)},onKeyDown:_=>{_.key==="Enter"&&Ot()}})}),!F&&t(Nr,{ctx:{type:s,project:g,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 $=_.target.value;Se($),an.value=$},children:E.map(_=>t("option",{value:_,children:_},_))})}),t(U,{plain:!0,label:A?"Project · optional":"Project",children:t(Er,{label:"Project",size:"md",width:"100%",value:g,placeholder:A?"No project":"Choose…",onChange:_=>{y(_),Ge.value=_},options:[...A?[{value:"",label:"No project"}]:[],...Vn(e,E,Z)]})})]}),F&&l(U,{label:"Interval · optional",children:[t("input",{class:"field mono",style:{...zn,borderColor:he?void 0:"var(--red)"},value:z,placeholder:"auto — Claude decides the pace",onInput:_=>L(_.target.value)}),!he&&t("span",{style:{fontSize:"12px",color:"var(--red)"},children:"Use forms like 30s, 5m, 2h — or leave it empty to self-pace"})]}),(s==="dev"||M)&&t(U,{label:"Description (optional)",children:t("textarea",{class:"field",rows:3,style:zn,placeholder:"Context the agent reads first…",value:m,onInput:_=>w(_.target.value)})}),R&&t(wl,{doctor:R,account:d,value:N,defaultHarness:At,isLoop:F,onChange:O,onOpenAccounts:c}),Be&&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:ve,children:"Model"}),$e?t(de,{fill:!0,size:"sm",label:"Model",tabs:bo.map(_=>({id:_.id,label:_.label})),active:p,onChange:x}):t("input",{class:"field mono",style:{height:"32px",fontSize:"12.5px"},value:p,placeholder:"the account's model","aria-label":"Model",onInput:_=>x(_.target.value)})]}),s==="dev"&&l("div",{class:"flex flex-col min-w-0",style:{gap:"5px"},children:[t("span",{style:ve,children:"Workflow"}),t(de,{fill:!0,size:"sm",label:"Workflow",tabs:Kl,active:k,onChange:b})]})]}),It&&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(cn,{checked:S,onChange:h,label:"Bypass permissions"})]}),tt&&l("p",{style:{fontSize:"12.5px",padding:"10px 12px",borderRadius:"12px",background:Q("--orange"),color:"var(--ink)"},children:[Lt," has no MCP and CW has no ",Et==="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:C?"Starting…":A?"Launch session":F?"Start loop":M?"Start review":"Start task",variant:"primary",size:"lg",block:!0,loading:C,disabled:Nt,onClick:Ot}),xe&&t("p",{style:{fontSize:"12px",color:"var(--red)",textAlign:"center"},children:xe}),t("p",{class:"mono",style:{fontSize:"11.5px",color:"var(--ink-3)",textAlign:"center",overflowWrap:"anywhere"},children:xn})]})},on=e=>`/api/skills/plugins/${encodeURIComponent(e)}`;async function St(e,n){try{return await ce(e,n)}catch(a){return j(le(a),"error"),null}}const Te=Y(null),Yn=Y(null);async function Ct(){const e=await fetch("/api/skills/plugins");if(!e.ok)throw new Error("fetch failed");Te.value=await e.json()}async function ln(){const e=await fetch("/api/skills/marketplaces");if(!e.ok)throw new Error("fetch failed");Yn.value=await e.json()}const Fe=({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]}),Le={fontSize:"11.5px",color:"var(--ink-3)"},Hl={fontSize:"11.5px",fontWeight:600,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},ql=e=>{const n=e.indexOf(" ");return n<0?{name:e,hint:""}:{name:e.slice(0,n),hint:e.slice(n+1).trim()}},Zt=e=>`${e.project}::${Me(e)}`;function Gl(e,n){var o;const a=new Set((o=(Te.value??[]).find(i=>i.name===n))==null?void 0:o.installs.filter(i=>i.scope==="account"&&i.enabled).map(i=>i.scopeRef)),r=Ie.value;return e.filter(i=>i.harness==="claude"&&i.status==="active"&&a.has(i.account)&&r[Zt(i)])}const Vl=({command:e,plugin:n,note:a,onClose:r})=>{const{name:o,hint:i}=ql(e),[c,s]=v(null),[d,f]=v(null),[g,y]=v(""),[m,w]=v(!1);D(()=>{Promise.all([jt("GET","/api/cw/spaces"),Te.value?null:Ct()]).then(([C])=>s(C),()=>s([]))},[]);const k=c?Gl(c,n):[],b=k.find(C=>Zt(C)===d)??k[0],p=g.trim()?`${o} ${g.trim()}`:o,x=i.startsWith("<")&&!g.trim(),h=l(H,{children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:r}),t(I,{label:m?"Sending…":"Run",variant:"primary",disabled:!b||x||m,onClick:async()=>{if(b){w(!0);try{await ce("/api/cw/terminal/command",{project:b.project,sessionDir:Me(b),line:p}),j(`Sent ${o} to ${ue(b)}`,"success"),r()}catch(C){j(le(C),"error")}finally{w(!1)}}}})]});return t(Re,{open:!0,title:`Run ${o}`,onClose:r,footer:h,children:l("div",{class:"flex flex-col",style:{gap:"12px",fontSize:"13px"},children:[i&&l("label",{class:"flex flex-col",style:{gap:"4px"},children:[l("span",{style:Le,children:[o," ",i]}),t("input",{type:"text",class:"field",value:g,placeholder:i.replace(/[<>[\]]/g,""),onInput:C=>y(C.target.value)})]}),c===null&&t("p",{style:Le,children:"Looking for open sessions…"}),c&&k.length===0&&l("p",{style:Le,children:["No Claude Code session of an account with ",n," is open in Forge. Start one from Tasks, then run it here."]}),k.length>0&&l("div",{class:"flex flex-col",style:{gap:"4px"},children:[t("span",{style:Le,children:"Session"}),k.map(C=>l("label",{class:"flex items-center cursor-pointer",style:{gap:"8px"},children:[t("input",{type:"radio",name:"session",checked:b===C,onChange:()=>f(Zt(C))}),t("span",{style:{fontWeight:500},children:ue(C)}),t("span",{style:Le,children:[se(C),C.account].filter(Boolean).join(" · ")})]},Zt(C)))]}),t("code",{style:{fontSize:"11.5px",color:"var(--ink-2)"},children:p}),a&&t("p",{style:Le,children:a}),t("p",{style:Le,children:"Forge types it into the session's terminal, as if you had."})]})})},Qn=({command:e,plugin:n,note:a,disabled:r})=>{const[o,i]=v(!1);return l(H,{children:[t("button",{type:"button",style:{...Hl,opacity:r?.5:1,cursor:r?"default":"pointer"},disabled:r,onClick:()=>i(!0),children:"Run…"}),o&&t(Vl,{command:e,plugin:n,note:a,onClose:()=>i(!1)})]})};function Jl(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 Yl(e){return`add-skill-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,30).replace(/-+$/,"")||Date.now()}`}function Ql(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
+ `)}async function _r(e,n,a){await St("/api/skills/plugins/install",{id:e,account:a})&&(j(`${n} installed in ${a} · applies to new sessions`,"success"),await Promise.all([Ct(),ln()]).catch(()=>{}))}const Kr=(e,n)=>n?e.skills.filter(a=>a.name.toLowerCase().includes(n)||a.description.toLowerCase().includes(n)):e.skills,Zl={padding:"6px 11px",fontSize:"11px",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase",color:"var(--ink-3)"},Xl=e=>/^[0-9a-f]{12,}$/.test(e)?e.slice(0,7):e,ei=e=>{var n;return(n=e.installs.find(a=>a.update))==null?void 0:n.latest},ti=({list:e,query:n,selected:a,onSelect:r})=>{const o=e.filter(c=>!n||Kr(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(H,{children:[...i].map(([c,s])=>l("div",{style:{marginBottom:"8px"},children:[t("p",{class:"truncate",style:Zl,children:c}),s.map(d=>{const f=a===d.id,g=ei(d),y=[...new Set(d.installs.map(m=>Xl(m.version)))].join(" · ");return l("button",{type:"button","aria-current":f?"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 ${f?"var(--hair)":"transparent"}`,background:f?"var(--card)":"transparent",boxShadow:f?"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}),g&&l("span",{class:"mono shrink-0",title:`Update to ${g} 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:["↑ ",g]})]}),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))})},Rn={fontSize:"12px",fontWeight:600,color:"var(--ink-2)",margin:"0 0 8px"},Ur={gap:"10px",padding:"9px 12px",borderRadius:"11px",border:"1px solid var(--hair)",background:"var(--card)"},ni=({plugin:e,install:n})=>{const[a,r]=v(null),o=n.scope==="global"?"global":n.scopeRef,i=async()=>{r("update");const d=await St(`${on(e.id)}/update`,{scope:n.scope,scopeRef:n.scopeRef});r(null),d&&(j(`${e.name} ${d.version??""} · applies to new sessions`,"success"),Ct().catch(()=>{}))},c=async()=>{if(!confirm(`Uninstall ${e.name} from ${o}?`))return;r("uninstall");const d=await St(`${on(e.id)}/uninstall`,{scope:n.scope,scopeRef:n.scopeRef});r(null),d&&(j(`${e.name} uninstalled from ${o} · applies to new sessions`,"success"),await Promise.all([Ct(),ln()]).catch(()=>{}))},s=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:Ur,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:s.color},children:s.text}),t("span",{style:{fontSize:"11.5px",color:n.enabled?"var(--green)":"var(--ink-3)"},children:n.enabled?"on":"off"}),t(I,{label:a==="update"?"Updating…":n.update?`Update to ${n.latest}`:"Check & update",variant:n.update?"primary":"secondary",size:"sm",loading:a==="update",disabled:a!==null,onClick:i}),t(I,{label:a==="uninstall"?"Uninstalling…":"Uninstall",variant:"secondary",size:"sm",loading:a==="uninstall",disabled:a!==null,onClick:c})]})},ai=({plugin:e,account:n})=>{const[a,r]=v(!1);return l("div",{class:"flex items-center",style:Ur,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 _r(e.id,e.name,n),r(!1)}})]})},ri=({plugin:e,name:n,onBack:a})=>{const[r,o]=v(null),[i,c]=v(!1);return D(()=>{let s=!1;return o(null),c(!1),fetch(`${on(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(H,{children:[t(Fe,{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})]})]})},oi=({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(H,{children:[l(Fe,{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:Rn,children:"Accounts · versions"}),l("div",{class:"flex flex-col",style:{gap:"6px"},children:[e.installs.map(s=>t(ni,{plugin:e,install:s},`${s.scope}/${s.scopeRef}`)),c.map(s=>t(ai,{plugin:e,account:s},s))]})]}),e.commands.length>0&&l("section",{children:[l("h3",{style:Rn,children:["Commands (",e.commands.length,")"]}),t("div",{class:"flex flex-col",style:{gap:"4px"},children:e.commands.map(s=>l("div",{class:"flex items-center",style:{gap:"10px",padding:"8px 11px"},children:[l("span",{class:"mono shrink-0",style:{fontSize:"12.5px",fontWeight:600},children:[s.name,s.argumentHint?` ${s.argumentHint}`:""]}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"12px",color:"var(--ink-2)"},children:s.description}),t(Qn,{command:s.argumentHint?`${s.name} ${s.argumentHint}`:s.name,plugin:e.name})]},s.name))})]}),l("section",{children:[l("h3",{style:Rn,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:Kr(e,a).map(s=>l("div",{class:"flex items-center hover:bg-elev",style:{gap:"10px",paddingRight:"11px",borderRadius:"10px"},children:[l("button",{type:"button",class:"flex flex-1 min-w-0 items-center text-left cursor-pointer",style:{gap:"10px",padding:"8px 11px",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.command&&t(Qn,{command:`${s.command} ${s.argumentHint??"[what to do]"}`,plugin:e.name})]},s.name))})]})]})})]})},li=({accounts:e})=>{const[n,a]=v(""),r=e.includes(n)?n:e[0]??"",[o,i]=v(""),[c,s]=v(""),[d,f]=v(""),[g,y]=v(!1),[m,w]=v(null);D(()=>{Yn.value===null&&ln().catch(()=>j("Failed to load marketplaces","error"))},[]);const k=Yn.value,b=(k==null?void 0:k.find(u=>u.name===o))??(k==null?void 0:k[0]),p=new Set((Te.value??[]).flatMap(u=>u.installs.some(z=>z.scope==="account"&&z.scopeRef===r)?[u.id]:[])),x=c.trim().toLowerCase(),S=((b==null?void 0:b.plugins)??[]).filter(u=>!x||u.name.toLowerCase().includes(x)||u.description.toLowerCase().includes(x)),h=async()=>{y(!0);const u=await St("/api/skills/marketplaces",{source:d.trim(),account:r});y(!1),u&&(j(`Marketplace added to ${r}`,"success"),f(""),await ln().catch(()=>{}))},C=async(u,z)=>{w(u),await _r(u,z,r),w(null)};return l(H,{children:[t(Fe,{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:u=>a(u.target.value),children:e.map(u=>t("option",{value:u,children:u},u))})}),k&&k.length>0&&t(U,{label:"Marketplace",children:t("select",{class:"field",value:b==null?void 0:b.name,onChange:u=>i(u.target.value),children:k.map(u=>l("option",{value:u.name,children:[u.name," · ",u.source]},u.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:u=>f(u.target.value),onKeyDown:u=>{u.key==="Enter"&&d.trim()&&h()}}),t(I,{label:g?"Adding…":"Add",variant:"secondary",size:"sm",loading:g,disabled:!d.trim()||!r,onClick:h})]})}),b&&b.plugins.length>0&&t("input",{class:"field",type:"search","aria-label":"Filter plugins",value:c,placeholder:`Filter ${b.plugins.length} plugins`,onInput:u=>s(u.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."}),b&&S.length===0&&t("p",{style:{fontSize:"13px",color:"var(--ink-2)"},children:x?"No plugin matches.":"This marketplace lists no plugins."}),S.map((u,z)=>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(z,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:u.name}),u.category&&t("span",{class:"mono shrink-0",style:{fontSize:"11px",color:"var(--ink-3)"},children:u.category})]}),u.description&&t("div",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-2)"},title:u.description,children:u.description})]}),p.has(u.id)?t("span",{style:{fontSize:"12px",color:"var(--green)"},children:"Installed"}):t(I,{label:m===u.id?"Installing…":"Install",variant:"secondary",size:"sm",loading:m===u.id,disabled:m!==null||!r,onClick:()=>C(u.id,u.name)})]},u.id))]})]})},ii=({plugin:e,accounts:n,onSubmit:a,onCancel:r})=>{const o=Jl(e),i=e.installs.filter(p=>p.scope==="account").map(p=>p.scopeRef),c=n.find(p=>i.includes(p))??n[0]??"",[s,d]=v(""),[f,g]=v(o[0]??""),[y,m]=v(c),[w,k]=v(!1),b=async()=>{k(!0);try{await a(s.trim(),o.length>1?f:void 0,y)}finally{k(!1)}};return l(H,{children:[t(Fe,{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:f,onChange:p=>g(p.target.value),children:o.map(p=>t("option",{value:p,children:p},p))})}),n.length>0&&t(U,{label:"Account",children:t("select",{class:"field",value:y,onChange:p=>m(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(I,{label:w?"Starting…":"Start task",variant:"primary",loading:w,disabled:!s.trim()||!y,onClick:b}),t(I,{label:"Cancel",variant:"secondary",onClick:r})]})]})})]})},si={global:"--blue",account:"--orange",project:"--green"},_t=e=>`${e.scope}/${e.scopeRef}/${e.dirName}`;function ci(e,n){return e==="global"?"global":e==="account"?`account/${encodeURIComponent(n)}`:`project/${encodeURIComponent(n)}`}const gt=e=>e.scope==="global"?"Global":`${e.scope==="account"?"Account":"Project"} · ${e.scopeRef}`,di=e=>e.scope==="global"?`~/.claude/skills/${e.dirName}`:e.scope==="account"?`~/.cw/accounts/${e.scopeRef}/skills/${e.dirName}`:`<${e.scopeRef}>/.claude/skills/${e.dirName}`,pi={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."},Hr=e=>e[0]?{scope:"account",scopeRef:e[0]}:{scope:"global",scopeRef:"global"},Zn=e=>e.scope==="global"||e.scopeRef!=="",qr=({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(H,{children:[l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:ve,children:"Scope"}),t(de,{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:pi[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))})})]})},ui=(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),Gr=(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(...Gr(o,n+" "))):a.push(`${n}${r}: ${String(o??"")}`);return a},hi=({skill:e,accounts:n,projects:a,onDeleted:r,onCopied:o,onRun:i})=>{const[c,s]=v(null),[d,f]=v(!0),[g,y]=v("SKILL.md"),[m,w]=v(""),[k,b]=v({}),[p,x]=v(!1),S=`/api/skills/${ci(e.scope,e.scopeRef)}/${encodeURIComponent(e.dirName)}`;D(()=>{let T=!1;return f(!0),y("SKILL.md"),fetch(S).then(P=>{if(!P.ok)throw new Error("fetch failed");return P.json()}).then(P=>{if(T)return;s(P);const R=Gr(P.frontmatter);w(R.length>0?`---
3
3
  ${R.join(`
4
4
  `)}
5
5
  ---
6
6
 
7
7
  ${P.body}`:P.body),b(Object.fromEntries(P.references.map(B=>[B.name,B.content])))}).catch(()=>{T||(s(null),j("Failed to load skill","error"))}).finally(()=>{T||f(!1)}),()=>{T=!0}},[S]);const h=async()=>{x(!0);const T=g==="SKILL.md";try{const R=await(await fetch(T?S:`${S}/references/${encodeURIComponent(g)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:T?m:k[g]??""})})).json();R.ok?j(T?"Skill saved":"Reference saved","success"):j(R.error??"Failed to save","error")}catch{j("Failed to save","error")}finally{x(!1)}},C=async()=>{if(confirm(`Delete the skill "${e.name}" permanently?`))try{const P=await(await fetch(S,{method:"DELETE"})).json();P.ok?(j("Skill deleted","info"),r()):j(P.error??"Failed to delete","error")}catch{j("Failed to delete","error")}},u=async T=>{try{const R=await(await fetch("/api/skills/copy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:{scope:e.scope,scopeRef:e.scopeRef,name:e.dirName},to:T})})).json();R.ok?(j(`Copied to ${gt(T)}`,"success"),o()):j(R.error??"Failed to copy","error")}catch{j("Failed to copy","error")}},z=async()=>{const T=prompt("Reference filename (e.g. examples.md):");if(!(T!=null&&T.trim()))return;const P=T.trim(),R=`# ${P}
8
- `;try{const A=await(await fetch(`${S}/references/${encodeURIComponent(P)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:R})})).json();A.ok?(b(D=>({...D,[P]:R})),s(D=>D&&{...D,references:[...D.references,{name:P,content:R}]}),y(P),j("Reference added","success")):j(A.error??"Failed to add reference","error")}catch{j("Failed to add reference","error")}},L=async T=>{if(confirm(`Delete reference "${T}"?`))try{const R=await(await fetch(`${S}/references/${encodeURIComponent(T)}`,{method:"DELETE"})).json();R.ok?(b(B=>{const{[T]:A,...D}=B;return D}),s(B=>B&&{...B,references:B.references.filter(A=>A.name!==T)}),g===T&&y("SKILL.md"),j("Reference deleted","info")):j(R.error??"Failed to delete reference","error")}catch{j("Failed to delete reference","error")}},N=["SKILL.md",...(c==null?void 0:c.references.map(T=>T.name))??[]],O=ui(e,n,a);return l(H,{children:[l(Fe,{title:e.name,sub:`${gt(e)} · ${di(e)}`,children:[t(I,{label:"Delete",variant:"danger",size:"sm",onClick:C}),l("select",{class:"field","aria-label":"Copy to",style:{height:"30px",padding:"0 8px",fontSize:"12.5px",width:"auto"},value:"",disabled:!c,onChange:T=>{const P=T.target,R=O[Number(P.value)];P.value="",R&&u(R)},children:[t("option",{value:"",disabled:!0,children:"Copy to…"}),O.map((T,P)=>t("option",{value:P,children:gt(T)},`${T.scope}/${T.scopeRef}`))]}),t(I,{label:"Run in session",variant:"secondary",size:"sm",onClick:i}),t(I,{label:p?"Saving…":"Save",variant:"primary",size:"sm",loading:p,disabled:!c,onClick:h})]}),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(T=>{const P=g===T;return l("span",{class:"inline-flex items-center",style:{gap:"4px",padding:P?"5px 8px 5px 11px":"5px 11px",borderRadius:"9px",background:P?"var(--card)":"transparent",border:`1px solid ${P?"var(--hair)":"transparent"}`,boxShadow:P?"var(--shadow-s)":"none"},children:[t("button",{type:"button",role:"tab","aria-selected":P,class:"mono cursor-pointer",style:{border:0,background:"none",padding:0,fontSize:"12px",fontWeight:P?600:400,color:P?"var(--ink)":"var(--ink-3)"},onClick:()=>y(T),children:T}),P&&T!=="SKILL.md"&&t("button",{type:"button","aria-label":`Delete ${T}`,class:"grid place-items-center cursor-pointer text-ink3 hover:text-red",style:{border:0,background:"none",padding:0},onClick:()=>L(T),children:t("span",{class:"i-lucide-x",style:{width:"12px",height:"12px"}})})]},T)}),t("span",{class:"flex-1"}),t("button",{type:"button",class:"cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px",style:{padding:"5px 10px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--blue)",fontSize:"12px",fontWeight:500},onClick:z,disabled:!c,children:"+ Reference"})]}),t("div",{class:"flex-1 min-h-0",style:{padding:"12px 20px 20px"},children:d?t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Loading skill…"}):c?t("textarea",{class:"field mono w-full h-full","aria-label":g,spellcheck:!1,style:{height:"100%",padding:"14px 16px",borderRadius:"14px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink)",fontSize:"12.5px",lineHeight:1.7,resize:"none",outline:"none",boxShadow:"var(--shadow-s)",minHeight:"240px"},value:g==="SKILL.md"?m:k[g]??"",onInput:T=>{const P=T.target.value;g==="SKILL.md"?w(P):b(R=>({...R,[g]:P}))}}):t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Skill not found."})})]})},fi=({query:e,accounts:n,projects:a,onInstalled:r})=>{const[o,i]=v(null),[c,s]=v(null),[d,f]=v(()=>Hr(n));M(()=>{let y=!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=>{y||i(m.results)}).catch(()=>{y||(i([]),j("Failed to search skills","error"))}),()=>{y=!0}},[e]);const g=async y=>{s(y.slug);try{const w=await(await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:y.repo,skill:y.skillId,...d})})).json();w.ok?(j(`Installed in ${gt(d)}`,"success"),r()):j(w.error??"Failed to install","error")}catch{j("Failed to install","error")}finally{s(null)}};return l(H,{children:[t(Fe,{title:`skills.sh · “${e}”`,sub:`Installs into ${gt(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(qr,{accounts:n,projects:a,value:d,onChange:f})}),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,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:y.name}),l("div",{class:"mono truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[y.repo," · ",y.installs," installs"]})]}),t(I,{label:c===y.slug?"Installing…":"Install",variant:"secondary",size:"sm",loading:c===y.slug,disabled:!Yn(d),onClick:()=>g(y)})]},y.slug))]})]})},gi=({accounts:e,projects:n,onCreated:a,onCreateWithAI:r})=>{const[o,i]=v(()=>Hr(e)),[c,s]=v(""),[d,f]=v(""),[g,y]=v(!1),{scope:m,scopeRef:w}=o,k=async()=>{if(!c.trim())return;y(!0);const b=`---
8
+ `;try{const A=await(await fetch(`${S}/references/${encodeURIComponent(P)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:R})})).json();A.ok?(b(M=>({...M,[P]:R})),s(M=>M&&{...M,references:[...M.references,{name:P,content:R}]}),y(P),j("Reference added","success")):j(A.error??"Failed to add reference","error")}catch{j("Failed to add reference","error")}},L=async T=>{if(confirm(`Delete reference "${T}"?`))try{const R=await(await fetch(`${S}/references/${encodeURIComponent(T)}`,{method:"DELETE"})).json();R.ok?(b(B=>{const{[T]:A,...M}=B;return M}),s(B=>B&&{...B,references:B.references.filter(A=>A.name!==T)}),g===T&&y("SKILL.md"),j("Reference deleted","info")):j(R.error??"Failed to delete reference","error")}catch{j("Failed to delete reference","error")}},N=["SKILL.md",...(c==null?void 0:c.references.map(T=>T.name))??[]],O=ui(e,n,a);return l(H,{children:[l(Fe,{title:e.name,sub:`${gt(e)} · ${di(e)}`,children:[t(I,{label:"Delete",variant:"danger",size:"sm",onClick:C}),l("select",{class:"field","aria-label":"Copy to",style:{height:"30px",padding:"0 8px",fontSize:"12.5px",width:"auto"},value:"",disabled:!c,onChange:T=>{const P=T.target,R=O[Number(P.value)];P.value="",R&&u(R)},children:[t("option",{value:"",disabled:!0,children:"Copy to…"}),O.map((T,P)=>t("option",{value:P,children:gt(T)},`${T.scope}/${T.scopeRef}`))]}),t(I,{label:"Run in session",variant:"secondary",size:"sm",onClick:i}),t(I,{label:p?"Saving…":"Save",variant:"primary",size:"sm",loading:p,disabled:!c,onClick:h})]}),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(T=>{const P=g===T;return l("span",{class:"inline-flex items-center",style:{gap:"4px",padding:P?"5px 8px 5px 11px":"5px 11px",borderRadius:"9px",background:P?"var(--card)":"transparent",border:`1px solid ${P?"var(--hair)":"transparent"}`,boxShadow:P?"var(--shadow-s)":"none"},children:[t("button",{type:"button",role:"tab","aria-selected":P,class:"mono cursor-pointer",style:{border:0,background:"none",padding:0,fontSize:"12px",fontWeight:P?600:400,color:P?"var(--ink)":"var(--ink-3)"},onClick:()=>y(T),children:T}),P&&T!=="SKILL.md"&&t("button",{type:"button","aria-label":`Delete ${T}`,class:"grid place-items-center cursor-pointer text-ink3 hover:text-red",style:{border:0,background:"none",padding:0},onClick:()=>L(T),children:t("span",{class:"i-lucide-x",style:{width:"12px",height:"12px"}})})]},T)}),t("span",{class:"flex-1"}),t("button",{type:"button",class:"cursor-pointer transition-all duration-180 ease-spring hover:-translate-y-px",style:{padding:"5px 10px",borderRadius:"9px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--blue)",fontSize:"12px",fontWeight:500},onClick:z,disabled:!c,children:"+ Reference"})]}),t("div",{class:"flex-1 min-h-0",style:{padding:"12px 20px 20px"},children:d?t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Loading skill…"}):c?t("textarea",{class:"field mono w-full h-full","aria-label":g,spellcheck:!1,style:{height:"100%",padding:"14px 16px",borderRadius:"14px",border:"1px solid var(--hair)",background:"var(--card)",color:"var(--ink)",fontSize:"12.5px",lineHeight:1.7,resize:"none",outline:"none",boxShadow:"var(--shadow-s)",minHeight:"240px"},value:g==="SKILL.md"?m:k[g]??"",onInput:T=>{const P=T.target.value;g==="SKILL.md"?w(P):b(R=>({...R,[g]:P}))}}):t("p",{style:{padding:"24px 0",textAlign:"center",fontSize:"13px",color:"var(--ink-2)"},children:"Skill not found."})})]})},fi=({query:e,accounts:n,projects:a,onInstalled:r})=>{const[o,i]=v(null),[c,s]=v(null),[d,f]=v(()=>Hr(n));D(()=>{let y=!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=>{y||i(m.results)}).catch(()=>{y||(i([]),j("Failed to search skills","error"))}),()=>{y=!0}},[e]);const g=async y=>{s(y.slug);try{const w=await(await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:y.repo,skill:y.skillId,...d})})).json();w.ok?(j(`Installed in ${gt(d)}`,"success"),r()):j(w.error??"Failed to install","error")}catch{j("Failed to install","error")}finally{s(null)}};return l(H,{children:[t(Fe,{title:`skills.sh · “${e}”`,sub:`Installs into ${gt(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(qr,{accounts:n,projects:a,value:d,onChange:f})}),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,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:y.name}),l("div",{class:"mono truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:[y.repo," · ",y.installs," installs"]})]}),t(I,{label:c===y.slug?"Installing…":"Install",variant:"secondary",size:"sm",loading:c===y.slug,disabled:!Zn(d),onClick:()=>g(y)})]},y.slug))]})]})},gi=({accounts:e,projects:n,onCreated:a,onCreateWithAI:r})=>{const[o,i]=v(()=>Hr(e)),[c,s]=v(""),[d,f]=v(""),[g,y]=v(!1),{scope:m,scopeRef:w}=o,k=async()=>{if(!c.trim())return;y(!0);const b=`---
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 x=await(await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:m,scopeRef:w,name:c.trim(),content:b})})).json();x.ok?(j("Skill created","success"),a()):j(x.error??"Failed to create skill","error")}catch{j("Failed to create skill","error")}finally{y(!1)}};return l(H,{children:[t(Fe,{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(qr,{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:b=>s(b.target.value)})}),t(U,{label:"Description",children:t("textarea",{class:"field",rows:3,value:d,placeholder:"What does this skill do?",onInput:b=>f(b.target.value)})}),l("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(I,{label:g?"Creating…":"Create",variant:"primary",loading:g,disabled:!c.trim()||!Yn(o),onClick:k}),r&&t(I,{label:"Create with AI",variant:"secondary",disabled:!d.trim()||!Yn(o),title:"Starts a session that drafts the skill",onClick:()=>r(m,w,d.trim())})]})]})})]})},xi=({accounts:e,projects:n,onCreateWithAI:a,onRunSkill:r,onProposeSkill:o})=>{const[i,c]=v(""),[s,d]=v({kind:"empty"}),[f,g]=v("skills"),[y,m]=v(ht.value===null),w=Object.keys(n),k=J(async()=>{try{await Promise.all([Ya(),pn()])}catch{j("Failed to load skills","error")}finally{m(!1)}},[]);M(()=>{(ht.value===null||Ee.value===null)&&k()},[k]);const b=ht.value??[],p=i.trim().toLowerCase(),x=p?b.filter(z=>z.name.toLowerCase().includes(p)||z.description.toLowerCase().includes(p)):b,S=Ee.value??[],h=s.kind==="plugin"||s.kind==="propose"?S.find(z=>z.id===s.id):void 0,C=S.filter(z=>z.installs.some(L=>L.update)).length;M(()=>{s.kind==="empty"&&b.length>0&&d({kind:"editor",skill:b[0]})},[b.length]);const u=s.kind==="editor"?Ft(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(pa,{}),t("h1",{style:{fontSize:"18px",fontWeight:700,letterSpacing:"-0.02em"},children:"Skills"}),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:z=>c(z.target.value),onKeyDown:z=>{z.key==="Enter"&&i.trim()&&d({kind:"explore",query:i.trim()})}}),t(de,{fill:!0,size:"sm",label:"Skills or plugins",tabs:[{id:"skills",label:"Skills",count:b.length},{id:"plugins",label:"Plugins",count:C>0?`${S.length} · ${C}↑`:S.length}],active:f,onChange:z=>{g(z);const L=s.kind==="plugin"||s.kind==="propose"||s.kind==="plugins";z==="plugins"&&!L&&d(S[0]?{kind:"plugin",id:S[0].id}:{kind:"plugins"}),z==="skills"&&L&&d(b[0]?{kind:"editor",skill:b[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&&f==="skills"&&x.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:p?"No installed skill matches.":"No skills yet."}),f==="plugins"&&S.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:Ee.value===null?"Loading plugins…":"No Claude Code plugins installed."}),f==="skills"&&x.map(z=>{const L=u===Ft(z);return l("button",{type:"button","aria-current":L?"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 ${L?"var(--hair)":"transparent"}`,background:L?"var(--card)":"transparent",boxShadow:L?"var(--shadow-s)":"none",color:"var(--ink)"},onClick:()=>d({kind:"editor",skill:z}),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(${si[z.scope]})`}}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:z.name}),t("span",{class:"truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"90px"},children:z.scope==="global"?"global":z.scopeRef})]}),z.description&&t("span",{class:"block truncate",style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:z.description})]},Ft(z))}),f==="plugins"&&t(ti,{list:S,query:p,selected:s.kind==="plugin"||s.kind==="propose"?s.id:null,onSelect:z=>d({kind:"plugin",id:z})}),f==="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(hi,{skill:s.skill,accounts:e,projects:w,onCopied:()=>{k()},onRun:()=>r(s.skill),onDeleted:()=>{d({kind:"empty"}),k()}},Ft(s.skill)),s.kind==="create"&&t(gi,{accounts:e,projects:n,onCreateWithAI:a,onCreated:()=>{d({kind:"empty"}),k()}}),s.kind==="explore"&&t(fi,{query:s.query,accounts:e,projects:w,onInstalled:()=>{k()}}),s.kind==="plugins"&&t(li,{accounts:e}),s.kind==="plugin"&&h&&!s.skill&&t(oi,{plugin:h,accounts:e,query:p,onSelectSkill:z=>d({kind:"plugin",id:h.id,skill:z}),onPropose:()=>d({kind:"propose",id:h.id})}),s.kind==="plugin"&&h&&s.skill&&t(ri,{plugin:h,name:s.skill,onBack:()=>d({kind:"plugin",id:h.id})},s.skill),s.kind==="propose"&&h&&t(ii,{plugin:h,accounts:e,onCancel:()=>d({kind:"plugin",id:h.id}),onSubmit:async(z,L,N)=>{await o(h,z,L,N)&&d({kind:"plugin",id:h.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(I,{label:"New skill",variant:"primary",onClick:()=>d({kind:"create"})})]})})]})]})},zn={auto:"qa:auto",escalated:"qa:needs-human",blocked:"qa:blocked"},Ta="<!-- qa-pilot:decision",mi="-->",vi=["auto","escalate","blocked"],yi=["pass","fail","warn"],bi=["journey","file","severity","artifact"],Ne=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pe=e=>typeof e=="string",xt=e=>typeof e=="number"&&Number.isFinite(e);function ki(e){return Ne(e)&&pe(e.id)&&pe(e.reason)}function wi(e){return!Ne(e)||!pe(e.check)||!pe(e.kind)||!pe(e.message)?!1:bi.every(n=>e[n]===void 0||pe(e[n]))}function Si(e){if(!Ne(e)||e.version!==1||!pe(e.decision)||!vi.includes(e.decision)||!pe(e.sha)||!Array.isArray(e.gates)||!e.gates.every(ki))return!1;const n=e.diff;return!Ne(n)||!xt(n.files)||!xt(n.added)||!xt(n.removed)||!Ne(e.checks)||!Object.values(e.checks).every(a=>pe(a)&&yi.includes(a))?!1:Array.isArray(e.findings)&&e.findings.every(wi)}function Ci(e){const n=e.lastIndexOf(Ta);if(n===-1)return null;const a=n+Ta.length,r=e.indexOf(mi,a);if(r===-1)return null;try{const o=JSON.parse(e.slice(a,r));return Si(o)?o:null}catch{return null}}const $i=["github-actions[bot]","github-actions"];function zi(e){var a;const n=(a=e.author)==null?void 0:a.login;return typeof n=="string"&&$i.includes(n)}function Ri(e){for(let n=e.length-1;n>=0;n--){if(!zi(e[n]))continue;const a=Ci(e[n].body);if(a)return a}return null}function Ti(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(zn.auto)&&n.auto++,r.has(zn.escalated)&&n.escalated++,r.has(zn.blocked)&&n.blocked++}return n}function ji(e,n){return e.sha!==n}const Pi=/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/raw\/([0-9a-f]{40})\/(pr-\d+\/[0-9a-f]{7}\/)$/,Ai=/^artifacts\/[A-Za-z0-9._-]+\.png$/;function Ii(e){const n=e.change;if(!Ne(n)||!xt(n.pixels)||!xt(n.percent)||!pe(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(pe)&&e.elements.length?`${e.elements.join(", ")} · `:""}${a} · ${n.zone}`}function Li(e){const n=Pi.exec(e.evidence??"");if(!n)return[];const[,a,r]=n,o=c=>pe(c)&&Ai.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(!Ne(s)||!pe(s.name))continue;const d={name:s.name};c.journey&&(d.journey=c.journey),pe(s.ai)&&s.ai&&(d.ai=s.ai.slice(0,200));const f=Ii(s);f&&(d.summary=f);const g=o(s.expected),y=o(s.marked)??o(s.actual),m=o(s.diff);g&&(d.before=g),y&&(d.after=y),m&&(d.diff=m),(g||y||m)&&i.push(d)}return i}function Qn(e){const n=an(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 an(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 Ei(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 Ni={pass:"✓",fail:"✗",warn:"!"};function Oi(e){return Ni[e]}const Wi=/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/;function Di(e){const n=an(e);if(!n.ok){const a=n.message.split(`
17
+ `;try{const x=await(await fetch("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:m,scopeRef:w,name:c.trim(),content:b})})).json();x.ok?(j("Skill created","success"),a()):j(x.error??"Failed to create skill","error")}catch{j("Failed to create skill","error")}finally{y(!1)}};return l(H,{children:[t(Fe,{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(qr,{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:b=>s(b.target.value)})}),t(U,{label:"Description",children:t("textarea",{class:"field",rows:3,value:d,placeholder:"What does this skill do?",onInput:b=>f(b.target.value)})}),l("div",{class:"flex flex-wrap",style:{gap:"8px"},children:[t(I,{label:g?"Creating…":"Create",variant:"primary",loading:g,disabled:!c.trim()||!Zn(o),onClick:k}),r&&t(I,{label:"Create with AI",variant:"secondary",disabled:!d.trim()||!Zn(o),title:"Starts a session that drafts the skill",onClick:()=>r(m,w,d.trim())})]})]})})]})},xi=({accounts:e,projects:n,onCreateWithAI:a,onRunSkill:r,onProposeSkill:o})=>{const[i,c]=v(""),[s,d]=v({kind:"empty"}),[f,g]=v("skills"),[y,m]=v(ht.value===null),w=Object.keys(n),k=J(async()=>{try{await Promise.all([Qa(),Ct()])}catch{j("Failed to load skills","error")}finally{m(!1)}},[]);D(()=>{(ht.value===null||Te.value===null)&&k()},[k]);const b=ht.value??[],p=i.trim().toLowerCase(),x=p?b.filter(z=>z.name.toLowerCase().includes(p)||z.description.toLowerCase().includes(p)):b,S=Te.value??[],h=s.kind==="plugin"||s.kind==="propose"?S.find(z=>z.id===s.id):void 0,C=S.filter(z=>z.installs.some(L=>L.update)).length;D(()=>{(s.kind==="plugin"||s.kind==="propose")&&Te.value!==null&&!h&&d({kind:"empty"})},[s,h]),D(()=>{s.kind==="empty"&&b.length>0&&d({kind:"editor",skill:b[0]})},[b.length]);const u=s.kind==="editor"?_t(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(ha,{}),t("h1",{style:{fontSize:"18px",fontWeight:700,letterSpacing:"-0.02em"},children:"Skills"}),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:z=>c(z.target.value),onKeyDown:z=>{z.key==="Enter"&&i.trim()&&d({kind:"explore",query:i.trim()})}}),t(de,{fill:!0,size:"sm",label:"Skills or plugins",tabs:[{id:"skills",label:"Skills",count:b.length},{id:"plugins",label:"Plugins",count:C>0?`${S.length} · ${C}↑`:S.length}],active:f,onChange:z=>{g(z);const L=s.kind==="plugin"||s.kind==="propose"||s.kind==="plugins";z==="plugins"&&!L&&d(S[0]?{kind:"plugin",id:S[0].id}:{kind:"plugins"}),z==="skills"&&L&&d(b[0]?{kind:"editor",skill:b[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&&f==="skills"&&x.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:p?"No installed skill matches.":"No skills yet."}),f==="plugins"&&S.length===0&&t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:Te.value===null?"Loading plugins…":"No Claude Code plugins installed."}),f==="skills"&&x.map(z=>{const L=u===_t(z);return l("button",{type:"button","aria-current":L?"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 ${L?"var(--hair)":"transparent"}`,background:L?"var(--card)":"transparent",boxShadow:L?"var(--shadow-s)":"none",color:"var(--ink)"},onClick:()=>d({kind:"editor",skill:z}),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(${si[z.scope]})`}}),t("span",{class:"flex-1 min-w-0 truncate",style:{fontSize:"13px",fontWeight:600},children:z.name}),t("span",{class:"truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"90px"},children:z.scope==="global"?"global":z.scopeRef})]}),z.description&&t("span",{class:"block truncate",style:{fontSize:"12px",color:"var(--ink-2)",marginTop:"2px"},children:z.description})]},_t(z))}),f==="plugins"&&t(ti,{list:S,query:p,selected:s.kind==="plugin"||s.kind==="propose"?s.id:null,onSelect:z=>d({kind:"plugin",id:z})}),f==="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(hi,{skill:s.skill,accounts:e,projects:w,onCopied:()=>{k()},onRun:()=>r(s.skill),onDeleted:()=>{d({kind:"empty"}),k()}},_t(s.skill)),s.kind==="create"&&t(gi,{accounts:e,projects:n,onCreateWithAI:a,onCreated:()=>{d({kind:"empty"}),k()}}),s.kind==="explore"&&t(fi,{query:s.query,accounts:e,projects:w,onInstalled:()=>{k()}}),s.kind==="plugins"&&t(li,{accounts:e}),s.kind==="plugin"&&h&&!s.skill&&t(oi,{plugin:h,accounts:e,query:p,onSelectSkill:z=>d({kind:"plugin",id:h.id,skill:z}),onPropose:()=>d({kind:"propose",id:h.id})}),s.kind==="plugin"&&h&&s.skill&&t(ri,{plugin:h,name:s.skill,onBack:()=>d({kind:"plugin",id:h.id})},s.skill),s.kind==="propose"&&h&&t(ii,{plugin:h,accounts:e,onCancel:()=>d({kind:"plugin",id:h.id}),onSubmit:async(z,L,N)=>{await o(h,z,L,N)&&d({kind:"plugin",id:h.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(I,{label:"New skill",variant:"primary",onClick:()=>d({kind:"create"})})]})})]})]})},Tn={auto:"qa:auto",escalated:"qa:needs-human",blocked:"qa:blocked"},ja="<!-- qa-pilot:decision",mi="-->",vi=["auto","escalate","blocked"],yi=["pass","fail","warn"],bi=["journey","file","severity","artifact"],Ne=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pe=e=>typeof e=="string",xt=e=>typeof e=="number"&&Number.isFinite(e);function ki(e){return Ne(e)&&pe(e.id)&&pe(e.reason)}function wi(e){return!Ne(e)||!pe(e.check)||!pe(e.kind)||!pe(e.message)?!1:bi.every(n=>e[n]===void 0||pe(e[n]))}function Si(e){if(!Ne(e)||e.version!==1||!pe(e.decision)||!vi.includes(e.decision)||!pe(e.sha)||!Array.isArray(e.gates)||!e.gates.every(ki))return!1;const n=e.diff;return!Ne(n)||!xt(n.files)||!xt(n.added)||!xt(n.removed)||!Ne(e.checks)||!Object.values(e.checks).every(a=>pe(a)&&yi.includes(a))?!1:Array.isArray(e.findings)&&e.findings.every(wi)}function Ci(e){const n=e.lastIndexOf(ja);if(n===-1)return null;const a=n+ja.length,r=e.indexOf(mi,a);if(r===-1)return null;try{const o=JSON.parse(e.slice(a,r));return Si(o)?o:null}catch{return null}}const $i=["github-actions[bot]","github-actions"];function zi(e){var a;const n=(a=e.author)==null?void 0:a.login;return typeof n=="string"&&$i.includes(n)}function Ri(e){for(let n=e.length-1;n>=0;n--){if(!zi(e[n]))continue;const a=Ci(e[n].body);if(a)return a}return null}function Ti(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(Tn.auto)&&n.auto++,r.has(Tn.escalated)&&n.escalated++,r.has(Tn.blocked)&&n.blocked++}return n}function ji(e,n){return e.sha!==n}const Pi=/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/raw\/([0-9a-f]{40})\/(pr-\d+\/[0-9a-f]{7}\/)$/,Ai=/^artifacts\/[A-Za-z0-9._-]+\.png$/;function Ii(e){const n=e.change;if(!Ne(n)||!xt(n.pixels)||!xt(n.percent)||!pe(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(pe)&&e.elements.length?`${e.elements.join(", ")} · `:""}${a} · ${n.zone}`}function Li(e){const n=Pi.exec(e.evidence??"");if(!n)return[];const[,a,r]=n,o=c=>pe(c)&&Ai.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(!Ne(s)||!pe(s.name))continue;const d={name:s.name};c.journey&&(d.journey=c.journey),pe(s.ai)&&s.ai&&(d.ai=s.ai.slice(0,200));const f=Ii(s);f&&(d.summary=f);const g=o(s.expected),y=o(s.marked)??o(s.actual),m=o(s.diff);g&&(d.before=g),y&&(d.after=y),m&&(d.diff=m),(g||y||m)&&i.push(d)}return i}function Xn(e){const n=sn(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 sn(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 Ei(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 Ni={pass:"✓",fail:"✗",warn:"!"};function Oi(e){return Ni[e]}const Wi=/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/;function Di(e){const n=sn(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 Wi.test(n.data)?{ok:!0,data:`data:image/png;base64,${n.data}`}:{ok:!1,message:"la imagen no es un PNG"}}const Tt=(e,n=16)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,me={background:"var(--card)",border:"1px solid var(--hair)",borderRadius:"12px"},Mi={pass:"--green",fail:"--red",warn:"--orange"};function Fi(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 Vr({message:e,onRetry:n}){return l("div",{style:{...me,padding:"18px 20px",borderColor:Tt("--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:{...me,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 ja({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?Tt(n):"var(--elev)"},children:e})}function _i({decision:e}){return l(H,{children:[l("div",{class:"flex flex-wrap gap-1.5",children:[e.gates.map(n=>t(ja,{label:`${n.id} · ${n.reason}`,tone:"--orange"},n.id+n.reason)),Object.entries(e.checks).map(([n,a])=>t(ja,{label:`${n} ${Oi(a)}`,tone:a==="pass"?void 0:Mi[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:{...me,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 Rn({file:e,label:n,run:a,onOpen:r}){const[o,i]=v({state:"loading"});M(()=>{if(!e)return;let s=!0;return i({state:"loading"}),a("get-evidence",{REF:e.ref,PATH:e.path}).then(d=>{const f=Di(d);s&&i(f.ok?{state:"ok",data:f.data}:{state:"error",message:f.message})}),()=>{s=!1}},[e==null?void 0:e.ref,e==null?void 0:e.path,a]);const c={...me,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 Ki({changes:e,run:n}){const[a,r]=v(null);M(()=>{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:{...me,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:Tt("--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(Rn,{file:i.before,label:"Antes",run:n,onOpen:o}),t(Rn,{file:i.after,label:"Después",run:n,onOpen:o}),t(Rn,{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 Ui({pr:e,run:n,onDone:a}){var C;const[r,o]=v({state:"loading"}),[i,c]=v(!1),[s,d]=v(""),[f,g]=v("Esperando tu decisión."),y=J(async()=>{o({state:"loading"});const u=Qn(await n("get-decision",{PR:String(e.number)}));o(u.ok?{state:"ok",data:u.data}:{state:"error",message:u.message})},[e.number,n]);if(M(()=>{c(!1),d(""),g("Esperando tu decisión."),y()},[y]),r.state==="loading")return t("div",{style:{...me,height:"220px"},class:"animate-pulse"});if(r.state==="error")return t(Vr,{message:r.message,onRetry:y});const m=r.data,w=Ri(m.comments),k=w?ji(w,m.headRefOid):!1,b=w!==null&&w.decision==="escalate"&&!k,p=w?Li(w):[],x=(w==null?void 0:w.diff)??{files:m.changedFiles,added:m.additions,removed:m.deletions},S=async()=>{const u=an(await n("approve",{PR:String(e.number)}));g(u.ok?"Aprobado: qa-pilot pone el status en verde y activa el auto-merge.":`No se pudo aprobar: ${u.message}`),u.ok&&a()},h=async()=>{const u=an(await n("request-changes",{PR:String(e.number),MSG:s.trim()}));u.ok?(g("Comentario publicado en el PR."),c(!1),d("")):g(u.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: ${u.message}`)};return l("div",{class:"flex flex-col gap-3.5",style:{...me,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:[(C=m.author)!=null&&C.login?`abierto por ${m.author.login} en `:"rama ",t("code",{style:{fontFamily:"var(--mono)"},children:m.headRefName}),` · ${x.files} archivos, +${x.added} −${x.removed}`]})]}),w===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(H,{children:[k&&l("p",{style:{fontSize:"12.5px",padding:"8px 10px",borderRadius:"8px",background:Tt("--orange"),color:"var(--orange)"},children:["La decisión es del commit ",t("code",{children:w.sha.slice(0,7)})," y el PR ya está en ",t("code",{children:m.headRefOid.slice(0,7)}),". Espera la nueva corrida."]}),t(_i,{decision:w}),p.length>0&&t(Ki,{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:u=>d(u.target.value.replace(/\s*\n\s*/g," ")),style:{...me,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:h}),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:!b,title:b?"Añade qa:approved al PR":"Solo se aprueba una decisión escalada y vigente",onClick:S}),l("a",{href:m.url,target:"_blank",rel:"noreferrer",class:"inline-flex items-center gap-1.5",style:{...me,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:f})]})}function Hi({moduleId:e,projectId:n,cwProject:a}){const r=Fi(e,n,a),o=!!(n||a),[i,c]=v({state:"loading"}),[s,d]=v({state:"loading"}),[f,g]=v(null),y=J(async()=>{c({state:"loading"});const[w,k]=await Promise.all([r("list-escalations").then(b=>Qn(b)),r("week-stats").then(b=>Qn(b))]);c(w.ok?{state:"ok",data:w.data}:{state:"error",message:w.message}),d(k.ok?{state:"ok",data:Ti(k.data)}:{state:"error",message:k.message}),w.ok&&g(b=>{var p;return w.data.some(x=>x.number===b)?b:((p=w.data[0])==null?void 0:p.number)??null})},[r]);if(M(()=>{o&&y()},[o,y]),!o)return t(Oe,{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(w=>w.number===f):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:y})]}),t(Bi,{stats:s}),i.state==="loading"?t("div",{style:{...me,height:"160px"},class:"animate-pulse"}):i.state==="error"?t(Vr,{message:i.message,onRetry:y}):i.data.length===0?t(Oe,{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(w=>{var k;return l("button",{type:"button",role:"option","aria-selected":w.number===f,onClick:()=>g(w.number),class:"text-left cursor-pointer",style:{...me,borderRadius:"10px",padding:"10px 12px",color:"var(--ink)",borderColor:w.number===f?"var(--blue)":"var(--hair)",background:w.number===f?Tt("--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:["#",w.number," · ",Ei(w.updatedAt)]}),((k=w.author)==null?void 0:k.login)&&t("span",{children:w.author.login})]}),t("b",{style:{display:"block",fontSize:"13px",marginTop:"2px"},children:w.title})]},w.number)})}),m&&t(Ui,{pr:m,run:r,onDone:y},m.number)]})]})}const qi=po({id:"escalations",title:"Escalamientos",component:Hi}),Jr="forge.qa.project",Gi="mod-qa";function Pa(){try{return localStorage.getItem(Jr)??""}catch{return""}}const Vi=({projects:e,preferred:n})=>{const a=Object.keys(e).sort(),r=d=>a.includes(d)?d:a[0]??"",[o,i]=v(()=>r(n||Pa()));M(()=>{a.includes(o)||i(r(n||Pa()))},[a.join(`
20
- `),n]);const c=d=>{i(d);try{localStorage.setItem(Jr,d)}catch{}},s=qi.component;return l("div",{class:"flex flex-col min-h-full",children:[t(et,{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(Oe,{icon:"i-lucide-folder-search",title:"No hay proyectos",description:"Agrega un proyecto de CW para ver sus PRs escalados."}):t(s,{moduleId:Gi,projectId:null,cwProject:o},o)})]})},Bt=e=>e.target.value,Ji=({accounts:e,onOpenSession:n,onFramesChanged:a})=>{const[r,o]=v(null),[i,c]=v(null),[s,d]=v(""),[f,g]=v(""),[y,m]=v(""),[w,k]=v(null),[b,p]=v(""),x=J(async()=>{try{const T=await(await fetch("/api/liveframe/frames")).json();c(T),a(T.length)}catch{c([])}},[a]);M(()=>{x(),fetch("/api/liveframe/status").then(T=>T.json()).then(o).catch(()=>{})},[x]);const S=async T=>{if(r)try{const P=await ce("/api/cw/start",{type:"general",account:r.account,directory:T.dir,task:`Liveframe: ${T.project}/${T.frame}`});n(P.session)}catch(P){j(le(P),"error")}},h=async(T,P)=>{try{const R=await T;return j(P,"success"),x(),await S(R),!0}catch(R){return j(le(R),"error"),!1}},C=async()=>{await h(ce("/api/liveframe/frames",{project:s,name:f}),`Frame "${f}" created`)&&g("")},u=async()=>{await h(ce("/api/liveframe/pull",{target:y}),`Pulled ${y}`)&&m("")},z=async()=>{if(w)try{const{url:T}=await ce(`/api/liveframe/frames/${w.project}/${w.frame}/push`,{note:b});j(`Published: ${T}`,"success"),k(null)}catch(T){j(le(T),"error")}},L=r!==null&&!e.includes(r.account),N=(r==null?void 0:r.installed)!==!1&&!L,O=(i??[]).reduce((T,P)=>{var R;return(T[R=P.project]??(T[R]=[])).push(P),T},{});return l(H,{children:[l(et,{title:"Prototypes",subtitle:r?`Liveframe frames in ${r.root} · agents run on ${r.account}`:"Liveframe frames",children:[r&&l("a",{class:Qe,style:De,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:x})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[r&&!r.installed&&l("p",{style:{...oe,background:Q("--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:{...oe,background:Q("--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:{...oe,background:Q("--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:{...Le,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:T=>d(Bt(T))})}),t(U,{label:"Frame name",children:t("input",{type:"text",class:"field",value:f,placeholder:"Checkout ideas",onInput:T=>g(Bt(T))})}),t("div",{class:"flex justify-end",children:t(I,{label:"Create and open agent",variant:"primary",size:"sm",disabled:!N||!s.trim()||!f.trim(),onClick:C})})]}),l("div",{class:"flex flex-col",style:{...Le,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:T=>m(Bt(T))})}),t("div",{class:"flex justify-end",children:t(I,{label:"Pull and open agent",variant:"secondary",size:"sm",disabled:!N||!y.includes("/"),onClick:u})})]})]}),i&&i.length===0&&t(Oe,{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(([T,P])=>l("section",{style:{...Le,overflow:"hidden"},children:[t("h2",{style:{padding:"12px 18px",fontSize:"13px",fontWeight:600,borderBottom:"1px solid var(--hair)"},children:T}),P.map(R=>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:R.frame}),l("p",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-3)"},children:[R.kind," · ",R.branch," · ",R.dir]})]}),l("a",{class:Qe,style:De,href:R.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:()=>{p(""),k(R)}}),t(I,{label:"Open agent",variant:"primary",size:"sm",disabled:!r||L,onClick:()=>S(R)})]},R.dir))]},T))]}),t(Re,{open:w!==null,title:`Push ${w==null?void 0:w.project}/${w==null?void 0:w.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:b,placeholder:"wallet-first layout",onInput:T=>p(Bt(T))})}),t("div",{class:"flex justify-end pt-1",children:t(I,{label:"Push",variant:"primary",onClick:z})})]})})]})},Yi=[{id:"project",label:"Project"},{id:"team",label:"Team"},{id:"personal",label:"Personal"}],Ue="__new";async function un(e,n,a,r){try{await ce(e,n),j(a,"success"),je(!0),r()}catch(o){j(le(o),"error")}}const Zn=e=>{var n;return(((n=be.value)==null?void 0:n.brains)??[]).filter(a=>a.onDisk&&e.includes(a.tier??""))},Yr=()=>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."}),Qi=({onClose:e})=>{const[n,a]=v(""),[r,o]=v("project"),[i,c]=v(""),[s,d]=v(""),f=Zn(["team"]);return l(Ze,{title:"New brain",onClose:e,children:[t("div",{class:"flex",children:t(de,{size:"sm",label:"Tier",tabs:Yi,active:r,onChange:o})}),t(U,{label:"Repository · owner/repo, the one it gets once published",children:t("input",{type:"text",class:"field",value:n,placeholder:"monoku/brain-shop",onInput:g=>a(ne(g))})}),r==="project"&&f.length>0&&t(Xn,{label:"Team brain",brains:f,value:i,onValue:c}),t(U,{label:"Language of its pages · optional",children:t("input",{type:"text",class:"field",value:s,placeholder:"en",onInput:g=>d(ne(g))})}),t(Yr,{}),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:()=>un("/api/kioku/brains",{repo:n,tier:r,team:i,language:s},`Made ${n.trim()}`,e)})]})]})},Xn=({label:e,brains:n,value:a,onValue:r,repo:o,placeholder:i,onRepo:c})=>l(H,{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:Ue,children:"New brain…"})]})}),c&&a===Ue&&t("input",{type:"text",class:"field",value:o,placeholder:i,onInput:s=>c(ne(s))})]}),Zi=({project:e,onClose:n})=>{const[a,r]=v(Ue),[o,i]=v(""),[c,s]=v(""),[d,f]=v(""),g=(m,w)=>m===Ue?w.trim():m,y={brain:g(a,o),team:g(c,d)};return l(Ze,{title:`A brain for ${e}`,onClose:n,children:[t(Xn,{label:"Project brain",brains:Zn(["project","client"]),value:a,repo:o,placeholder:`monoku/brain-${e}`,onValue:r,onRepo:i}),t(Xn,{label:"Team brain",brains:Zn(["team"]),value:c,repo:d,placeholder:"monoku/brain",onValue:s,onRepo:f}),l("p",{style:{...oe,background:Q("--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===Ue||c===Ue)&&t(Yr,{}),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:!y.brain&&!y.team,onClick:()=>un("/api/kioku/link",{project:e,...y},`Linked ${e}`,n)})]})]})},Qr=({brain:e,onClose:n})=>{const[a,r]=v(""),[o,i]=v("");return t(Re,{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:()=>un("/api/kioku/areas",{brain:e.key,area:a,summary:o},`Added ${a.trim()} to ${re(e)}`,n)})]})]})})},Xi=({brain:e,onClose:n})=>{const[a,r]=v(""),[o,i]=v(!1),c=re(e);return t(Re,{open:!0,title:`Publish ${c}`,onClose:n,children:l("div",{class:"flex flex-col",style:{gap:"12px"},children:[l("div",{style:{...oe,background:Q("--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(H,{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:()=>un("/api/kioku/publish",{brain:e.key,to:a,understood:o},`Published ${c}`,n)})]})]})})};function es(e,n){const r=(n?sa(n):[]).find(o=>o.tier==="project"||o.tier==="client")??e.find(o=>o.personal)??e[0];return(r==null?void 0:r.key)??""}const ts=({project:e,onClose:n})=>{var B;const a=(((B=be.value)==null?void 0:B.brains)??[]).filter(A=>A.onDisk),[r,o]=v(()=>es(a,e)),[i,c]=v(Ot[0].id),[s,d]=v(""),[f,g]=v(""),[y,m]=v(""),[w,k]=v({}),[b,p]=v(null),[x,S]=v(!1),[h,C]=v(!1),u=a.find(A=>A.key===r),z=(u==null?void 0:u.namespaces)??[],L=z.length===1?z[0]:s,N=Ot.find(A=>A.id===i)??Ot[0],O=N.sections.length===0,T=O?["Text"]:N.sections,P=!!(u&&L&&f.trim()&&y.trim()&&T.every(A=>{var D;return(D=w[A])==null?void 0:D.trim()})),R=async(A=!1)=>{if(!u||!P||x)return;S(!0);const D=O?`${(w.Text??"").trim()}
19
+ `)[0]}}return Wi.test(n.data)?{ok:!0,data:`data:image/png;base64,${n.data}`}:{ok:!1,message:"la imagen no es un PNG"}}const Pt=(e,n=16)=>`color-mix(in srgb, var(${e}) ${n}%, transparent)`,me={background:"var(--card)",border:"1px solid var(--hair)",borderRadius:"12px"},Mi={pass:"--green",fail:"--red",warn:"--orange"};function Fi(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 Vr({message:e,onRetry:n}){return l("div",{style:{...me,padding:"18px 20px",borderColor:Pt("--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:{...me,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 Pa({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?Pt(n):"var(--elev)"},children:e})}function _i({decision:e}){return l(H,{children:[l("div",{class:"flex flex-wrap gap-1.5",children:[e.gates.map(n=>t(Pa,{label:`${n.id} · ${n.reason}`,tone:"--orange"},n.id+n.reason)),Object.entries(e.checks).map(([n,a])=>t(Pa,{label:`${n} ${Oi(a)}`,tone:a==="pass"?void 0:Mi[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:{...me,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 jn({file:e,label:n,run:a,onOpen:r}){const[o,i]=v({state:"loading"});D(()=>{if(!e)return;let s=!0;return i({state:"loading"}),a("get-evidence",{REF:e.ref,PATH:e.path}).then(d=>{const f=Di(d);s&&i(f.ok?{state:"ok",data:f.data}:{state:"error",message:f.message})}),()=>{s=!1}},[e==null?void 0:e.ref,e==null?void 0:e.path,a]);const c={...me,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 Ki({changes:e,run:n}){const[a,r]=v(null);D(()=>{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:{...me,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:Pt("--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(jn,{file:i.before,label:"Antes",run:n,onOpen:o}),t(jn,{file:i.after,label:"Después",run:n,onOpen:o}),t(jn,{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 Ui({pr:e,run:n,onDone:a}){var C;const[r,o]=v({state:"loading"}),[i,c]=v(!1),[s,d]=v(""),[f,g]=v("Esperando tu decisión."),y=J(async()=>{o({state:"loading"});const u=Xn(await n("get-decision",{PR:String(e.number)}));o(u.ok?{state:"ok",data:u.data}:{state:"error",message:u.message})},[e.number,n]);if(D(()=>{c(!1),d(""),g("Esperando tu decisión."),y()},[y]),r.state==="loading")return t("div",{style:{...me,height:"220px"},class:"animate-pulse"});if(r.state==="error")return t(Vr,{message:r.message,onRetry:y});const m=r.data,w=Ri(m.comments),k=w?ji(w,m.headRefOid):!1,b=w!==null&&w.decision==="escalate"&&!k,p=w?Li(w):[],x=(w==null?void 0:w.diff)??{files:m.changedFiles,added:m.additions,removed:m.deletions},S=async()=>{const u=sn(await n("approve",{PR:String(e.number)}));g(u.ok?"Aprobado: qa-pilot pone el status en verde y activa el auto-merge.":`No se pudo aprobar: ${u.message}`),u.ok&&a()},h=async()=>{const u=sn(await n("request-changes",{PR:String(e.number),MSG:s.trim()}));u.ok?(g("Comentario publicado en el PR."),c(!1),d("")):g(u.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: ${u.message}`)};return l("div",{class:"flex flex-col gap-3.5",style:{...me,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:[(C=m.author)!=null&&C.login?`abierto por ${m.author.login} en `:"rama ",t("code",{style:{fontFamily:"var(--mono)"},children:m.headRefName}),` · ${x.files} archivos, +${x.added} −${x.removed}`]})]}),w===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(H,{children:[k&&l("p",{style:{fontSize:"12.5px",padding:"8px 10px",borderRadius:"8px",background:Pt("--orange"),color:"var(--orange)"},children:["La decisión es del commit ",t("code",{children:w.sha.slice(0,7)})," y el PR ya está en ",t("code",{children:m.headRefOid.slice(0,7)}),". Espera la nueva corrida."]}),t(_i,{decision:w}),p.length>0&&t(Ki,{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:u=>d(u.target.value.replace(/\s*\n\s*/g," ")),style:{...me,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:h}),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:!b,title:b?"Añade qa:approved al PR":"Solo se aprueba una decisión escalada y vigente",onClick:S}),l("a",{href:m.url,target:"_blank",rel:"noreferrer",class:"inline-flex items-center gap-1.5",style:{...me,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:f})]})}function Hi({moduleId:e,projectId:n,cwProject:a}){const r=Fi(e,n,a),o=!!(n||a),[i,c]=v({state:"loading"}),[s,d]=v({state:"loading"}),[f,g]=v(null),y=J(async()=>{c({state:"loading"});const[w,k]=await Promise.all([r("list-escalations").then(b=>Xn(b)),r("week-stats").then(b=>Xn(b))]);c(w.ok?{state:"ok",data:w.data}:{state:"error",message:w.message}),d(k.ok?{state:"ok",data:Ti(k.data)}:{state:"error",message:k.message}),w.ok&&g(b=>{var p;return w.data.some(x=>x.number===b)?b:((p=w.data[0])==null?void 0:p.number)??null})},[r]);if(D(()=>{o&&y()},[o,y]),!o)return t(Oe,{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(w=>w.number===f):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:y})]}),t(Bi,{stats:s}),i.state==="loading"?t("div",{style:{...me,height:"160px"},class:"animate-pulse"}):i.state==="error"?t(Vr,{message:i.message,onRetry:y}):i.data.length===0?t(Oe,{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(w=>{var k;return l("button",{type:"button",role:"option","aria-selected":w.number===f,onClick:()=>g(w.number),class:"text-left cursor-pointer",style:{...me,borderRadius:"10px",padding:"10px 12px",color:"var(--ink)",borderColor:w.number===f?"var(--blue)":"var(--hair)",background:w.number===f?Pt("--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:["#",w.number," · ",Ei(w.updatedAt)]}),((k=w.author)==null?void 0:k.login)&&t("span",{children:w.author.login})]}),t("b",{style:{display:"block",fontSize:"13px",marginTop:"2px"},children:w.title})]},w.number)})}),m&&t(Ui,{pr:m,run:r,onDone:y},m.number)]})]})}const qi=po({id:"escalations",title:"Escalamientos",component:Hi}),Jr="forge.qa.project",Gi="mod-qa";function Aa(){try{return localStorage.getItem(Jr)??""}catch{return""}}const Vi=({projects:e,preferred:n})=>{const a=Object.keys(e).sort(),r=d=>a.includes(d)?d:a[0]??"",[o,i]=v(()=>r(n||Aa()));D(()=>{a.includes(o)||i(r(n||Aa()))},[a.join(`
20
+ `),n]);const c=d=>{i(d);try{localStorage.setItem(Jr,d)}catch{}},s=qi.component;return l("div",{class:"flex flex-col min-h-full",children:[t(et,{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(Oe,{icon:"i-lucide-folder-search",title:"No hay proyectos",description:"Agrega un proyecto de CW para ver sus PRs escalados."}):t(s,{moduleId:Gi,projectId:null,cwProject:o},o)})]})},Kt=e=>e.target.value,Ji=({accounts:e,onOpenSession:n,onFramesChanged:a})=>{const[r,o]=v(null),[i,c]=v(null),[s,d]=v(""),[f,g]=v(""),[y,m]=v(""),[w,k]=v(null),[b,p]=v(""),x=J(async()=>{try{const T=await(await fetch("/api/liveframe/frames")).json();c(T),a(T.length)}catch{c([])}},[a]);D(()=>{x(),fetch("/api/liveframe/status").then(T=>T.json()).then(o).catch(()=>{})},[x]);const S=async T=>{if(r)try{const P=await ce("/api/cw/start",{type:"general",account:r.account,directory:T.dir,task:`Liveframe: ${T.project}/${T.frame}`});n(P.session)}catch(P){j(le(P),"error")}},h=async(T,P)=>{try{const R=await T;return j(P,"success"),x(),await S(R),!0}catch(R){return j(le(R),"error"),!1}},C=async()=>{await h(ce("/api/liveframe/frames",{project:s,name:f}),`Frame "${f}" created`)&&g("")},u=async()=>{await h(ce("/api/liveframe/pull",{target:y}),`Pulled ${y}`)&&m("")},z=async()=>{if(w)try{const{url:T}=await ce(`/api/liveframe/frames/${w.project}/${w.frame}/push`,{note:b});j(`Published: ${T}`,"success"),k(null)}catch(T){j(le(T),"error")}},L=r!==null&&!e.includes(r.account),N=(r==null?void 0:r.installed)!==!1&&!L,O=(i??[]).reduce((T,P)=>{var R;return(T[R=P.project]??(T[R]=[])).push(P),T},{});return l(H,{children:[l(et,{title:"Prototypes",subtitle:r?`Liveframe frames in ${r.root} · agents run on ${r.account}`:"Liveframe frames",children:[r&&l("a",{class:Qe,style:De,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:x})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[r&&!r.installed&&l("p",{style:{...oe,background:Q("--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:{...oe,background:Q("--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:{...oe,background:Q("--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:{...Ee,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:T=>d(Kt(T))})}),t(U,{label:"Frame name",children:t("input",{type:"text",class:"field",value:f,placeholder:"Checkout ideas",onInput:T=>g(Kt(T))})}),t("div",{class:"flex justify-end",children:t(I,{label:"Create and open agent",variant:"primary",size:"sm",disabled:!N||!s.trim()||!f.trim(),onClick:C})})]}),l("div",{class:"flex flex-col",style:{...Ee,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:T=>m(Kt(T))})}),t("div",{class:"flex justify-end",children:t(I,{label:"Pull and open agent",variant:"secondary",size:"sm",disabled:!N||!y.includes("/"),onClick:u})})]})]}),i&&i.length===0&&t(Oe,{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(([T,P])=>l("section",{style:{...Ee,overflow:"hidden"},children:[t("h2",{style:{padding:"12px 18px",fontSize:"13px",fontWeight:600,borderBottom:"1px solid var(--hair)"},children:T}),P.map(R=>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:R.frame}),l("p",{class:"truncate",style:{fontSize:"12px",color:"var(--ink-3)"},children:[R.kind," · ",R.branch," · ",R.dir]})]}),l("a",{class:Qe,style:De,href:R.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:()=>{p(""),k(R)}}),t(I,{label:"Open agent",variant:"primary",size:"sm",disabled:!r||L,onClick:()=>S(R)})]},R.dir))]},T))]}),t(Re,{open:w!==null,title:`Push ${w==null?void 0:w.project}/${w==null?void 0:w.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:b,placeholder:"wallet-first layout",onInput:T=>p(Kt(T))})}),t("div",{class:"flex justify-end pt-1",children:t(I,{label:"Push",variant:"primary",onClick:z})})]})})]})},Yi=[{id:"project",label:"Project"},{id:"team",label:"Team"},{id:"personal",label:"Personal"}],Ue="__new";async function fn(e,n,a,r){try{await ce(e,n),j(a,"success"),Pe(!0),r()}catch(o){j(le(o),"error")}}const ea=e=>{var n;return(((n=be.value)==null?void 0:n.brains)??[]).filter(a=>a.onDisk&&e.includes(a.tier??""))},Yr=()=>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."}),Qi=({onClose:e})=>{const[n,a]=v(""),[r,o]=v("project"),[i,c]=v(""),[s,d]=v(""),f=ea(["team"]);return l(Ze,{title:"New brain",onClose:e,children:[t("div",{class:"flex",children:t(de,{size:"sm",label:"Tier",tabs:Yi,active:r,onChange:o})}),t(U,{label:"Repository · owner/repo, the one it gets once published",children:t("input",{type:"text",class:"field",value:n,placeholder:"monoku/brain-shop",onInput:g=>a(ne(g))})}),r==="project"&&f.length>0&&t(ta,{label:"Team brain",brains:f,value:i,onValue:c}),t(U,{label:"Language of its pages · optional",children:t("input",{type:"text",class:"field",value:s,placeholder:"en",onInput:g=>d(ne(g))})}),t(Yr,{}),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:()=>fn("/api/kioku/brains",{repo:n,tier:r,team:i,language:s},`Made ${n.trim()}`,e)})]})]})},ta=({label:e,brains:n,value:a,onValue:r,repo:o,placeholder:i,onRepo:c})=>l(H,{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:Ue,children:"New brain…"})]})}),c&&a===Ue&&t("input",{type:"text",class:"field",value:o,placeholder:i,onInput:s=>c(ne(s))})]}),Zi=({project:e,onClose:n})=>{const[a,r]=v(Ue),[o,i]=v(""),[c,s]=v(""),[d,f]=v(""),g=(m,w)=>m===Ue?w.trim():m,y={brain:g(a,o),team:g(c,d)};return l(Ze,{title:`A brain for ${e}`,onClose:n,children:[t(ta,{label:"Project brain",brains:ea(["project","client"]),value:a,repo:o,placeholder:`monoku/brain-${e}`,onValue:r,onRepo:i}),t(ta,{label:"Team brain",brains:ea(["team"]),value:c,repo:d,placeholder:"monoku/brain",onValue:s,onRepo:f}),l("p",{style:{...oe,background:Q("--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===Ue||c===Ue)&&t(Yr,{}),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:!y.brain&&!y.team,onClick:()=>fn("/api/kioku/link",{project:e,...y},`Linked ${e}`,n)})]})]})},Qr=({brain:e,onClose:n})=>{const[a,r]=v(""),[o,i]=v("");return t(Re,{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:()=>fn("/api/kioku/areas",{brain:e.key,area:a,summary:o},`Added ${a.trim()} to ${re(e)}`,n)})]})]})})},Xi=({brain:e,onClose:n})=>{const[a,r]=v(""),[o,i]=v(!1),c=re(e);return t(Re,{open:!0,title:`Publish ${c}`,onClose:n,children:l("div",{class:"flex flex-col",style:{gap:"12px"},children:[l("div",{style:{...oe,background:Q("--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(H,{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:()=>fn("/api/kioku/publish",{brain:e.key,to:a,understood:o},`Published ${c}`,n)})]})]})})};function es(e,n){const r=(n?da(n):[]).find(o=>o.tier==="project"||o.tier==="client")??e.find(o=>o.personal)??e[0];return(r==null?void 0:r.key)??""}const ts=({project:e,onClose:n})=>{var B;const a=(((B=be.value)==null?void 0:B.brains)??[]).filter(A=>A.onDisk),[r,o]=v(()=>es(a,e)),[i,c]=v(Dt[0].id),[s,d]=v(""),[f,g]=v(""),[y,m]=v(""),[w,k]=v({}),[b,p]=v(null),[x,S]=v(!1),[h,C]=v(!1),u=a.find(A=>A.key===r),z=(u==null?void 0:u.namespaces)??[],L=z.length===1?z[0]:s,N=Dt.find(A=>A.id===i)??Dt[0],O=N.sections.length===0,T=O?["Text"]:N.sections,P=!!(u&&L&&f.trim()&&y.trim()&&T.every(A=>{var M;return(M=w[A])==null?void 0:M.trim()})),R=async(A=!1)=>{if(!u||!P||x)return;S(!0);const M=O?`${(w.Text??"").trim()}
21
21
  `:N.sections.map(F=>`## ${F}
22
22
 
23
23
  ${(w[F]??"").trim()}
24
24
  `).join(`
25
- `);try{const F=await ce("/api/kioku/pages",{brain:u.key,type:i,title:f,summary:y,body:D,namespace:L,create:A});F.status==="similar"?p(F.similar):F.status==="namespace"?j(`Pick an area of ${re(u)}`,"error"):(j(`Saved to ${F.brain}: ${F.path}`,"success"),je(!0),n())}catch(F){j(le(F),"error")}finally{S(!1)}};return l(Ze,{title:"New memory",onClose:n,children:[t(U,{label:"Brain",children:t("select",{class:"field",value:r,onChange:A=>{o(ne(A)),d(""),p(null)},children:a.map(A=>l("option",{value:A.key,children:[re(A)," · ",A.tier]},A.key))})}),u&&z.length===0&&l("div",{class:"flex items-center",style:{...oe,gap:"12px",background:Q("--orange")},children:[l("span",{class:"flex-1",children:[re(u)," has no areas yet. Each page goes in one, and a person names them."]}),t(I,{label:"Add area",variant:"secondary",size:"sm",onClick:()=>C(!0)})]}),z.length>1&&t(U,{label:"Area",children:l("select",{class:"field",value:s,onChange:A=>d(ne(A)),children:[t("option",{value:"",children:"Choose…"}),z.map(A=>t("option",{value:A,children:A},A))]})}),t("div",{class:"flex",children:t(de,{size:"sm",label:"Page type",tabs:Ot.map(A=>({id:A.id,label:A.label})),active:i,onChange:A=>{c(A),p(null)}})}),t(U,{label:"Title",children:t("input",{type:"text",class:"field",value:f,placeholder:"Payments retry at most three times",onInput:A=>{g(ne(A)),p(null)}})}),t(U,{label:"Summary · one line the agent reads first",children:t("input",{type:"text",class:"field",value:y,onInput:A=>m(ne(A))})}),T.map(A=>t(U,{label:A,children:t("textarea",{class:"field",rows:A==="Text"?8:3,value:w[A]??"",onInput:D=>k(F=>({...F,[A]:ne(D)}))})},`${i}:${A}`)),b&&l("div",{style:{...oe,background:Q("--orange")},children:[l("p",{style:{fontWeight:600,marginBottom:"6px"},children:[u?re(u):"The brain"," already has pages on this:"]}),t("ul",{class:"flex flex-col",style:{gap:"4px",paddingLeft:"16px",listStyle:"disc"},children:b.map(A=>l("li",{children:[t("b",{children:A.title}),A.summary?` — ${A.summary}`:""]},A.path))}),t("p",{style:{marginTop:"6px",color:"var(--ink-2)"},children:"Save it anyway to keep both; kioku links them under See also."})]}),(u==null?void 0:u.remote)&&l("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Kioku commits to ",re(u),"'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:b?"Save anyway":"Save",variant:"primary",disabled:!P||x,onClick:()=>R(b!==null)})]}),h&&u&&t(Qr,{brain:u,onClose:()=>C(!1)})]})},Zr={fontSize:"11px",fontWeight:600,letterSpacing:".02em",color:"var(--ink-3)"},Xr={gap:"10px",padding:"9px 16px",borderTop:"1px solid var(--hair)",fontSize:"12.5px"},fe={fontSize:"11.5px",color:"var(--ink-3)"},ns={updated:"--green",current:"--ink-3"},Pe=({text:e})=>l("div",{class:"flex items-center min-w-0",style:{gap:"6px"},children:[t("code",{class:"truncate",title:e,style:{fontSize:"11px",color:"var(--ink-2)",padding:"2px 6px",borderRadius:"6px",background:"var(--elev)"},children:e}),t("button",{type:"button","aria-label":"Copy command",title:"Copy command",class:"grid place-items-center shrink-0 cursor-pointer hover:text-ink",style:{padding:"2px",color:"var(--ink-3)",background:"none",border:0},onClick:()=>sn(e,"Command"),children:t("span",{class:"i-lucide-copy",style:{width:"12px",height:"12px"}})})]}),eo=({title:e,aside:n,command:a,children:r})=>l("section",{class:"flex flex-col min-w-0",style:{...Le,overflow:"hidden"},children:[l("div",{class:"flex items-center",style:{gap:"8px",padding:"12px 16px 8px"},children:[t("h2",{style:Zr,children:e}),t("span",{class:"flex-1"}),n]}),r,t("div",{style:{padding:"8px 16px 12px",borderTop:"1px solid var(--hair)"},children:t(Pe,{text:a})})]}),Aa=({release:e,label:n,action:a,onTry:r})=>l("div",{class:"flex flex-col",style:Xr,children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[t("span",{class:"shrink-0",style:{...fe,width:"70px"},children:n}),t("span",{class:"mono",style:{fontWeight:600},children:e.version}),e.date&&t("span",{style:fe,children:$t(e.date)}),t("a",{href:e.notesUrl,target:"_blank",rel:"noreferrer",style:{fontSize:"11.5px",color:"var(--blue)"},children:"Notes ↗"}),t("span",{class:"flex-1"}),a&&t(I,{label:a,variant:e.prerelease?"primary":"secondary",size:"sm",onClick:()=>r(e.version)})]}),a&&t(Pe,{text:e.install}),e.notes&&l("details",{style:{fontSize:"12px",color:"var(--ink-2)"},children:[t("summary",{class:"cursor-pointer",style:fe,children:"What it brings"}),t("p",{style:{whiteSpace:"pre-wrap",marginTop:"6px"},children:e.notes})]})]}),as=({onTry:e})=>{const n=wt.value;if(!n)return null;const{installed:a,stable:r,stableAction:o,prereleases:i}=n,c=l(H,{children:[t("span",{class:"mono",style:{fontSize:"13px",fontWeight:600},children:a??"unknown"}),(a==null?void 0:a.includes("-"))&&t(He,{label:"pre-release",color:"var(--orange)"})]});return l(eo,{title:"KIOKU VERSION",aside:c,command:n.command,children:[n.error&&t("p",{style:{...oe,margin:"0 16px 10px",background:Q("--orange")},children:n.error}),r&&t(Aa,{release:r,label:"Stable",action:o==="back"?"Back to stable":o==="update"?`Update to ${r.version}`:void 0,onTry:e}),i.map(s=>t(Aa,{release:s,label:"Pre-release",action:`Try ${s.version}`,onTry:e},s.version)),!n.error&&i.length===0&&t("p",{style:{...fe,padding:"8px 16px 12px",borderTop:"1px solid var(--hair)"},children:"No pre-release newer than the one installed."})]})},rs=({version:e,onClose:n})=>{const[a,r]=v(null),[o,i]=v(null),[c,s]=v(null),[d,f]=v(!1);M(()=>{ce("/api/kioku/update/check",{version:e}).then(r,w=>s(le(w)))},[e]);const g=async()=>{f(!0),s(null);try{i(await ce("/api/kioku/update",{version:e})),Promise.all([je(),_n()])}catch(w){s(le(w))}finally{f(!1)}},y=o??a,m=o?l(H,{children:[t("span",{class:"flex-1"}),t(I,{label:"Close",variant:"primary",onClick:n})]}):l(H,{children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:d?"Installing…":`Install ${e}`,variant:"primary",disabled:!a||a.status==="current"||d,onClick:g})]});return t(Re,{open:!0,title:o?`Kioku ${o.version??e}`:`Try Kioku ${e}`,onClose:d?()=>{}:n,footer:m,children:l("div",{class:"flex flex-col",style:{gap:"12px",fontSize:"13px"},children:[!y&&!c&&t("p",{style:fe,children:"Asking kioku what it would install…"}),y&&l("div",{class:"flex items-center",style:{gap:"10px"},children:[l("span",{class:"mono",style:{fontSize:"16px",fontWeight:600},children:[y.was??"?"," → ",y.version??e]}),t(He,{label:y.status,color:`var(${ns[y.status]??"--blue"})`})]}),(a==null?void 0:a.status)==="current"&&!o&&t("p",{style:fe,children:"This version is already installed."}),y&&t(Pe,{text:y.command}),!o&&(a==null?void 0:a.install)&&t(Pe,{text:a.install}),o&&o.agents.length>0&&l("div",{class:"flex flex-col",style:{gap:"4px"},children:[t("h3",{style:Zr,children:"AGENT PLUGINS"}),o.agents.map(w=>l("div",{class:"flex items-center",style:{gap:"8px",fontSize:"12.5px"},children:[t("span",{style:{fontWeight:500},children:w.host}),t("span",{style:fe,children:w.name}),l("span",{class:"mono",children:[w.from??"–"," → ",w.to??"–"]}),t("span",{class:"flex-1"}),w.error?t(He,{label:w.error,color:"var(--red)"}):t(He,{label:w.changed?"changed":"unchanged",color:`var(${w.changed?"--green":"--ink-3"})`})]},`${w.host}:${w.name}`))]}),(o==null?void 0:o.finishError)&&t("p",{style:{...oe,background:Q("--orange")},children:o.finishError}),c&&t("p",{style:{...oe,background:Q("--red")},children:c}),!o&&l("p",{style:fe,children:["Kioku installs it on this machine for every session.",e.includes("-")?" Back to stable undoes it.":""]})]})})},os=({mismatch:e,tool:n,onTry:a})=>{const[r,o]=v(!1),{fix:i}=e,c=async()=>{o(!0),await dn(`${ua(e.plugin)}/update`,{scope:e.scope,scopeRef:e.scopeRef})&&(j(`Kioku's plugin updated in ${e.scopeRef} · applies to new sessions`,"success"),await kr()),o(!1)};let s=null;return(i==null?void 0:i.kind)==="release"&&(s=t(I,{label:`Try ${i.version}`,variant:"primary",size:"sm",onClick:()=>a(i.version)})),(i==null?void 0:i.kind)==="plugin"&&(s=t(I,{label:r?"Updating…":"Update plugin",variant:"primary",size:"sm",disabled:r,onClick:c})),l("div",{class:"flex flex-col",style:{gap:"4px"},children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[l("span",{class:"flex-1",children:[e.scopeRef,": plugin ",t("span",{class:"mono",children:e.version}),", tool ",t("span",{class:"mono",children:n})]}),s]}),i?t(Pe,{text:i.command}):t("span",{style:fe,children:"No kioku release of that major yet."})]})},ls=({onTry:e})=>{const n=wt.value;return!(n!=null&&n.installed)||n.mismatches.length===0?null:l("section",{class:"flex flex-col",style:{...oe,gap:"8px",background:Q("--orange")},children:[t("p",{style:{fontWeight:600},children:"Kioku does nothing in these sessions: its plugin and the tool have different major versions."}),n.mismatches.map(a=>t(os,{mismatch:a,tool:n.installed,onTry:e},`${a.scope}:${a.scopeRef}`))]})},is=({lab:e})=>{const[n,a]=v(!1),r=async o=>{a(!0);try{ia.value=await ce(`/api/kioku/labs/${encodeURIComponent(e.name)}`,{enabled:o}),j(`${e.title} ${o?"on":"off"} · applies from the next session`,"info")}catch(i){j(le(i),"error")}finally{a(!1)}};return l("div",{class:"flex flex-col",style:{...Xr,gap:"6px"},children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[t("span",{style:{fontWeight:600},children:e.title}),t("span",{class:"flex-1"}),t(rn,{checked:e.enabled,disabled:n,label:`${e.title} enabled`,onChange:r})]}),e.about&&t("p",{style:{color:"var(--ink-2)"},children:e.about}),t(Pe,{text:e.toggle}),e.command&&l("div",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{style:fe,children:"In a session"}),t(Pe,{text:e.command}),t(Br,{command:e.command,plugin:"kioku",disabled:!e.enabled,note:"A session has it only when it was opened after the lab was switched on."})]}),Object.entries(e.settings??{}).map(([o,i])=>{var c;return l("div",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{class:"mono",style:fe,children:o}),t("span",{class:"mono",children:JSON.stringify(i)}),t("span",{class:"flex-1"}),((c=e.set)==null?void 0:c[o])&&t(Pe,{text:e.set[o]})]},o)})]})},ss=()=>{var n,a;const e=ia.value;return(n=e==null?void 0:e.labs)!=null&&n.length?t(eo,{title:`LABS · ${((a=wt.value)==null?void 0:a.installed)??""}`,aside:t("span",{style:fe,children:"off by default, may change in any version"}),command:e.command,children:e.labs.map(r=>t(is,{lab:r},r.name))}):null},cs=[{label:"Personal",tiers:["personal"]},{label:"Projects",tiers:["project","client"]},{label:"Team",tiers:["team"]}],ds={save:"--green",update:"--blue",supersede:"--blue",evolve:"--purple",link:"--teal",confirm:"--green",retire:"--red",forget:"--red"},ps=({brain:e})=>{const n=Object.entries(e.kinds).filter(([,a])=>a>0).sort((a,r)=>r[1]-a[1]);return l(H,{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(${ma(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(ze,{color:`var(${ma(a)})`}),a," ",r]},a))})]})},Ia={fontSize:"11.5px",fontWeight:500,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},La=({brain:e,usedBy:n,showTier:a,onDialog:r})=>{const o=Ve(e.tier);return l("div",{class:"flex flex-col min-w-0",style:{...Le,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?$t(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(ps,{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(He,{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:Ia,onClick:()=>r({kind:"area",brain:e}),children:"+ Area"}),t("span",{class:"flex-1"}),!e.remote&&l(H,{children:[t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"only on this machine"}),t("button",{type:"button",style:Ia,onClick:()=>r({kind:"publish",brain:e}),children:"Publish…"})]})]})]})},us=({writes:e})=>l("section",{style:{...Le,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(He,{label:n.verb,color:`var(${ds[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}`:""," · ",$t(n.date)]})]},`${n.brain}:${n.path}:${n.date}:${n.verb}`))]}),hs=({project:e,onProject:n})=>{const[a,r]=v(!1),[o,i]=v(null),c=()=>i(null);M(()=>wr(),[]);const s=be.value,d=(s==null?void 0:s.installed)===!0;M(()=>{d&&_n(!1,!e)},[d,e]);const f=C=>i({kind:"version",version:C}),g=async()=>{const C=window.open("","_blank");r(!0);try{const{address:u}=await ce("/api/kioku/viewer",{});C?C.location.href=u:j(`Viewer running at ${u}`,"info"),je()}catch(u){C==null||C.close(),j(le(u),"error")}finally{r(!1)}},y=async()=>{await fetch("/api/kioku/viewer",{method:"DELETE"}).catch(()=>{}),je()},m=(s==null?void 0:s.brains)??[],w=(s==null?void 0:s.projects)??{},k=Object.keys(w).filter(C=>w[C].some(u=>u.tier!=="personal")).sort();e&&!k.includes(e)&&k.unshift(e);const b=e?sa(e):[],p=C=>Object.keys(w).filter(u=>w[u].some(z=>z.name===re(C))).sort(),x=new Set(b.map(re)),S=((s==null?void 0:s.activity)??[]).filter(C=>!e||x.has(C.brain)).slice(0,15),h=d?e?`${e} · ${en(b)} pages its sessions can recall`:`Kioku ${s.version??""} · ${en(m)} pages in ${m.length} brain${m.length===1?"":"s"}`:"Kioku brains on this machine";return l(H,{children:[l(et,{title:"Memory",subtitle:h,children:[(s==null?void 0:s.viewer)&&t(I,{label:"Stop viewer",variant:"secondary",onClick:y}),t(I,{label:"Refresh",variant:"secondary",onClick:()=>je(!0).then(()=>d&&_n(!0,!e))}),t(I,{label:"New brain",variant:"secondary",disabled:!d,onClick:()=>i({kind:"brain"})}),t(I,{label:"New memory",variant:"secondary",disabled:!m.some(C=>C.onDisk),onClick:()=>i({kind:"memory"})}),t(I,{label:s!=null&&s.viewer?"Viewer open ↗":"Open viewer",variant:"primary",disabled:!d||a,onClick:g})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[s&&!s.installed&&l("p",{style:{...oe,background:Q("--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"}),"."]}),d&&t(ls,{onTry:f}),d&&!e&&l("div",{class:"grid items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 380px), 1fr))",gap:"12px"},children:[t(as,{onTry:f}),t(ss,{})]}),d&&m.length===0&&t(Oe,{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."}),m.length>0&&k.length>0&&t("div",{class:"flex",children:t(de,{size:"sm",label:"Project",tabs:[{id:"",label:"All"},...k.map(C=>({id:C,label:C}))],active:e??"",onChange:C=>n(C||null)})}),m.length>0&&!e&&t("div",{class:"flex flex-wrap",style:{gap:"14px 12px"},children:cs.map(C=>{const u=m.filter(z=>C.tiers.includes(z.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(${Ve(C.tiers[0])})`},children:["● ",C.label.toUpperCase(),u.length>1&&t("span",{style:{color:"var(--ink-3)"},children:u.length})]}),t("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:"12px"},children:u.map(z=>t(La,{brain:z,usedBy:p(z),onDialog:i},z.key))})]},C.label)})}),e&&b.length>0&&t("div",{class:"grid items-center",style:{gridTemplateColumns:b.map(()=>"minmax(0, 1fr)").join(" 24px ")},children:b.map((C,u)=>l(ro,{children:[u>0&&t("span",{style:{textAlign:"center",color:"var(--ink-3)",fontSize:"16px"},children:"→"}),t(La,{brain:C,showTier:!0,onDialog:i})]},C.key))}),e&&d&&!b.some(C=>C.tier!=="personal")&&l("div",{class:"flex items-center",style:{...oe,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"})})]}),m.length>0&&t(us,{writes:S}),d&&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(ts,{project:e,onClose:c}),(o==null?void 0:o.kind)==="brain"&&t(Qi,{onClose:c}),(o==null?void 0:o.kind)==="link"&&e&&t(Zi,{project:e,onClose:c}),(o==null?void 0:o.kind)==="area"&&t(Qr,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="publish"&&t(Xi,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="version"&&t(rs,{version:o.version,onClose:c})]})},St=Y(null);function fs(e,n){var a;return(a=St.value)==null||a.resolve(!1),new Promise(r=>{St.value={confirmation:e,module:n,resolve:r}})}const Tn=e=>{const n=St.value;St.value=null,n==null||n.resolve(e)},gs=()=>{var a;const e=St.value;if(!e)return null;const{confirmation:n}=e;return l(Re,{open:!0,title:n.title,onClose:()=>Tn(!1),footer:l(H,{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:()=>Tn(!1)}),t(I,{label:n.confirmLabel,variant:"destructive",onClick:()=>Tn(!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))})]})},_t=e=>`/api/modules/${encodeURIComponent(e)}`;async function jn(e){const n=await e.json().catch(()=>({}));throw new Qt(n.code??`http_${e.status}`,n.message??n.error??`Request failed (${e.status})`)}const Ea=(e,n)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});async function xs(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 f;for(;(f=o.indexOf(`
25
+ `);try{const F=await ce("/api/kioku/pages",{brain:u.key,type:i,title:f,summary:y,body:M,namespace:L,create:A});F.status==="similar"?p(F.similar):F.status==="namespace"?j(`Pick an area of ${re(u)}`,"error"):(j(`Saved to ${F.brain}: ${F.path}`,"success"),Pe(!0),n())}catch(F){j(le(F),"error")}finally{S(!1)}};return l(Ze,{title:"New memory",onClose:n,children:[t(U,{label:"Brain",children:t("select",{class:"field",value:r,onChange:A=>{o(ne(A)),d(""),p(null)},children:a.map(A=>l("option",{value:A.key,children:[re(A)," · ",A.tier]},A.key))})}),u&&z.length===0&&l("div",{class:"flex items-center",style:{...oe,gap:"12px",background:Q("--orange")},children:[l("span",{class:"flex-1",children:[re(u)," has no areas yet. Each page goes in one, and a person names them."]}),t(I,{label:"Add area",variant:"secondary",size:"sm",onClick:()=>C(!0)})]}),z.length>1&&t(U,{label:"Area",children:l("select",{class:"field",value:s,onChange:A=>d(ne(A)),children:[t("option",{value:"",children:"Choose…"}),z.map(A=>t("option",{value:A,children:A},A))]})}),t("div",{class:"flex",children:t(de,{size:"sm",label:"Page type",tabs:Dt.map(A=>({id:A.id,label:A.label})),active:i,onChange:A=>{c(A),p(null)}})}),t(U,{label:"Title",children:t("input",{type:"text",class:"field",value:f,placeholder:"Payments retry at most three times",onInput:A=>{g(ne(A)),p(null)}})}),t(U,{label:"Summary · one line the agent reads first",children:t("input",{type:"text",class:"field",value:y,onInput:A=>m(ne(A))})}),T.map(A=>t(U,{label:A,children:t("textarea",{class:"field",rows:A==="Text"?8:3,value:w[A]??"",onInput:M=>k(F=>({...F,[A]:ne(M)}))})},`${i}:${A}`)),b&&l("div",{style:{...oe,background:Q("--orange")},children:[l("p",{style:{fontWeight:600,marginBottom:"6px"},children:[u?re(u):"The brain"," already has pages on this:"]}),t("ul",{class:"flex flex-col",style:{gap:"4px",paddingLeft:"16px",listStyle:"disc"},children:b.map(A=>l("li",{children:[t("b",{children:A.title}),A.summary?` — ${A.summary}`:""]},A.path))}),t("p",{style:{marginTop:"6px",color:"var(--ink-2)"},children:"Save it anyway to keep both; kioku links them under See also."})]}),(u==null?void 0:u.remote)&&l("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:["Kioku commits to ",re(u),"'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:b?"Save anyway":"Save",variant:"primary",disabled:!P||x,onClick:()=>R(b!==null)})]}),h&&u&&t(Qr,{brain:u,onClose:()=>C(!1)})]})},Zr={fontSize:"11px",fontWeight:600,letterSpacing:".02em",color:"var(--ink-3)"},Xr={gap:"10px",padding:"9px 16px",borderTop:"1px solid var(--hair)",fontSize:"12.5px"},fe={fontSize:"11.5px",color:"var(--ink-3)"},ns={updated:"--green",current:"--ink-3"},Ae=({text:e})=>l("div",{class:"flex items-center min-w-0",style:{gap:"6px"},children:[t("code",{class:"truncate",title:e,style:{fontSize:"11px",color:"var(--ink-2)",padding:"2px 6px",borderRadius:"6px",background:"var(--elev)"},children:e}),t("button",{type:"button","aria-label":"Copy command",title:"Copy command",class:"grid place-items-center shrink-0 cursor-pointer hover:text-ink",style:{padding:"2px",color:"var(--ink-3)",background:"none",border:0},onClick:()=>un(e,"Command"),children:t("span",{class:"i-lucide-copy",style:{width:"12px",height:"12px"}})})]}),eo=({title:e,aside:n,command:a,children:r})=>l("section",{class:"flex flex-col min-w-0",style:{...Ee,overflow:"hidden"},children:[l("div",{class:"flex items-center",style:{gap:"8px",padding:"12px 16px 8px"},children:[t("h2",{style:Zr,children:e}),t("span",{class:"flex-1"}),n]}),r,t("div",{style:{padding:"8px 16px 12px",borderTop:"1px solid var(--hair)"},children:t(Ae,{text:a})})]}),Ia=({release:e,label:n,action:a,onTry:r})=>l("div",{class:"flex flex-col",style:Xr,children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[t("span",{class:"shrink-0",style:{...fe,width:"70px"},children:n}),t("span",{class:"mono",style:{fontWeight:600},children:e.version}),e.date&&t("span",{style:fe,children:Rt(e.date)}),t("a",{href:e.notesUrl,target:"_blank",rel:"noreferrer",style:{fontSize:"11.5px",color:"var(--blue)"},children:"Notes ↗"}),t("span",{class:"flex-1"}),a&&t(I,{label:a,variant:e.prerelease?"primary":"secondary",size:"sm",onClick:()=>r(e.version)})]}),a&&t(Ae,{text:e.install}),e.notes&&l("details",{style:{fontSize:"12px",color:"var(--ink-2)"},children:[t("summary",{class:"cursor-pointer",style:fe,children:"What it brings"}),t("p",{style:{whiteSpace:"pre-wrap",marginTop:"6px"},children:e.notes})]})]}),as=({onTry:e})=>{const n=wt.value;if(!n)return null;const{installed:a,stable:r,stableAction:o,prereleases:i}=n,c=l(H,{children:[t("span",{class:"mono",style:{fontSize:"13px",fontWeight:600},children:a??"unknown"}),(a==null?void 0:a.includes("-"))&&t(He,{label:"pre-release",color:"var(--orange)"})]});return l(eo,{title:"KIOKU VERSION",aside:c,command:n.command,children:[n.error&&t("p",{style:{...oe,margin:"0 16px 10px",background:Q("--orange")},children:n.error}),r&&t(Ia,{release:r,label:"Stable",action:o==="back"?"Back to stable":o==="update"?`Update to ${r.version}`:void 0,onTry:e}),i.map(s=>t(Ia,{release:s,label:"Pre-release",action:`Try ${s.version}`,onTry:e},s.version)),!n.error&&i.length===0&&t("p",{style:{...fe,padding:"8px 16px 12px",borderTop:"1px solid var(--hair)"},children:"No pre-release newer than the one installed."})]})},rs=({version:e,onClose:n})=>{const[a,r]=v(null),[o,i]=v(null),[c,s]=v(null),[d,f]=v(!1);D(()=>{ce("/api/kioku/update/check",{version:e}).then(r,w=>s(le(w)))},[e]);const g=async()=>{f(!0),s(null);try{i(await ce("/api/kioku/update",{version:e})),Promise.all([Pe(),Un()])}catch(w){s(le(w))}finally{f(!1)}},y=o??a,m=o?l(H,{children:[t("span",{class:"flex-1"}),t(I,{label:"Close",variant:"primary",onClick:n})]}):l(H,{children:[t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",onClick:n}),t(I,{label:d?"Installing…":`Install ${e}`,variant:"primary",disabled:!a||a.status==="current"||d,onClick:g})]});return t(Re,{open:!0,title:o?`Kioku ${o.version??e}`:`Try Kioku ${e}`,onClose:d?()=>{}:n,footer:m,children:l("div",{class:"flex flex-col",style:{gap:"12px",fontSize:"13px"},children:[!y&&!c&&t("p",{style:fe,children:"Asking kioku what it would install…"}),y&&l("div",{class:"flex items-center",style:{gap:"10px"},children:[l("span",{class:"mono",style:{fontSize:"16px",fontWeight:600},children:[y.was??"?"," → ",y.version??e]}),t(He,{label:y.status,color:`var(${ns[y.status]??"--blue"})`})]}),(a==null?void 0:a.status)==="current"&&!o&&t("p",{style:fe,children:"This version is already installed."}),y&&t(Ae,{text:y.command}),!o&&(a==null?void 0:a.install)&&t(Ae,{text:a.install}),o&&o.agents.length>0&&l("div",{class:"flex flex-col",style:{gap:"4px"},children:[t("h3",{style:Zr,children:"AGENT PLUGINS"}),o.agents.map(w=>l("div",{class:"flex items-center",style:{gap:"8px",fontSize:"12.5px"},children:[t("span",{style:{fontWeight:500},children:w.host}),t("span",{style:fe,children:w.name}),l("span",{class:"mono",children:[w.from??"–"," → ",w.to??"–"]}),t("span",{class:"flex-1"}),w.error?t(He,{label:w.error,color:"var(--red)"}):t(He,{label:w.changed?"changed":"unchanged",color:`var(${w.changed?"--green":"--ink-3"})`})]},`${w.host}:${w.name}`))]}),(o==null?void 0:o.finishError)&&t("p",{style:{...oe,background:Q("--orange")},children:o.finishError}),c&&t("p",{style:{...oe,background:Q("--red")},children:c}),!o&&l("p",{style:fe,children:["Kioku installs it on this machine for every session.",e.includes("-")?" Back to stable undoes it.":""]})]})})},os=({mismatch:e,tool:n,onTry:a})=>{const[r,o]=v(!1),{fix:i}=e,c=async()=>{o(!0),await St(`${on(e.plugin)}/update`,{scope:e.scope,scopeRef:e.scopeRef})&&(j(`Kioku's plugin updated in ${e.scopeRef} · applies to new sessions`,"success"),await wr()),o(!1)};let s=null;return(i==null?void 0:i.kind)==="release"&&(s=t(I,{label:`Try ${i.version}`,variant:"primary",size:"sm",onClick:()=>a(i.version)})),(i==null?void 0:i.kind)==="plugin"&&(s=t(I,{label:r?"Updating…":"Update plugin",variant:"primary",size:"sm",disabled:r,onClick:c})),l("div",{class:"flex flex-col",style:{gap:"4px"},children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[l("span",{class:"flex-1",children:[e.scopeRef,": plugin ",t("span",{class:"mono",children:e.version}),", tool ",t("span",{class:"mono",children:n})]}),s]}),i?t(Ae,{text:i.command}):t("span",{style:fe,children:"No kioku release of that major yet."})]})},ls=({onTry:e})=>{const n=wt.value;return!(n!=null&&n.installed)||n.mismatches.length===0?null:l("section",{class:"flex flex-col",style:{...oe,gap:"8px",background:Q("--orange")},children:[t("p",{style:{fontWeight:600},children:"Kioku does nothing in these sessions: its plugin and the tool have different major versions."}),n.mismatches.map(a=>t(os,{mismatch:a,tool:n.installed,onTry:e},`${a.scope}:${a.scopeRef}`))]})},is=({lab:e})=>{const[n,a]=v(!1),r=async o=>{a(!0);try{ca.value=await ce(`/api/kioku/labs/${encodeURIComponent(e.name)}`,{enabled:o}),j(`${e.title} ${o?"on":"off"} · applies from the next session`,"info")}catch(i){j(le(i),"error")}finally{a(!1)}};return l("div",{class:"flex flex-col",style:{...Xr,gap:"6px"},children:[l("div",{class:"flex items-center",style:{gap:"10px"},children:[t("span",{style:{fontWeight:600},children:e.title}),t("span",{class:"flex-1"}),t(cn,{checked:e.enabled,disabled:n,label:`${e.title} enabled`,onChange:r})]}),e.about&&t("p",{style:{color:"var(--ink-2)"},children:e.about}),t(Ae,{text:e.toggle}),e.command&&l("div",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{style:fe,children:"In a session"}),t(Ae,{text:e.command}),t(Qn,{command:e.command,plugin:"kioku",disabled:!e.enabled,note:"A session has it only when it was opened after the lab was switched on."})]}),Object.entries(e.settings??{}).map(([o,i])=>{var c;return l("div",{class:"flex items-center",style:{gap:"8px"},children:[t("span",{class:"mono",style:fe,children:o}),t("span",{class:"mono",children:JSON.stringify(i)}),t("span",{class:"flex-1"}),((c=e.set)==null?void 0:c[o])&&t(Ae,{text:e.set[o]})]},o)})]})},ss=()=>{var n,a;const e=ca.value;return(n=e==null?void 0:e.labs)!=null&&n.length?t(eo,{title:`LABS · ${((a=wt.value)==null?void 0:a.installed)??""}`,aside:t("span",{style:fe,children:"off by default, may change in any version"}),command:e.command,children:e.labs.map(r=>t(is,{lab:r},r.name))}):null},cs=[{label:"Personal",tiers:["personal"]},{label:"Projects",tiers:["project","client"]},{label:"Team",tiers:["team"]}],ds={save:"--green",update:"--blue",supersede:"--blue",evolve:"--purple",link:"--teal",confirm:"--green",retire:"--red",forget:"--red"},ps=({brain:e})=>{const n=Object.entries(e.kinds).filter(([,a])=>a>0).sort((a,r)=>r[1]-a[1]);return l(H,{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(${va(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(ze,{color:`var(${va(a)})`}),a," ",r]},a))})]})},La={fontSize:"11.5px",fontWeight:500,color:"var(--blue)",background:"none",border:0,padding:0,cursor:"pointer"},Ea=({brain:e,usedBy:n,showTier:a,onDialog:r})=>{const o=Ve(e.tier);return l("div",{class:"flex flex-col min-w-0",style:{...Ee,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?Rt(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(ps,{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(He,{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:La,onClick:()=>r({kind:"area",brain:e}),children:"+ Area"}),t("span",{class:"flex-1"}),!e.remote&&l(H,{children:[t("span",{style:{fontSize:"11.5px",color:"var(--ink-3)"},children:"only on this machine"}),t("button",{type:"button",style:La,onClick:()=>r({kind:"publish",brain:e}),children:"Publish…"})]})]})]})},us=({writes:e})=>l("section",{style:{...Ee,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(He,{label:n.verb,color:`var(${ds[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}`:""," · ",Rt(n.date)]})]},`${n.brain}:${n.path}:${n.date}:${n.verb}`))]}),hs=({project:e,onProject:n})=>{const[a,r]=v(!1),[o,i]=v(null),c=()=>i(null);D(()=>Sr(),[]);const s=be.value,d=(s==null?void 0:s.installed)===!0;D(()=>{d&&Un(!1,!e)},[d,e]);const f=C=>i({kind:"version",version:C}),g=async()=>{const C=window.open("","_blank");r(!0);try{const{address:u}=await ce("/api/kioku/viewer",{});C?C.location.href=u:j(`Viewer running at ${u}`,"info"),Pe()}catch(u){C==null||C.close(),j(le(u),"error")}finally{r(!1)}},y=async()=>{await fetch("/api/kioku/viewer",{method:"DELETE"}).catch(()=>{}),Pe()},m=(s==null?void 0:s.brains)??[],w=(s==null?void 0:s.projects)??{},k=Object.keys(w).filter(C=>w[C].some(u=>u.tier!=="personal")).sort();e&&!k.includes(e)&&k.unshift(e);const b=e?da(e):[],p=C=>Object.keys(w).filter(u=>w[u].some(z=>z.name===re(C))).sort(),x=new Set(b.map(re)),S=((s==null?void 0:s.activity)??[]).filter(C=>!e||x.has(C.brain)).slice(0,15),h=d?e?`${e} · ${nn(b)} pages its sessions can recall`:`Kioku ${s.version??""} · ${nn(m)} pages in ${m.length} brain${m.length===1?"":"s"}`:"Kioku brains on this machine";return l(H,{children:[l(et,{title:"Memory",subtitle:h,children:[(s==null?void 0:s.viewer)&&t(I,{label:"Stop viewer",variant:"secondary",onClick:y}),t(I,{label:"Refresh",variant:"secondary",onClick:()=>Pe(!0).then(()=>d&&Un(!0,!e))}),t(I,{label:"New brain",variant:"secondary",disabled:!d,onClick:()=>i({kind:"brain"})}),t(I,{label:"New memory",variant:"secondary",disabled:!m.some(C=>C.onDisk),onClick:()=>i({kind:"memory"})}),t(I,{label:s!=null&&s.viewer?"Viewer open ↗":"Open viewer",variant:"primary",disabled:!d||a,onClick:g})]}),l("div",{class:"flex flex-col w-full",style:{padding:"18px 22px 40px",gap:"14px",maxWidth:"1180px"},children:[s&&!s.installed&&l("p",{style:{...oe,background:Q("--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"}),"."]}),d&&t(ls,{onTry:f}),d&&!e&&l("div",{class:"grid items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 380px), 1fr))",gap:"12px"},children:[t(as,{onTry:f}),t(ss,{})]}),d&&m.length===0&&t(Oe,{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."}),m.length>0&&k.length>0&&t("div",{class:"flex",children:t(de,{size:"sm",label:"Project",tabs:[{id:"",label:"All"},...k.map(C=>({id:C,label:C}))],active:e??"",onChange:C=>n(C||null)})}),m.length>0&&!e&&t("div",{class:"flex flex-wrap",style:{gap:"14px 12px"},children:cs.map(C=>{const u=m.filter(z=>C.tiers.includes(z.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(${Ve(C.tiers[0])})`},children:["● ",C.label.toUpperCase(),u.length>1&&t("span",{style:{color:"var(--ink-3)"},children:u.length})]}),t("div",{class:"grid",style:{gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:"12px"},children:u.map(z=>t(Ea,{brain:z,usedBy:p(z),onDialog:i},z.key))})]},C.label)})}),e&&b.length>0&&t("div",{class:"grid items-center",style:{gridTemplateColumns:b.map(()=>"minmax(0, 1fr)").join(" 24px ")},children:b.map((C,u)=>l(ro,{children:[u>0&&t("span",{style:{textAlign:"center",color:"var(--ink-3)",fontSize:"16px"},children:"→"}),t(Ea,{brain:C,showTier:!0,onDialog:i})]},C.key))}),e&&d&&!b.some(C=>C.tier!=="personal")&&l("div",{class:"flex items-center",style:{...oe,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"})})]}),m.length>0&&t(us,{writes:S}),d&&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(ts,{project:e,onClose:c}),(o==null?void 0:o.kind)==="brain"&&t(Qi,{onClose:c}),(o==null?void 0:o.kind)==="link"&&e&&t(Zi,{project:e,onClose:c}),(o==null?void 0:o.kind)==="area"&&t(Qr,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="publish"&&t(Xi,{brain:o.brain,onClose:c}),(o==null?void 0:o.kind)==="version"&&t(rs,{version:o.version,onClose:c})]})},$t=Y(null);function fs(e,n){var a;return(a=$t.value)==null||a.resolve(!1),new Promise(r=>{$t.value={confirmation:e,module:n,resolve:r}})}const Pn=e=>{const n=$t.value;$t.value=null,n==null||n.resolve(e)},gs=()=>{var a;const e=$t.value;if(!e)return null;const{confirmation:n}=e;return l(Re,{open:!0,title:n.title,onClose:()=>Pn(!1),footer:l(H,{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:()=>Pn(!1)}),t(I,{label:n.confirmLabel,variant:"destructive",onClick:()=>Pn(!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))})]})},Ut=e=>`/api/modules/${encodeURIComponent(e)}`;async function An(e){const n=await e.json().catch(()=>({}));throw new Xt(n.code??`http_${e.status}`,n.message??n.error??`Request failed (${e.status})`)}const Na=(e,n)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});async function xs(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 f;for(;(f=o.indexOf(`
26
26
 
27
- `))>=0;){const g=o.slice(0,f);o=o.slice(f+2);const y=(i=/^event: (.*)$/m.exec(g))==null?void 0:i[1],m=JSON.parse(((c=/^data: (.*)$/m.exec(g))==null?void 0:c[1])??"null");if(y==="output"&&m.chunk&&n(m.chunk),y==="done")return m.result;if(y==="error")throw new Qt(m.code??"module_error",m.message??"action failed")}}throw new Qt("module_error","the action stream ended early")}function ms(e,n,a){const r=Y({}),o=async()=>{const c=await fetch(`${_t(e)}/settings`);c.ok&&(r.value=await c.json())};o();const i=async(c,s,d,f)=>{const g=`${_t(e)}/actions/${encodeURIComponent(c)}${f?"/stream":""}`,y=await Ea(g,{input:s,token:d});return y.status===409?{needsConfirmation:!0}:y.ok?f?{result:await xs(y,f)}:{result:(await y.json()).result}:jn(y)};return{settings:r,status:Fa(()=>ke.value.find(c=>c.id===e)),openSettings:a,reloadSettings:o,async route(c,s){const d=await fetch(`${_t(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():jn(d)},async action(c,s,d){var k,b,p;if(((p=(b=(k=ke.value.find(x=>x.id===e))==null?void 0:k.actions)==null?void 0:b.find(x=>x.id===c))==null?void 0:p.effect)!=="external"){const x=await i(c,s,void 0,d==null?void 0:d.onOutput);if(!("needsConfirmation"in x))return x.result}const g=await Ea(`${_t(e)}/actions/${encodeURIComponent(c)}/prepare`,{input:s});if(!g.ok)return jn(g);const{confirmation:y,token:m}=await g.json();if(!await fs(y,n()))return;const w=await i(c,s,m,d==null?void 0:d.onOutput);if("needsConfirmation"in w)throw new Qt("confirmation_required","The confirmation expired; try again");return w.result}}}const ea=({value:e,onChange:n,initialPath:a,requireGit:r=!0})=>{const[o,i]=v(a??"~"),[c,s]=v(o),[d,f]=v([]),[g,y]=v(null),[m,w]=v(null),[k,b]=v(""),[p,x]=v(!1),[S,h]=v(!1),[C,u]=v(null);M(()=>{let A=!1;return(async()=>{h(!0),u(null);try{const q=await(await fetch(`/api/cw/browse-dirs?path=${encodeURIComponent(o)}`)).json();if(A)return;if(!q.ok){u(q.error??"Failed to load directory"),f([]);return}f(q.entries??[]),y(q.parent??null),w(q.home??null),b(q.path??o),x(!!q.isGitRepo)}catch{A||(u("Network error"),f([]))}finally{A||h(!1)}})(),()=>{A=!0}},[o]);const z=A=>{i(A),s(A)},L=e===k,N=r&&!p,O=k?m&&k===m?"~":m&&k.startsWith(m+"/")?"~"+k.slice(m.length):k:o,T={width:"24px",height:"24px",borderRadius:"7px",border:0,background:"var(--card)",color:"var(--ink-2)",boxShadow:"var(--shadow-s)"},P="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev disabled:cursor-not-allowed disabled:opacity-60",R={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:Q("--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:T,onClick:()=>g&&z(g),disabled:!g||S,title:"Parent folder","aria-label":"Parent folder",children:"←"}),t("button",{type:"button",class:"grid place-items-center cursor-pointer",style:T,onClick:()=>z("~"),title:"Home","aria-label":"Home",children:"~"}),t("input",{type:"text",value:c,"aria-label":"Path",onInput:A=>s(A.target.value),onBlur:()=>i(c),onKeyDown:A=>{A.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:Q("--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:S?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:"Loading…"}):C?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--red)"},children:C}):l(H,{children:[l("button",{type:"button",class:P,style:{...R,background:L?"var(--elev)":"none",fontWeight:600},onClick:()=>n(k,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(A=>l("button",{type:"button",class:P,style:R,onClick:()=>z(A.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:A.name}),A.isGitRepo&&t("span",{style:B,children:"git"})]},A.path))]})})]})},to={fontSize:"11.5px",color:"var(--red)"},Na=e=>e.type==="boolean"||e.type==="string"&&e.format==="path",Oa=({def:e,value:n,projects:a,onChange:r})=>e.type==="boolean"?t(rn,{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(ea,{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))}),Wa=({def:e,error:n,plain:a,children:r})=>l(U,{plain:a,label:l(H,{children:[e.label??"",e.required?" *":""]}),children:[r,e.help&&t("span",{style:ve,children:e.help}),n&&t("span",{style:to,children:n})]}),vs=({moduleId:e,displayName:n,schema:a,onClose:r,onSaved:o})=>{const[i,c]=v(null),[s,d]=v({}),[f,g]=v([]),[y,m]=v(!1),w=`/api/modules/${encodeURIComponent(e)}/settings`;M(()=>{fetch(w).then(x=>x.json()).then(c).catch(()=>c({})),fetch("/api/cw/projects").then(x=>x.json()).then(x=>g(Object.keys(x))).catch(()=>{})},[w]);const k=(x,S)=>c(h=>({...h,[x]:S})),b=(x,S,h,C)=>c(u=>{const z=[...(u==null?void 0:u[x])??[]];return z[S]={...z[S],[h]:C},{...u,[x]:z}}),p=async()=>{m(!0);try{const x=await fetch(w,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(x.status===400){const{errors:S}=await x.json();d(Object.fromEntries(S.map(h=>[h.path,h.message])));return}if(!x.ok)throw new Error(`Saving failed (${x.status})`);d({}),j(`${n} settings saved`,"success"),o(),r()}catch(x){j(le(x),"error")}finally{m(!1)}};return t(Ze,{title:`${n} settings`,onClose:r,children:i?l("div",{class:"flex flex-col",style:{gap:"14px"},children:[Object.entries(a).map(([x,S])=>{if(S.type!=="list")return t(Wa,{def:{...S,label:S.label??x},error:s[x],plain:Na(S),children:t(Oa,{def:S,value:i[x],projects:f,onChange:C=>k(x,C)})},x);const h=i[x]??[];return l("div",{class:"flex flex-col",style:{gap:"10px"},children:[t("span",{style:{...ve,fontWeight:600},children:S.label??x}),S.help&&t("span",{style:ve,children:S.help}),s[x]&&t("span",{style:to,children:s[x]}),h.map((C,u)=>l("div",{class:"flex flex-col",style:{gap:"10px",padding:"12px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},children:[Object.entries(S.item).map(([z,L])=>t(Wa,{def:{...L,label:L.label??z},error:s[`${x}[${u}].${z}`],plain:Na(L),children:t(Oa,{def:L,value:C[z],projects:f,onChange:N=>b(x,u,z,N)})},z)),t("div",{children:t(I,{label:"Remove",variant:"danger",size:"sm",onClick:()=>c(z=>({...z,[x]:h.filter((L,N)=>N!==u)}))})})]},u)),t("div",{children:t(I,{label:`Add ${(S.label??x).replace(/s$/,"").toLowerCase()}`,icon:"i-lucide-plus",variant:"secondary",size:"sm",onClick:()=>k(x,[...h,{}])})})]},x)}),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:y,onClick:p})]})]}):t("div",{class:"text-ink2",style:{fontSize:"13px"},children:"Loading…"})})};class ys extends oo{constructor(){super(...arguments);fa(this,"state",{error:null})}componentDidCatch(a){this.setState({error:a})}render(){const{error:a}=this.state;return a?t(ta,{title:`${this.props.name}'s view crashed`,message:a.message,onReload:()=>{this.setState({error:null}),this.props.onReload()}}):this.props.children}}const ta=({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})})]}),bs=({status:e,onClose:n,onRemoved:a})=>{const[r,o]=v(!1),i=async()=>{o(!0);try{ke.value=await Rt("DELETE",`/api/modules/${encodeURIComponent(e.id)}`),j(`Removed ${e.displayName}`,"success"),a()}catch(c){j(le(c),"error"),o(!1)}};return t(Re,{open:!0,title:`Remove ${e.displayName}?`,onClose:n,footer:l(H,{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."]})})},Pn=new Map;function ks(e){const n=`${e.view.url}?v=${encodeURIComponent(e.view.version)}`;let a=Pn.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(()=>Pn.delete(n)),Pn.set(n,a)),a}const ws=({moduleId:e,cwProject:n,onBack:a})=>{var u,z,L,N;const r=ke.value.find(O=>O.id===e),[o,i]=v(!1),[c,s]=v(!1),[d,f]=v(null),[g,y]=v(0),m=ie(e);r&&(m.current=r.displayName);const w=m.current,k=ee(()=>ms(e,()=>m.current,()=>i(!0)),[e]),b=(r==null?void 0:r.state)==="enabled"?(u=r.view)==null?void 0:u.version:void 0,p=((z=dr.value[e])==null?void 0:z.attention)??0;M(()=>{p>0&&qo(e)},[e,p]),M(()=>{if(!r||!b)return;let O=!0;return ks(r).then(T=>{O&&f({version:b,config:T})},T=>{O&&f({version:b,error:T.message})}),()=>{O=!1}},[e,b,g]);const x=r?cr(r):null,S=l(et,{title:((L=r==null?void 0:r.view)==null?void 0:L.title)??w,subtitle:r?`${r.name} ${r.version}`:void 0,children:[x&&l("span",{class:"mono truncate",title:x,style:{maxWidth:"320px",fontSize:"11.5px",color:"var(--orange)"},children:["⚠ ",x]}),(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(bs,{status:r,onClose:()=>s(!1),onRemoved:a})]});if(!r)return l("div",{children:[S,t("div",{style:{padding:"56px 22px"},children:t(Oe,{icon:"i-lucide-package-x",title:`${w} was removed`,description:"The module is no longer installed.",action:{label:"Back to Tasks",onClick:a}})})]});if(r.state!=="enabled")return l("div",{children:[S,t(ta,{title:`${w} is disabled`,message:r.reason??"No reason given",onReload:()=>{vt()}})]});const h=d&&d.version===b?d:null,C=(N=h==null?void 0:h.config)==null?void 0:N.component;return l("div",{children:[S,h!=null&&h.error?t(ta,{title:`${w}'s view did not load`,message:h.error,onReload:()=>y(O=>O+1)}):C?t(ys,{name:w,onReload:()=>y(O=>O+1),children:t(C,{moduleId:e,projectId:null,cwProject:n,forge:k})},`${b}-${g}`):l("div",{class:"py-20 text-center text-ink2",children:["Loading ",w,"…"]}),o&&r.settingsSchema&&t(vs,{moduleId:e,displayName:w,schema:r.settingsSchema,onClose:()=>i(!1),onSaved:()=>{k.reloadSettings(),vt()}})]})},An={padding:"12px 14px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},Ss=({onClose:e,onInstalled:n})=>{const[a,r]=v(""),[o,i]=v(null),[c,s]=v(null),[d,f]=v(null),g=async()=>{f("preview"),s(null);try{i(await ce("/api/modules/install/preview",{spec:a}))}catch(m){s(le(m))}finally{f(null)}},y=async()=>{if(o){f("install"),s(null);try{const{status:m,modules:w}=await ce("/api/modules/install",{token:o.token});ke.value=w,(m==null?void 0:m.state)==="disabled"?j(`Installed ${o.displayName}, but Forge disabled it: ${m.reason??""}`,"error"):j(`Installed ${o.displayName}`,"success"),m&&n(m),e()}catch(m){i(null),s(le(m))}finally{f(null)}}};return l(Ze,{title:"Add a module",onClose:e,children:[l("form",{class:"flex flex-col",style:{gap:"10px"},onSubmit:m=>{m.preventDefault(),a.trim()&&!d&&g()},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:ve,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:{...An,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:An,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:{...ve,fontWeight:600},children:o.permissions.length?"It asks for":"It asks for no permissions"}),o.permissions.map((m,w)=>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})]},w))]}),t("p",{style:{...An,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:y}):t(I,{label:"Review",loading:d==="preview",disabled:!a.trim(),onClick:g})]})]})},Cs=({open:e,accounts:n,onClose:a,onCreated:r})=>{const[o,i]=v("create"),[c,s]=v(""),[d,f]=v(""),[g,y]=v(""),[m,w]=v(""),[k,b]=v(""),[p,x]=v(""),[S,h]=v(!1),[C,u]=v(""),[z,L]=v(!1);M(()=>{e&&n.length>0&&!c&&s(n[0])},[e,n]),M(()=>{e||(i("create"),f(""),y(""),w(""),b(""),x(""),h(!1),u(""),L(!1))},[e]);const N=c.trim().length>0&&d.trim().length>0&&m.trim().length>0,O=c.trim().length>0&&p.length>0&&S,T=async()=>{if(N){L(!0);try{const F=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:g.trim()||void 0,model:k||void 0})})).json();F.ok?(j("Project creation started in terminal","success"),r(F.session)):j(F.error??"Failed to create project","error")}catch{j("Failed to create project","error")}finally{L(!1)}}},P=async()=>{if(O){L(!0);try{const F=await(await fetch("/api/cw/register-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p,account:c.trim(),alias:C.trim()||void 0})})).json();F.ok?(j(`Project "${F.project}" registered`,"success"),r()):j(F.error??"Failed to register project","error")}catch{j("Failed to register project","error")}finally{L(!1)}}},R=o==="create";return t(Re,{open:e,title:"Add a project",onClose:a,footer:l(H,{children:[t("span",{class:"mono flex-1 truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:R?"cw create":"cw project register"}),t(I,{label:"Cancel",variant:"secondary",onClick:a}),t(I,{label:R?z?"Creating…":"Create":z?"Registering…":"Register",variant:"primary",loading:z,disabled:!(R?N:O),onClick:R?T:P})]}),children:l("div",{class:"flex flex-col",style:{gap:"13px"},children:[t(de,{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)})}),R?t(U,{label:"Project name",children:t("input",{type:"text",class:"field",value:d,placeholder:"my-new-project",onInput:D=>f(D.target.value)})}):t(U,{label:"Alias",children:t("input",{type:"text",class:"field",value:C,placeholder:"defaults to folder name",onInput:D=>u(D.target.value)})})]}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:ve,children:R?"Parent folder · optional":"Repository · must contain .git"}),R?t(ea,{value:g,onChange:y,requireGit:!1},"dir-create"):t(ea,{value:p,onChange:(D,F)=>{x(D),h(F)}},"dir-existing")]}),R&&l(H,{children:[t(U,{label:"Description",children:t("textarea",{rows:2,class:"field",value:m,placeholder:"A SaaS platform for…",onInput:D=>w(D.target.value)})}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:ve,children:"Model"}),t(de,{size:"sm",label:"Model",tabs:[{id:"",label:"Auto"},{id:"haiku",label:"Haiku"},{id:"sonnet",label:"Sonnet"},{id:"opus",label:"Opus"}],active:k,onChange:b})]})]})]})})},$s=(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"}},zs=(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(" · ")},_e=({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?Q(e):"var(--elev)",color:e?`var(${e})`:"var(--ink-3)"},children:[t("span",{style:{width:"6px",height:"6px",borderRadius:"50%",background:"currentColor"}}),n]}),Rs=({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(_e,{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(_e,{token:null,label:"Not installed"});case"error":return t(_e,{token:"--red",label:"Error"});case"local":return t(_e,{token:"--orange",label:"Local"});case"api_key":return t(_e,{token:"--green",label:"API key"});case"connected":return t(_e,{token:"--green",label:"Connected"});case"connect":return t(I,{label:"Connect",size:"sm",onClick:n})}},In=({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})]}),Ln=({warn:e,children:n})=>t("span",{style:{fontSize:"11.5px",color:e?"var(--orange)":"var(--ink-3)"},children:n}),Ts=({account:e,harness:n})=>{const a=Eo(e,n);return!a||a.state==="not_connected"?null:a.state==="expired"?t(In,{children:t(Ln,{warn:!0,children:"Reconnect to see usage limits"})}):a.state==="error"?t(In,{children:l(Ln,{children:["Limits unavailable — ",a.detail??"the request failed"]})}):a.windows.length===0?null:l(In,{children:[t(Ba,{bars:Va(a.windows)}),a.stale&&l(Ln,{children:["Last known values — ",a.detail??"the refresh failed"]})]})},js=3e3,Ps=({account:e,harness:n,canUseApiKey:a,onConnected:r,onClose:o})=>{const[i,c]=v(null),[s,d]=v(!1),[f,g]=v(0),[y,m]=v(""),[w,k]=v(!1),b=ge(n).label,p=`/api/cw/accounts/${encodeURIComponent(e)}`,x=`${p}/login/${encodeURIComponent(n)}`,S=ie(!1),h=ie(!1);M(()=>{let L=!1,N=null;c(null),d(!1),S.current=!1,h.current=!1;const O=()=>{S.current||(S.current=!0,fetch(x,{method:"DELETE"}).catch(()=>{}),j(`${e} is connected to ${b}`,"success"),r())},T=async()=>{var D;const R=await fetch(x).catch(()=>null);if(!(R!=null&&R.ok)||L)return;const{login:B}=await R.json();if(c(B),B.status!=="exited"||(h.current=!0,N&&(clearInterval(N),N=null),B.exitCode!==0))return;d(!0);const A=await ye(!0);L||(A.available&&((D=We(A.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(R=>R.json()).then(R=>{if(!L){if(!R.ok||!R.login){j(R.error??"Could not start the login","error");return}c(R.login),N=setInterval(T,js)}}).catch(()=>j("Could not start the login","error"));const P=tl(R=>{var B;return((B=We(R,e,n))==null?void 0:B.status)==="connected"},{onDone:R=>{R&&O()}});return()=>{L=!0,N&&clearInterval(N),P(),h.current||fetch(x,{method:"DELETE"}).catch(()=>{})}},[e,n,f]);const C=()=>{fetch(x,{method:"DELETE"}).catch(()=>{}),o()},u=async()=>{const L=y.trim();if(L){k(!0);try{const O=await(await fetch(`${p}/api-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n,apiKey:L})})).json();O.ok?(m(""),j("API key saved","success"),ye(!0)):j(O.error??"Could not save the API key","error")}catch{j("Could not save the API key","error")}finally{k(!1)}}},z=(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 ",b]}),t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:C})]}),!i&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Starting the login…"}),i&&!z&&l(H,{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(H,{children:[t("span",{class:"mono",style:{fontSize:"19px",fontWeight:650,letterSpacing:".12em"},children:i.code}),t(I,{label:"Copy",variant:"secondary",size:"sm",onClick:()=>sn(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…"})]}),z&&s&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Checking the connection…"}),z&&!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:()=>g(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:y,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:w,disabled:!y.trim(),onClick:u})]}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:"Sent to cw over stdin. Forge never stores or shows it."})]})]})},Kt={display:"block",fontSize:"12px",color:"var(--ink-2)",marginBottom:"5px"},As=({response:e,onCancel:n,onCreated:a})=>{const[r,o]=v(""),[i,c]=v(""),[s,d]=v(""),[f,g]=v(""),[y,m]=v(!1),w=zt(),k=r.trim(),b=ko.test(k),p=e!=null&&e.available?e.doctor.harnesses.map(h=>h.name).filter(h=>h!=="claude"):[],x=!!i&&qe(e,i,"custom_provider"),S=async()=>{if(!(!b||y)){m(!0);try{const C=await(await fetch("/api/cw/accounts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:k,harness:i||void 0,provider:x&&s.trim()||void 0,model:x&&f.trim()||void 0})})).json();C.ok?(j(`Account "${k}" created`,"success"),a()):j(C.error??"Failed to create account","error")}catch{j("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:Kt,for:"new-account-name",children:"Account name"}),t("input",{id:"new-account-name",type:"text",value:r,onInput:h=>o(h.target.value),onKeyDown:h=>{h.key==="Enter"&&S()},placeholder:"my-account",class:"field",ref:w}),k&&!b&&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:Kt,children:"Default harness"}),t(de,{label:"Default harness",tabs:[{id:"",label:"Claude Code"},...p.map(h=>({id:h,label:ge(h).label}))],active:i,onChange:c}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)",marginTop:"5px"},children:"The default harness cannot be changed later."})]}),x&&l("div",{class:"grid",style:{gridTemplateColumns:"1fr 1fr",gap:"10px",maxWidth:"520px"},children:[l("div",{children:[t("label",{style:Kt,children:"Provider · optional"}),t("input",{type:"text",value:s,onInput:h=>d(h.target.value),placeholder:"zai, ollama, openrouter",class:"field"})]}),l("div",{children:[t("label",{style:Kt,children:"Model · optional"}),t("input",{type:"text",value:f,onInput:h=>g(h.target.value),placeholder:"glm-5.1",class:"field"})]})]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:y?"Creating…":"Add account",variant:"primary",loading:y,disabled:!b,onClick:S}),t(I,{label:"Cancel",variant:"secondary",onClick:n})]})]})},Is=new Set(["localhost","127.0.0.1","::1","[::1]"]),Da={...Le,overflow:"hidden"},Ls=({account:e,onRemoved:n})=>{const[a,r]=v(!1),o=async()=>{try{const c=await(await fetch(`/api/cw/accounts/${encodeURIComponent(e)}`,{method:"DELETE"})).json();c.ok?(j(`Account "${e}" removed`,"info"),n()):j(c.error??"Failed to remove account","error")}catch{j("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)})},Es=({projects:e,onOpenSession:n,onAccountsChanged:a})=>{const[r,o]=v(null),[i,c]=v(!1);M(()=>{ye()},[]),M(()=>ar(),[]);const s=ln.value,d=!Is.has(window.location.hostname),f=s!=null&&s.available?s.doctor:null,g=()=>{r&&(fetch(`/api/cw/accounts/${encodeURIComponent(r.account)}/login/${encodeURIComponent(r.harness)}`,{method:"DELETE"}).catch(()=>{}),o(null))},y=async(p,x)=>{if(qe(s,x,"headless_login")){o({account:p,harness:x});return}try{const h=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"login",account:p,harness:x})})).json();h.ok&&h.session?n(h.session):j(h.error??"Could not open the login","error")}catch{j("Could not open the login","error")}},m=f?f.accounts.reduce((p,x)=>p+x.harnesses.filter(S=>S.status==="not_logged_in").length,0):0,w=f?`${f.accounts.length} account${f.accounts.length===1?"":"s"} · ${f.harnesses.length} harnesses · ${m} need${m===1?"s":""} connecting`:"Reading cw doctor…",k=p=>Object.values(e).filter(x=>x.account===p).length,b=(p,x)=>{if(!f)return null;const[S,h]=Ua(x),C=k(p.name),u=We(f,p.name,p.default_harness),z=[ge(p.default_harness).label,u&&u.provider!=="native"?u.provider:null].filter(Boolean).join(" · ");return l("section",{style:{...Da,animation:`riseIn .36s var(--ease) ${x*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(${S}), var(${h}))`,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 ",z," · ",C," project",C===1?"":"s"]}),t("span",{class:"flex-1"}),t(Ls,{account:p.name,onRemoved:()=>{ye(!0),a()}})]}),f.harnesses.map(L=>{const N=We(f,p.name,L.name),O=(r==null?void 0:r.account)===p.name&&r.harness===L.name,T=ge(L.name),P=N?$s(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:T.color}}),T.label]}),t("span",{class:"flex-1",style:{minWidth:"140px",fontSize:"12.5px",color:"var(--ink-2)"},children:N&&P?zs(P,L.version,qe(s,L.name,"headless_login"),N):"Not configured for this account"}),P&&t(Rs,{view:P,onConnect:()=>{y(p.name,L.name)},onCancel:g})]}),N&&t(Ts,{account:p.name,harness:L.name}),O&&t("div",{style:{padding:"0 15px 13px"},children:t(Ps,{account:p.name,harness:L.name,canUseApiKey:qe(s,L.name,"api_key_login"),onConnected:()=>o(null),onClose:()=>o(null)},`${p.name}::${L.name}`)})]},L.name)})]},p.name)};return l(H,{children:[l(et,{title:"Accounts",subtitle:w,children:[t(I,{label:"Refresh",variant:"secondary",onClick:()=>{ye(!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),ye(!0),a()}}),s&&!s.available&&l("section",{style:{...Da,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:()=>{ye(!0)}})]}),f&&d&&t("p",{style:{...oe,background:Q("--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."}),f&&f.issues.map(p=>t("p",{style:{...oe,background:Q("--red"),color:"var(--ink)"},children:p.message},p.code)),f&&f.warnings.map(p=>t("p",{style:{...oe,background:"var(--elev)",color:"var(--ink-2)"},children:p.message},p.code)),f==null?void 0:f.accounts.map(b)]})]})},Ma="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev",Ns=({sessions:e,openTabKeys:n,onOpenSession:a,onNewTask:r,onClose:o,position:i})=>{const c=ie(null);M(()=>{const d=g=>{c.current&&!c.current.contains(g.target)&&o()},f=g=>{g.key==="Escape"&&o()};return document.addEventListener("mousedown",d),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",f)}},[o]);const s=e.filter(d=>!n.has(G(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"}),Xe.map(d=>l("button",{type:"button",class:Ma,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{r(d.key),o()},children:[t(Hn,{type:d.sessionType,size:22,radius:7,font:10}),t("span",{class:"flex-1",children:aa(d.key)})]},d.key)),s.length>0&&l(H,{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:Ma,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{a(d),o()},children:[t(Hn,{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:se(d)})]},G(d)))]})]})},Os=({tabs:e,activeIndex:n,onActivate:a,onClose:r,onBack:o,allSessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d})=>{const[f,g]=v(!1),y=ie(null),[m,w]=v({top:0,left:0}),k=J(()=>g(!1),[]),b=()=>{if(!f&&y.current){const p=y.current.getBoundingClientRect();w({top:p.bottom+6,left:Math.max(8,Math.min(p.left,window.innerWidth-328))})}g(!f)};return l(H,{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(pa,{}),t(Rl,{onClick:o}),e.map((p,x)=>{const S=x===n,h=Ae.value[G(p)],C=!S&&Je(h);return l("div",{role:"tab",tabIndex:0,"aria-selected":S,title:[C?Zt(h):null,x<5?`⌘${x+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:S?"var(--card)":"transparent",border:`1px solid ${S?"var(--hair)":"transparent"}`,boxShadow:S?"var(--shadow-s)":"none"},onClick:()=>a(x),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),a(x))},children:[t(ze,{size:6,live:p.status==="active",color:C?`var(${Ut(h)})`:void 0}),t("span",{style:{fontWeight:600,color:S?"var(--ink)":"var(--ink-2)"},children:ue(p)}),t("span",{class:"mono truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"110px"},children:se(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:u=>{u.stopPropagation(),r(x)},title:"Close tab (⌘W)","aria-label":`Close ${ue(p)}`,children:t("span",{class:"i-lucide-x",style:{width:"13px",height:"13px"}})})]},G(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:b,"aria-expanded":f,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"}})})]}),f&&t(Ns,{sessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d,onClose:k,position:m})]})};function Ws(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?kt(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(Re,{open:!0,title:"Close this task?",onClose:n,footer:l(H,{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:Ws(c,e.state)},c))}),e.error&&t("p",{style:{marginTop:"10px",fontSize:"12.5px",color:"var(--ink-2)"},children:e.error})]})},En="forge-open-tabs";function Ms({spaces:e,loading:n,onFetchData:a}){const[r,o]=v([]),[i,c]=v(0),[s,d]=v(!0),f=ie(!1),g=ie(r);g.current=r,M(()=>{if(!(n||e.length===0||f.current)){f.current=!0;try{const p=sessionStorage.getItem(En);if(!p)return;const{keys:x,activeIndex:S}=JSON.parse(p),h=[];for(const C of x){const u=e.find(z=>G(z)===C);u&&h.push(u)}h.length>0&&(o(h),c(Math.min(S,h.length-1)))}catch{}}},[n,e]),M(()=>{if(f.current)if(r.length>0){const p=r.map(G);sessionStorage.setItem(En,JSON.stringify({keys:p,activeIndex:i}))}else sessionStorage.removeItem(En)},[r,i]);const y=J(p=>{const x=G(p),S=r.findIndex(h=>G(h)===x);S>=0?c(S):(o(h=>[...h,p]),c(r.length)),d(!1)},[r]),m=J(async p=>{const x=g.current.find(u=>G(u)===p);if(!x)return;const S=x.sessionDir??(x.type==="review"?`review-pr-${x.pr}`:`task-${x.task}`);try{await fetch("/api/cw/terminal/kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:x.project,sessionDir:S})})}catch{}const h=g.current.findIndex(u=>G(u)===p);if(h<0)return;Io(p);const C=g.current.length-1;o(u=>u.filter(z=>G(z)!==p)),C===0?(d(!0),c(0),a()):c(u=>u>h?u-1:Math.min(u,C-1))},[a]),w=J(p=>{const x=r[p];return x?m(G(x)):Promise.resolve()},[r,m]),k=J(()=>{d(!0),a()},[a]);M(()=>{const p=x=>{if(r.length===0||s)return;const S=x.metaKey||x.ctrlKey;if(S&&x.key>="1"&&x.key<="5"){const h=parseInt(x.key)-1;h<r.length&&(x.preventDefault(),c(h));return}if(S&&(x.key==="ArrowLeft"||x.key==="ArrowRight")){x.preventDefault(),c(h=>x.key==="ArrowLeft"?h>0?h-1:r.length-1:h<r.length-1?h+1:0);return}if(S&&x.key==="w"){x.preventDefault(),w(i);return}S&&x.key==="l"&&(x.preventDefault(),k())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,s,i,w,k]);const b=ee(()=>new Set(r.map(G)),[r]);return{openTabs:r,activeTabIndex:i,setActiveTabIndex:c,showList:s,openTab:y,closeTab:w,closeTabByKey:m,goToList:k,openTabKeys:b}}function Fs({spaces:e,accounts:n,projects:a}){const[r,o]=v(null),[i,c]=v(null),[s,d]=v(null),[f,g]=v(null),[y,m]=v(!1),w=ee(()=>Array.from(new Set(e.map(S=>S.harness??"claude"))).sort(),[e]),k=ee(()=>{if(n.length>0)return n;const S=new Set;for(const h of e)h.account&&S.add(h.account);return Array.from(S).sort()},[n,e]),b=ee(()=>{const S=new Set;for(const h of e)r&&h.account!==r||se(h)&&S.add(h.project);for(const[h,C]of Object.entries(a))r&&C.account!==r||S.add(h);return Array.from(S).sort()},[e,a,r]),p=S=>{if(o(S),S&&i){const h=a[i];h&&h.account!==S&&c(null)}},x=ee(()=>e.filter(S=>!(r&&S.account!==r||i&&S.project!==i||f&&(S.harness??"claude")!==f||s&&S.type!==mo(s)||!y&&S.status==="done")),[e,r,i,s,f,y]);return{filterAccount:r,setFilterAccount:p,filterProject:i,setFilterProject:c,filterType:s,setFilterType:d,filterHarness:f,setFilterHarness:g,showDone:y,setShowDone:m,accountNames:k,projectNames:b,harnessNames:w,filteredSpaces:x}}function Bs(){const[e,n]=v([]),[a,r]=v({}),[o,i]=v([]),[c,s]=v(!0),[d,f]=v("list"),[g,y]=v(!1),[m,w]=v(null),[k,b]=v(!1);M(()=>{ye(),yr(),fetch("/api/liveframe/frames").then($=>$.json()).then($=>w($.length)).catch(()=>{})},[]);const p=J(async()=>{try{const[$,W,K]=await Promise.all([fetch("/api/cw/spaces"),fetch("/api/cw/projects"),fetch("/api/cw/accounts")]);n(await $.json()),r(await W.json()),i(await K.json()),ul()}catch{j("Failed to connect to server","error")}finally{s(!1)}},[]),x=J(()=>{setTimeout(p,500),setTimeout(p,2500)},[p]);M(()=>{p()},[p]);const S=Ms({spaces:e,loading:c,onFetchData:p}),h=Fs({spaces:e,accounts:o,projects:a}),C=Object.keys(a).length>0,u=$=>{const W=Xe.find(K=>K.key===$);W&&(Ye.value=W.key),y(!0)},[z,L]=v(null),N=J(async($,W)=>{try{const V=await(await fetch("/api/cw/done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:$.project,task:$.type==="review"?$.pr:$.task,type:$.type,sessionDir:$.sessionDir})})).json();if(V.ok)j("Task closed","info"),W==null||W(),x();else{const ae=V.error??"cw --done failed";console.error(`[forge] closing ${$.project}/${$.task??$.pr} failed:
27
+ `))>=0;){const g=o.slice(0,f);o=o.slice(f+2);const y=(i=/^event: (.*)$/m.exec(g))==null?void 0:i[1],m=JSON.parse(((c=/^data: (.*)$/m.exec(g))==null?void 0:c[1])??"null");if(y==="output"&&m.chunk&&n(m.chunk),y==="done")return m.result;if(y==="error")throw new Xt(m.code??"module_error",m.message??"action failed")}}throw new Xt("module_error","the action stream ended early")}function ms(e,n,a){const r=Y({}),o=async()=>{const c=await fetch(`${Ut(e)}/settings`);c.ok&&(r.value=await c.json())};o();const i=async(c,s,d,f)=>{const g=`${Ut(e)}/actions/${encodeURIComponent(c)}${f?"/stream":""}`,y=await Na(g,{input:s,token:d});return y.status===409?{needsConfirmation:!0}:y.ok?f?{result:await xs(y,f)}:{result:(await y.json()).result}:An(y)};return{settings:r,status:Ba(()=>ke.value.find(c=>c.id===e)),openSettings:a,reloadSettings:o,async route(c,s){const d=await fetch(`${Ut(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():An(d)},async action(c,s,d){var k,b,p;if(((p=(b=(k=ke.value.find(x=>x.id===e))==null?void 0:k.actions)==null?void 0:b.find(x=>x.id===c))==null?void 0:p.effect)!=="external"){const x=await i(c,s,void 0,d==null?void 0:d.onOutput);if(!("needsConfirmation"in x))return x.result}const g=await Na(`${Ut(e)}/actions/${encodeURIComponent(c)}/prepare`,{input:s});if(!g.ok)return An(g);const{confirmation:y,token:m}=await g.json();if(!await fs(y,n()))return;const w=await i(c,s,m,d==null?void 0:d.onOutput);if("needsConfirmation"in w)throw new Xt("confirmation_required","The confirmation expired; try again");return w.result}}}const na=({value:e,onChange:n,initialPath:a,requireGit:r=!0})=>{const[o,i]=v(a??"~"),[c,s]=v(o),[d,f]=v([]),[g,y]=v(null),[m,w]=v(null),[k,b]=v(""),[p,x]=v(!1),[S,h]=v(!1),[C,u]=v(null);D(()=>{let A=!1;return(async()=>{h(!0),u(null);try{const q=await(await fetch(`/api/cw/browse-dirs?path=${encodeURIComponent(o)}`)).json();if(A)return;if(!q.ok){u(q.error??"Failed to load directory"),f([]);return}f(q.entries??[]),y(q.parent??null),w(q.home??null),b(q.path??o),x(!!q.isGitRepo)}catch{A||(u("Network error"),f([]))}finally{A||h(!1)}})(),()=>{A=!0}},[o]);const z=A=>{i(A),s(A)},L=e===k,N=r&&!p,O=k?m&&k===m?"~":m&&k.startsWith(m+"/")?"~"+k.slice(m.length):k:o,T={width:"24px",height:"24px",borderRadius:"7px",border:0,background:"var(--card)",color:"var(--ink-2)",boxShadow:"var(--shadow-s)"},P="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev disabled:cursor-not-allowed disabled:opacity-60",R={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:Q("--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:T,onClick:()=>g&&z(g),disabled:!g||S,title:"Parent folder","aria-label":"Parent folder",children:"←"}),t("button",{type:"button",class:"grid place-items-center cursor-pointer",style:T,onClick:()=>z("~"),title:"Home","aria-label":"Home",children:"~"}),t("input",{type:"text",value:c,"aria-label":"Path",onInput:A=>s(A.target.value),onBlur:()=>i(c),onKeyDown:A=>{A.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:Q("--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:S?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--ink-2)"},children:"Loading…"}):C?t("p",{style:{padding:"12px",fontSize:"12.5px",color:"var(--red)"},children:C}):l(H,{children:[l("button",{type:"button",class:P,style:{...R,background:L?"var(--elev)":"none",fontWeight:600},onClick:()=>n(k,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(A=>l("button",{type:"button",class:P,style:R,onClick:()=>z(A.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:A.name}),A.isGitRepo&&t("span",{style:B,children:"git"})]},A.path))]})})]})},to={fontSize:"11.5px",color:"var(--red)"},Oa=e=>e.type==="boolean"||e.type==="string"&&e.format==="path",Wa=({def:e,value:n,projects:a,onChange:r})=>e.type==="boolean"?t(cn,{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(na,{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))}),Da=({def:e,error:n,plain:a,children:r})=>l(U,{plain:a,label:l(H,{children:[e.label??"",e.required?" *":""]}),children:[r,e.help&&t("span",{style:ve,children:e.help}),n&&t("span",{style:to,children:n})]}),vs=({moduleId:e,displayName:n,schema:a,onClose:r,onSaved:o})=>{const[i,c]=v(null),[s,d]=v({}),[f,g]=v([]),[y,m]=v(!1),w=`/api/modules/${encodeURIComponent(e)}/settings`;D(()=>{fetch(w).then(x=>x.json()).then(c).catch(()=>c({})),fetch("/api/cw/projects").then(x=>x.json()).then(x=>g(Object.keys(x))).catch(()=>{})},[w]);const k=(x,S)=>c(h=>({...h,[x]:S})),b=(x,S,h,C)=>c(u=>{const z=[...(u==null?void 0:u[x])??[]];return z[S]={...z[S],[h]:C},{...u,[x]:z}}),p=async()=>{m(!0);try{const x=await fetch(w,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(x.status===400){const{errors:S}=await x.json();d(Object.fromEntries(S.map(h=>[h.path,h.message])));return}if(!x.ok)throw new Error(`Saving failed (${x.status})`);d({}),j(`${n} settings saved`,"success"),o(),r()}catch(x){j(le(x),"error")}finally{m(!1)}};return t(Ze,{title:`${n} settings`,onClose:r,children:i?l("div",{class:"flex flex-col",style:{gap:"14px"},children:[Object.entries(a).map(([x,S])=>{if(S.type!=="list")return t(Da,{def:{...S,label:S.label??x},error:s[x],plain:Oa(S),children:t(Wa,{def:S,value:i[x],projects:f,onChange:C=>k(x,C)})},x);const h=i[x]??[];return l("div",{class:"flex flex-col",style:{gap:"10px"},children:[t("span",{style:{...ve,fontWeight:600},children:S.label??x}),S.help&&t("span",{style:ve,children:S.help}),s[x]&&t("span",{style:to,children:s[x]}),h.map((C,u)=>l("div",{class:"flex flex-col",style:{gap:"10px",padding:"12px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},children:[Object.entries(S.item).map(([z,L])=>t(Da,{def:{...L,label:L.label??z},error:s[`${x}[${u}].${z}`],plain:Oa(L),children:t(Wa,{def:L,value:C[z],projects:f,onChange:N=>b(x,u,z,N)})},z)),t("div",{children:t(I,{label:"Remove",variant:"danger",size:"sm",onClick:()=>c(z=>({...z,[x]:h.filter((L,N)=>N!==u)}))})})]},u)),t("div",{children:t(I,{label:`Add ${(S.label??x).replace(/s$/,"").toLowerCase()}`,icon:"i-lucide-plus",variant:"secondary",size:"sm",onClick:()=>k(x,[...h,{}])})})]},x)}),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:y,onClick:p})]})]}):t("div",{class:"text-ink2",style:{fontSize:"13px"},children:"Loading…"})})};class ys extends oo{constructor(){super(...arguments);ga(this,"state",{error:null})}componentDidCatch(a){this.setState({error:a})}render(){const{error:a}=this.state;return a?t(aa,{title:`${this.props.name}'s view crashed`,message:a.message,onReload:()=>{this.setState({error:null}),this.props.onReload()}}):this.props.children}}const aa=({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})})]}),bs=({status:e,onClose:n,onRemoved:a})=>{const[r,o]=v(!1),i=async()=>{o(!0);try{ke.value=await jt("DELETE",`/api/modules/${encodeURIComponent(e.id)}`),j(`Removed ${e.displayName}`,"success"),a()}catch(c){j(le(c),"error"),o(!1)}};return t(Re,{open:!0,title:`Remove ${e.displayName}?`,onClose:n,footer:l(H,{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."]})})},In=new Map;function ks(e){const n=`${e.view.url}?v=${encodeURIComponent(e.view.version)}`;let a=In.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(()=>In.delete(n)),In.set(n,a)),a}const ws=({moduleId:e,cwProject:n,onBack:a})=>{var u,z,L,N;const r=ke.value.find(O=>O.id===e),[o,i]=v(!1),[c,s]=v(!1),[d,f]=v(null),[g,y]=v(0),m=ie(e);r&&(m.current=r.displayName);const w=m.current,k=ee(()=>ms(e,()=>m.current,()=>i(!0)),[e]),b=(r==null?void 0:r.state)==="enabled"?(u=r.view)==null?void 0:u.version:void 0,p=((z=pr.value[e])==null?void 0:z.attention)??0;D(()=>{p>0&&qo(e)},[e,p]),D(()=>{if(!r||!b)return;let O=!0;return ks(r).then(T=>{O&&f({version:b,config:T})},T=>{O&&f({version:b,error:T.message})}),()=>{O=!1}},[e,b,g]);const x=r?dr(r):null,S=l(et,{title:((L=r==null?void 0:r.view)==null?void 0:L.title)??w,subtitle:r?`${r.name} ${r.version}`:void 0,children:[x&&l("span",{class:"mono truncate",title:x,style:{maxWidth:"320px",fontSize:"11.5px",color:"var(--orange)"},children:["⚠ ",x]}),(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(bs,{status:r,onClose:()=>s(!1),onRemoved:a})]});if(!r)return l("div",{children:[S,t("div",{style:{padding:"56px 22px"},children:t(Oe,{icon:"i-lucide-package-x",title:`${w} was removed`,description:"The module is no longer installed.",action:{label:"Back to Tasks",onClick:a}})})]});if(r.state!=="enabled")return l("div",{children:[S,t(aa,{title:`${w} is disabled`,message:r.reason??"No reason given",onReload:()=>{vt()}})]});const h=d&&d.version===b?d:null,C=(N=h==null?void 0:h.config)==null?void 0:N.component;return l("div",{children:[S,h!=null&&h.error?t(aa,{title:`${w}'s view did not load`,message:h.error,onReload:()=>y(O=>O+1)}):C?t(ys,{name:w,onReload:()=>y(O=>O+1),children:t(C,{moduleId:e,projectId:null,cwProject:n,forge:k})},`${b}-${g}`):l("div",{class:"py-20 text-center text-ink2",children:["Loading ",w,"…"]}),o&&r.settingsSchema&&t(vs,{moduleId:e,displayName:w,schema:r.settingsSchema,onClose:()=>i(!1),onSaved:()=>{k.reloadSettings(),vt()}})]})},Ln={padding:"12px 14px",borderRadius:"12px",background:"var(--card)",border:"1px solid var(--hair)"},Ss=({onClose:e,onInstalled:n})=>{const[a,r]=v(""),[o,i]=v(null),[c,s]=v(null),[d,f]=v(null),g=async()=>{f("preview"),s(null);try{i(await ce("/api/modules/install/preview",{spec:a}))}catch(m){s(le(m))}finally{f(null)}},y=async()=>{if(o){f("install"),s(null);try{const{status:m,modules:w}=await ce("/api/modules/install",{token:o.token});ke.value=w,(m==null?void 0:m.state)==="disabled"?j(`Installed ${o.displayName}, but Forge disabled it: ${m.reason??""}`,"error"):j(`Installed ${o.displayName}`,"success"),m&&n(m),e()}catch(m){i(null),s(le(m))}finally{f(null)}}};return l(Ze,{title:"Add a module",onClose:e,children:[l("form",{class:"flex flex-col",style:{gap:"10px"},onSubmit:m=>{m.preventDefault(),a.trim()&&!d&&g()},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:ve,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:{...Ln,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:Ln,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:{...ve,fontWeight:600},children:o.permissions.length?"It asks for":"It asks for no permissions"}),o.permissions.map((m,w)=>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})]},w))]}),t("p",{style:{...Ln,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:y}):t(I,{label:"Review",loading:d==="preview",disabled:!a.trim(),onClick:g})]})]})},Cs=({open:e,accounts:n,onClose:a,onCreated:r})=>{const[o,i]=v("create"),[c,s]=v(""),[d,f]=v(""),[g,y]=v(""),[m,w]=v(""),[k,b]=v(""),[p,x]=v(""),[S,h]=v(!1),[C,u]=v(""),[z,L]=v(!1);D(()=>{e&&n.length>0&&!c&&s(n[0])},[e,n]),D(()=>{e||(i("create"),f(""),y(""),w(""),b(""),x(""),h(!1),u(""),L(!1))},[e]);const N=c.trim().length>0&&d.trim().length>0&&m.trim().length>0,O=c.trim().length>0&&p.length>0&&S,T=async()=>{if(N){L(!0);try{const F=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:g.trim()||void 0,model:k||void 0})})).json();F.ok?(j("Project creation started in terminal","success"),r(F.session)):j(F.error??"Failed to create project","error")}catch{j("Failed to create project","error")}finally{L(!1)}}},P=async()=>{if(O){L(!0);try{const F=await(await fetch("/api/cw/register-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p,account:c.trim(),alias:C.trim()||void 0})})).json();F.ok?(j(`Project "${F.project}" registered`,"success"),r()):j(F.error??"Failed to register project","error")}catch{j("Failed to register project","error")}finally{L(!1)}}},R=o==="create";return t(Re,{open:e,title:"Add a project",onClose:a,footer:l(H,{children:[t("span",{class:"mono flex-1 truncate",style:{fontSize:"11.5px",color:"var(--ink-3)"},children:R?"cw create":"cw project register"}),t(I,{label:"Cancel",variant:"secondary",onClick:a}),t(I,{label:R?z?"Creating…":"Create":z?"Registering…":"Register",variant:"primary",loading:z,disabled:!(R?N:O),onClick:R?T:P})]}),children:l("div",{class:"flex flex-col",style:{gap:"13px"},children:[t(de,{fill:!0,label:"Mode",tabs:[{id:"create",label:"Create new"},{id:"existing",label:"Register existing"}],active:o,onChange:M=>i(M)}),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:M=>s(M.target.value),children:n.map(M=>t("option",{value:M,children:M},M))}):t("input",{type:"text",class:"field",value:c,placeholder:"account-name",onInput:M=>s(M.target.value)})}),R?t(U,{label:"Project name",children:t("input",{type:"text",class:"field",value:d,placeholder:"my-new-project",onInput:M=>f(M.target.value)})}):t(U,{label:"Alias",children:t("input",{type:"text",class:"field",value:C,placeholder:"defaults to folder name",onInput:M=>u(M.target.value)})})]}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:ve,children:R?"Parent folder · optional":"Repository · must contain .git"}),R?t(na,{value:g,onChange:y,requireGit:!1},"dir-create"):t(na,{value:p,onChange:(M,F)=>{x(M),h(F)}},"dir-existing")]}),R&&l(H,{children:[t(U,{label:"Description",children:t("textarea",{rows:2,class:"field",value:m,placeholder:"A SaaS platform for…",onInput:M=>w(M.target.value)})}),l("div",{class:"flex flex-col",style:{gap:"5px"},children:[t("span",{style:ve,children:"Model"}),t(de,{size:"sm",label:"Model",tabs:[{id:"",label:"Auto"},{id:"haiku",label:"Haiku"},{id:"sonnet",label:"Sonnet"},{id:"opus",label:"Opus"}],active:k,onChange:b})]})]})]})})},$s=(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"}},zs=(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(" · ")},_e=({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?Q(e):"var(--elev)",color:e?`var(${e})`:"var(--ink-3)"},children:[t("span",{style:{width:"6px",height:"6px",borderRadius:"50%",background:"currentColor"}}),n]}),Rs=({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(_e,{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(_e,{token:null,label:"Not installed"});case"error":return t(_e,{token:"--red",label:"Error"});case"local":return t(_e,{token:"--orange",label:"Local"});case"api_key":return t(_e,{token:"--green",label:"API key"});case"connected":return t(_e,{token:"--green",label:"Connected"});case"connect":return t(I,{label:"Connect",size:"sm",onClick:n})}},En=({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})]}),Nn=({warn:e,children:n})=>t("span",{style:{fontSize:"11.5px",color:e?"var(--orange)":"var(--ink-3)"},children:n}),Ts=({account:e,harness:n})=>{const a=Eo(e,n);return!a||a.state==="not_connected"?null:a.state==="expired"?t(En,{children:t(Nn,{warn:!0,children:"Reconnect to see usage limits"})}):a.state==="error"?t(En,{children:l(Nn,{children:["Limits unavailable — ",a.detail??"the request failed"]})}):a.windows.length===0?null:l(En,{children:[t(_a,{bars:Ja(a.windows)}),a.stale&&l(Nn,{children:["Last known values — ",a.detail??"the refresh failed"]})]})},js=3e3,Ps=({account:e,harness:n,canUseApiKey:a,onConnected:r,onClose:o})=>{const[i,c]=v(null),[s,d]=v(!1),[f,g]=v(0),[y,m]=v(""),[w,k]=v(!1),b=ge(n).label,p=`/api/cw/accounts/${encodeURIComponent(e)}`,x=`${p}/login/${encodeURIComponent(n)}`,S=ie(!1),h=ie(!1);D(()=>{let L=!1,N=null;c(null),d(!1),S.current=!1,h.current=!1;const O=()=>{S.current||(S.current=!0,fetch(x,{method:"DELETE"}).catch(()=>{}),j(`${e} is connected to ${b}`,"success"),r())},T=async()=>{var M;const R=await fetch(x).catch(()=>null);if(!(R!=null&&R.ok)||L)return;const{login:B}=await R.json();if(c(B),B.status!=="exited"||(h.current=!0,N&&(clearInterval(N),N=null),B.exitCode!==0))return;d(!0);const A=await ye(!0);L||(A.available&&((M=We(A.doctor,e,n))==null?void 0:M.status)==="connected"?O():d(!1))};fetch(`${p}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n})}).then(R=>R.json()).then(R=>{if(!L){if(!R.ok||!R.login){j(R.error??"Could not start the login","error");return}c(R.login),N=setInterval(T,js)}}).catch(()=>j("Could not start the login","error"));const P=tl(R=>{var B;return((B=We(R,e,n))==null?void 0:B.status)==="connected"},{onDone:R=>{R&&O()}});return()=>{L=!0,N&&clearInterval(N),P(),h.current||fetch(x,{method:"DELETE"}).catch(()=>{})}},[e,n,f]);const C=()=>{fetch(x,{method:"DELETE"}).catch(()=>{}),o()},u=async()=>{const L=y.trim();if(L){k(!0);try{const O=await(await fetch(`${p}/api-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({harness:n,apiKey:L})})).json();O.ok?(m(""),j("API key saved","success"),ye(!0)):j(O.error??"Could not save the API key","error")}catch{j("Could not save the API key","error")}finally{k(!1)}}},z=(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 ",b]}),t("span",{class:"flex-1"}),t(I,{label:"Cancel",variant:"secondary",size:"sm",onClick:C})]}),!i&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Starting the login…"}),i&&!z&&l(H,{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(H,{children:[t("span",{class:"mono",style:{fontSize:"19px",fontWeight:650,letterSpacing:".12em"},children:i.code}),t(I,{label:"Copy",variant:"secondary",size:"sm",onClick:()=>un(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…"})]}),z&&s&&t("p",{style:{fontSize:"12.5px",color:"var(--ink-2)"},children:"Checking the connection…"}),z&&!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:()=>g(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:y,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:w,disabled:!y.trim(),onClick:u})]}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)"},children:"Sent to cw over stdin. Forge never stores or shows it."})]})]})},Ht={display:"block",fontSize:"12px",color:"var(--ink-2)",marginBottom:"5px"},As=({response:e,onCancel:n,onCreated:a})=>{const[r,o]=v(""),[i,c]=v(""),[s,d]=v(""),[f,g]=v(""),[y,m]=v(!1),w=Tt(),k=r.trim(),b=ko.test(k),p=e!=null&&e.available?e.doctor.harnesses.map(h=>h.name).filter(h=>h!=="claude"):[],x=!!i&&qe(e,i,"custom_provider"),S=async()=>{if(!(!b||y)){m(!0);try{const C=await(await fetch("/api/cw/accounts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:k,harness:i||void 0,provider:x&&s.trim()||void 0,model:x&&f.trim()||void 0})})).json();C.ok?(j(`Account "${k}" created`,"success"),a()):j(C.error??"Failed to create account","error")}catch{j("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:Ht,for:"new-account-name",children:"Account name"}),t("input",{id:"new-account-name",type:"text",value:r,onInput:h=>o(h.target.value),onKeyDown:h=>{h.key==="Enter"&&S()},placeholder:"my-account",class:"field",ref:w}),k&&!b&&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:Ht,children:"Default harness"}),t(de,{label:"Default harness",tabs:[{id:"",label:"Claude Code"},...p.map(h=>({id:h,label:ge(h).label}))],active:i,onChange:c}),t("p",{style:{fontSize:"12px",color:"var(--ink-3)",marginTop:"5px"},children:"The default harness cannot be changed later."})]}),x&&l("div",{class:"grid",style:{gridTemplateColumns:"1fr 1fr",gap:"10px",maxWidth:"520px"},children:[l("div",{children:[t("label",{style:Ht,children:"Provider · optional"}),t("input",{type:"text",value:s,onInput:h=>d(h.target.value),placeholder:"zai, ollama, openrouter",class:"field"})]}),l("div",{children:[t("label",{style:Ht,children:"Model · optional"}),t("input",{type:"text",value:f,onInput:h=>g(h.target.value),placeholder:"glm-5.1",class:"field"})]})]}),l("div",{class:"flex",style:{gap:"8px"},children:[t(I,{label:y?"Creating…":"Add account",variant:"primary",loading:y,disabled:!b,onClick:S}),t(I,{label:"Cancel",variant:"secondary",onClick:n})]})]})},Is=new Set(["localhost","127.0.0.1","::1","[::1]"]),Ma={...Ee,overflow:"hidden"},Ls=({account:e,onRemoved:n})=>{const[a,r]=v(!1),o=async()=>{try{const c=await(await fetch(`/api/cw/accounts/${encodeURIComponent(e)}`,{method:"DELETE"})).json();c.ok?(j(`Account "${e}" removed`,"info"),n()):j(c.error??"Failed to remove account","error")}catch{j("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)})},Es=({projects:e,onOpenSession:n,onAccountsChanged:a})=>{const[r,o]=v(null),[i,c]=v(!1);D(()=>{ye()},[]),D(()=>rr(),[]);const s=pn.value,d=!Is.has(window.location.hostname),f=s!=null&&s.available?s.doctor:null,g=()=>{r&&(fetch(`/api/cw/accounts/${encodeURIComponent(r.account)}/login/${encodeURIComponent(r.harness)}`,{method:"DELETE"}).catch(()=>{}),o(null))},y=async(p,x)=>{if(qe(s,x,"headless_login")){o({account:p,harness:x});return}try{const h=await(await fetch("/api/cw/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"login",account:p,harness:x})})).json();h.ok&&h.session?n(h.session):j(h.error??"Could not open the login","error")}catch{j("Could not open the login","error")}},m=f?f.accounts.reduce((p,x)=>p+x.harnesses.filter(S=>S.status==="not_logged_in").length,0):0,w=f?`${f.accounts.length} account${f.accounts.length===1?"":"s"} · ${f.harnesses.length} harnesses · ${m} need${m===1?"s":""} connecting`:"Reading cw doctor…",k=p=>Object.values(e).filter(x=>x.account===p).length,b=(p,x)=>{if(!f)return null;const[S,h]=Ha(x),C=k(p.name),u=We(f,p.name,p.default_harness),z=[ge(p.default_harness).label,u&&u.provider!=="native"?u.provider:null].filter(Boolean).join(" · ");return l("section",{style:{...Ma,animation:`riseIn .36s var(--ease) ${x*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(${S}), var(${h}))`,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 ",z," · ",C," project",C===1?"":"s"]}),t("span",{class:"flex-1"}),t(Ls,{account:p.name,onRemoved:()=>{ye(!0),a()}})]}),f.harnesses.map(L=>{const N=We(f,p.name,L.name),O=(r==null?void 0:r.account)===p.name&&r.harness===L.name,T=ge(L.name),P=N?$s(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:T.color}}),T.label]}),t("span",{class:"flex-1",style:{minWidth:"140px",fontSize:"12.5px",color:"var(--ink-2)"},children:N&&P?zs(P,L.version,qe(s,L.name,"headless_login"),N):"Not configured for this account"}),P&&t(Rs,{view:P,onConnect:()=>{y(p.name,L.name)},onCancel:g})]}),N&&t(Ts,{account:p.name,harness:L.name}),O&&t("div",{style:{padding:"0 15px 13px"},children:t(Ps,{account:p.name,harness:L.name,canUseApiKey:qe(s,L.name,"api_key_login"),onConnected:()=>o(null),onClose:()=>o(null)},`${p.name}::${L.name}`)})]},L.name)})]},p.name)};return l(H,{children:[l(et,{title:"Accounts",subtitle:w,children:[t(I,{label:"Refresh",variant:"secondary",onClick:()=>{ye(!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),ye(!0),a()}}),s&&!s.available&&l("section",{style:{...Ma,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:()=>{ye(!0)}})]}),f&&d&&t("p",{style:{...oe,background:Q("--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."}),f&&f.issues.map(p=>t("p",{style:{...oe,background:Q("--red"),color:"var(--ink)"},children:p.message},p.code)),f&&f.warnings.map(p=>t("p",{style:{...oe,background:"var(--elev)",color:"var(--ink-2)"},children:p.message},p.code)),f==null?void 0:f.accounts.map(b)]})]})},Fa="flex items-center w-full text-left cursor-pointer transition-colors duration-140 hover:bg-elev",Ns=({sessions:e,openTabKeys:n,onOpenSession:a,onNewTask:r,onClose:o,position:i})=>{const c=ie(null);D(()=>{const d=g=>{c.current&&!c.current.contains(g.target)&&o()},f=g=>{g.key==="Escape"&&o()};return document.addEventListener("mousedown",d),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",f)}},[o]);const s=e.filter(d=>!n.has(G(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"}),Xe.map(d=>l("button",{type:"button",class:Fa,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{r(d.key),o()},children:[t(Gn,{type:d.sessionType,size:22,radius:7,font:10}),t("span",{class:"flex-1",children:oa(d.key)})]},d.key)),s.length>0&&l(H,{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:Fa,style:{gap:"10px",padding:"7px 10px",borderRadius:"10px",border:0,background:"none",color:"var(--ink)",fontSize:"13px"},onClick:()=>{a(d),o()},children:[t(Gn,{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:se(d)})]},G(d)))]})]})},Os=({tabs:e,activeIndex:n,onActivate:a,onClose:r,onBack:o,allSessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d})=>{const[f,g]=v(!1),y=ie(null),[m,w]=v({top:0,left:0}),k=J(()=>g(!1),[]),b=()=>{if(!f&&y.current){const p=y.current.getBoundingClientRect();w({top:p.bottom+6,left:Math.max(8,Math.min(p.left,window.innerWidth-328))})}g(!f)};return l(H,{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(ha,{}),t(Rl,{onClick:o}),e.map((p,x)=>{const S=x===n,h=Ie.value[G(p)],C=!S&&Je(h);return l("div",{role:"tab",tabIndex:0,"aria-selected":S,title:[C?en(h):null,x<5?`⌘${x+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:S?"var(--card)":"transparent",border:`1px solid ${S?"var(--hair)":"transparent"}`,boxShadow:S?"var(--shadow-s)":"none"},onClick:()=>a(x),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),a(x))},children:[t(ze,{size:6,live:p.status==="active",color:C?`var(${qt(h)})`:void 0}),t("span",{style:{fontWeight:600,color:S?"var(--ink)":"var(--ink-2)"},children:ue(p)}),t("span",{class:"mono truncate",style:{fontSize:"11px",color:"var(--ink-3)",maxWidth:"110px"},children:se(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:u=>{u.stopPropagation(),r(x)},title:"Close tab (⌘W)","aria-label":`Close ${ue(p)}`,children:t("span",{class:"i-lucide-x",style:{width:"13px",height:"13px"}})})]},G(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:b,"aria-expanded":f,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"}})})]}),f&&t(Ns,{sessions:i,openTabKeys:c,onOpenSession:s,onNewTask:d,onClose:k,position:m})]})};function Ws(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?kt(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(Re,{open:!0,title:"Close this task?",onClose:n,footer:l(H,{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:Ws(c,e.state)},c))}),e.error&&t("p",{style:{marginTop:"10px",fontSize:"12.5px",color:"var(--ink-2)"},children:e.error})]})},On="forge-open-tabs";function Ms({spaces:e,loading:n,onFetchData:a}){const[r,o]=v([]),[i,c]=v(0),[s,d]=v(!0),f=ie(!1),g=ie(r);g.current=r,D(()=>{if(!(n||e.length===0||f.current)){f.current=!0;try{const p=sessionStorage.getItem(On);if(!p)return;const{keys:x,activeIndex:S}=JSON.parse(p),h=[];for(const C of x){const u=e.find(z=>G(z)===C);u&&h.push(u)}h.length>0&&(o(h),c(Math.min(S,h.length-1)))}catch{}}},[n,e]),D(()=>{if(f.current)if(r.length>0){const p=r.map(G);sessionStorage.setItem(On,JSON.stringify({keys:p,activeIndex:i}))}else sessionStorage.removeItem(On)},[r,i]);const y=J(p=>{const x=G(p),S=r.findIndex(h=>G(h)===x);S>=0?c(S):(o(h=>[...h,p]),c(r.length)),d(!1)},[r]),m=J(async p=>{const x=g.current.find(u=>G(u)===p);if(!x)return;const S=x.sessionDir??(x.type==="review"?`review-pr-${x.pr}`:`task-${x.task}`);try{await fetch("/api/cw/terminal/kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:x.project,sessionDir:S})})}catch{}const h=g.current.findIndex(u=>G(u)===p);if(h<0)return;Io(p);const C=g.current.length-1;o(u=>u.filter(z=>G(z)!==p)),C===0?(d(!0),c(0),a()):c(u=>u>h?u-1:Math.min(u,C-1))},[a]),w=J(p=>{const x=r[p];return x?m(G(x)):Promise.resolve()},[r,m]),k=J(()=>{d(!0),a()},[a]);D(()=>{const p=x=>{if(r.length===0||s)return;const S=x.metaKey||x.ctrlKey;if(S&&x.key>="1"&&x.key<="5"){const h=parseInt(x.key)-1;h<r.length&&(x.preventDefault(),c(h));return}if(S&&(x.key==="ArrowLeft"||x.key==="ArrowRight")){x.preventDefault(),c(h=>x.key==="ArrowLeft"?h>0?h-1:r.length-1:h<r.length-1?h+1:0);return}if(S&&x.key==="w"){x.preventDefault(),w(i);return}S&&x.key==="l"&&(x.preventDefault(),k())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,s,i,w,k]);const b=ee(()=>new Set(r.map(G)),[r]);return{openTabs:r,activeTabIndex:i,setActiveTabIndex:c,showList:s,openTab:y,closeTab:w,closeTabByKey:m,goToList:k,openTabKeys:b}}function Fs({spaces:e,accounts:n,projects:a}){const[r,o]=v(null),[i,c]=v(null),[s,d]=v(null),[f,g]=v(null),[y,m]=v(!1),w=ee(()=>Array.from(new Set(e.map(S=>S.harness??"claude"))).sort(),[e]),k=ee(()=>{if(n.length>0)return n;const S=new Set;for(const h of e)h.account&&S.add(h.account);return Array.from(S).sort()},[n,e]),b=ee(()=>{const S=new Set;for(const h of e)r&&h.account!==r||se(h)&&S.add(h.project);for(const[h,C]of Object.entries(a))r&&C.account!==r||S.add(h);return Array.from(S).sort()},[e,a,r]),p=S=>{if(o(S),S&&i){const h=a[i];h&&h.account!==S&&c(null)}},x=ee(()=>e.filter(S=>!(r&&S.account!==r||i&&S.project!==i||f&&(S.harness??"claude")!==f||s&&S.type!==mo(s)||!y&&S.status==="done")),[e,r,i,s,f,y]);return{filterAccount:r,setFilterAccount:p,filterProject:i,setFilterProject:c,filterType:s,setFilterType:d,filterHarness:f,setFilterHarness:g,showDone:y,setShowDone:m,accountNames:k,projectNames:b,harnessNames:w,filteredSpaces:x}}function Bs(){const[e,n]=v([]),[a,r]=v({}),[o,i]=v([]),[c,s]=v(!0),[d,f]=v("list"),[g,y]=v(!1),[m,w]=v(null),[k,b]=v(!1);D(()=>{ye(),br(),fetch("/api/liveframe/frames").then($=>$.json()).then($=>w($.length)).catch(()=>{})},[]);const p=J(async()=>{try{const[$,W,K]=await Promise.all([fetch("/api/cw/spaces"),fetch("/api/cw/projects"),fetch("/api/cw/accounts")]);n(await $.json()),r(await W.json()),i(await K.json()),ul()}catch{j("Failed to connect to server","error")}finally{s(!1)}},[]),x=J(()=>{setTimeout(p,500),setTimeout(p,2500)},[p]);D(()=>{p()},[p]);const S=Ms({spaces:e,loading:c,onFetchData:p}),h=Fs({spaces:e,accounts:o,projects:a}),C=Object.keys(a).length>0,u=$=>{const W=Xe.find(K=>K.key===$);W&&(Ye.value=W.key),y(!0)},[z,L]=v(null),N=J(async($,W)=>{try{const V=await(await fetch("/api/cw/done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:$.project,task:$.type==="review"?$.pr:$.task,type:$.type,sessionDir:$.sessionDir})})).json();if(V.ok)j("Task closed","info"),W==null||W(),x();else{const ae=V.error??"cw --done failed";console.error(`[forge] closing ${$.project}/${$.task??$.pr} failed:
29
29
  ${ae}`),j(ae.split(`
30
- `)[0],"error")}}catch{j("Failed to close the task","error")}},[x]),O=J(async($,W)=>{const K=await Un($,!0);if(K.state&&K.state.closeWarnings.length===0){await N($,W);return}L({session:$,state:K.state,error:K.error,onClosed:W})},[N]),T=t(Ds,{request:z,onCancel:()=>L(null),onConfirm:async()=>{const $=z;if($)try{await N($.session,$.onClosed)}finally{L(null)}}}),P=J($=>{Te.value=!1,S.showList||S.goToList(),y(!1),f($)},[S.showList,S.goToList]),R=J(()=>P("list"),[P]),B=J(()=>y(!1),[]),A=J($=>{h.setFilterProject(h.filterProject===$?null:$),P(d==="memory"?"memory":"list")},[h.filterProject,h.setFilterProject,P,d]),D=J($=>{h.setFilterProject($),P("memory")},[h.setFilterProject,P]),F=J($=>{Te.value=!1,y(!1),S.openTab($)},[S.openTab]),[q,he]=v(!1),E=J(()=>he(!1),[]),Z=J(()=>he(!0),[]);M(()=>{const $=W=>{const K=W.metaKey||W.ctrlKey,V=W.key.toLowerCase();if(K&&V==="j"){W.preventDefault(),ga();return}if(K&&V==="k"){W.preventDefault(),q?he(!1):Z();return}const ae=W.target;ae!=null&&ae.closest('input, textarea, select, [contenteditable="true"]')||K||W.altKey||q||g||k||(W.key==="/"?(W.preventDefault(),Z()):V==="n"?(W.preventDefault(),y(!0)):V==="p"&&(W.preventDefault(),b(!0)))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[q,g,k,Z]);const te=J(async($,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:$})})).json();X.ok&&X.session?(F(X.session),x(),j(V,"success")):j(X.error??"Failed to start session","error")}catch{j("Failed to start session","error")}},[F,x]),Se=J(($,W)=>{const K=$==="project"&&a[W]?W:void 0;return{account:$==="account"?W:K?a[K].account:o[0]||"default",project:K}},[o,a]),jt=J(($,W,K)=>{const{account:V,project:ae}=Se($,W),X=$==="global"?"~/.claude/skills/":$==="account"?`~/.cw/accounts/${W}/skills/`:`${ae?a[ae].path:"<project>"}/.claude/skills/`,nt=["Use the skill-creator skill to create a new Claude Code skill.","",`The user wants: ${K}`,`Target scope: ${$}${$!=="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(nt,V,ae,"AI skill creation session started")},[a,Se,te]),Ce=J($=>{const{account:W,project:K}=Se($.scope,$.scopeRef);te(`Use the ${$.name} skill.`,W,K,`Session started with ${$.name}`)},[Se,te]),Pt=J(async($,W,K,V)=>{if(!$.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:$.project,task:Yl(W),description:Ql($,W,K),account:V,harness:"claude"})})).json();if(X.ok&&X.session)return F(X.session),x(),j(`Proposing a skill in ${$.project}`,"success"),!0;j(X.error??"Failed to start session","error")}catch{j("Failed to start session","error")}return!1},[F,x]);M(()=>{c||Ya().catch(()=>{})},[c]);const $e=ee(()=>e.filter($=>$.status==="active"),[e]),Be=ee(()=>S.openTabs.filter($=>$.status==="active"&&$.type!=="login").map($=>({key:G($),session:$})),[S.openTabs]),xe=!S.showList&&S.openTabs.length>0;M(()=>{const $=xe?S.openTabs[S.activeTabIndex]:void 0;ya.value=$?G($):null},[xe,S.openTabs,S.activeTabIndex]);const At=ie({openTabs:S.openTabs,spaces:e,openSession:F});At.current={openTabs:S.openTabs,spaces:e,openSession:F},M(()=>Do(($,W)=>{if(document.visibilityState==="visible"&&$===ya.value)return;const{openTabs:K,spaces:V,openSession:ae}=At.current,X=K.find(nt=>G(nt)===$)??V.find(nt=>G(nt)===$);X&&ba(`${ue(X)}: ${Zt(W).toLowerCase()}`,se(X)||X.account,$,()=>ae(X))}),[]),M(()=>_o(),[]);const It=ie(P);It.current=P,M(()=>Ho($=>{var K;const W=((K=ke.value.find(V=>V.id===$.moduleId))==null?void 0:K.displayName)??$.moduleId;ba(`${W}: ${$.title}`,$.body??"",`module:${$.moduleId}:${$.key}`,()=>It.current(`module:${$.moduleId}`))}),[]);const tt=Object.values(Ae.value).filter(Je).length;M(()=>{document.title=tt>0?`(${tt}) Forge Console`:"Forge Console"},[tt]);const ha=ee(()=>{const $=new Map(Object.entries(a).map(([W,K])=>[W,K.account]));for(const W of e)se(W)&&!$.has(W.project)&&$.set(W.project,W.account);return Array.from($,([W,K])=>({name:W,account:K||"unassigned",count:$e.filter(V=>V.project===W).length,live:Be.some(V=>V.session.project===W)}))},[a,e,$e,Be]);M(()=>{h.filterProject&&(Ge.value=h.filterProject)},[h.filterProject]);const Lt=ee(()=>Object.keys(a),[a]),Et=J($=>{h.setFilterProject($),P("list")},[h.setFilterProject,P]),hn=xe?"list":d,fn=ee(()=>[{id:"new-task",label:"New task",hint:"N",glyph:"+",token:"--blue",run:()=>u()},{id:"add-project",label:"Add project",hint:"P",glyph:"P",token:"--green",run:()=>b(!0)},...fr.map($=>({id:$.view,label:$.label,hint:$.view==="list"?"⌘L":"",glyph:$.glyph,token:$.token,run:()=>P($.view)})),...sr(ke.value).map($=>({id:`module:${$.id}`,label:$.displayName,hint:"",glyph:$.displayName.charAt(0).toUpperCase(),token:null,run:()=>P(`module:${$.id}`)})),{id:"add-module",label:"Add a module",hint:"",glyph:"+",token:null,run:()=>{qt.value=!0}},{id:"appearance",label:"Toggle appearance",hint:"⌘J",glyph:"◐",token:null,run:ga}],[P,ke.value]),Nt=t(Qo,{view:hn,counts:{list:$e.length,accounts:h.accountNames.length,prototypes:m},projects:ha,accounts:h.accountNames,selectedProject:h.filterProject,live:Be,onNavigate:P,onSelectProject:A,onAddProject:()=>{Te.value=!1,b(!0)},onOpenLive:F,onSearch:Z}),_=c?t("div",{class:"py-20 text-center text-ink2",children:"Loading…"}):d==="list"&&!C?t("div",{style:{padding:"56px 22px"},children:t(Oe,{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:()=>b(!0)}})}):d==="list"?t(Al,{spaces:h.filteredSpaces,allSpaces:e,projects:a,accountNames:h.accountNames,filterAccount:h.filterAccount,filterProject:h.filterProject,onFilterProject:h.setFilterProject,filterType:h.filterType,onFilterType:h.setFilterType,harnessNames:h.harnessNames,filterHarness:h.filterHarness,onFilterHarness:h.setFilterHarness,showDone:h.showDone,onShowDone:h.setShowDone,openTabKeys:S.openTabKeys,onSelectTask:F,onMarkDone:O,onNewTask:()=>u(),onCreateProject:()=>b(!0),onRefresh:()=>p(),onStarted:$=>{$&&F($),x()}}):d.startsWith("module:")?t(ws,{moduleId:d.slice(7),cwProject:h.filterProject,onBack:R},d):d==="qa"?t(Vi,{projects:a,preferred:h.filterProject??void 0}):d==="memory"?t(hs,{project:h.filterProject,onProject:h.setFilterProject}):d==="prototypes"?t(Ji,{accounts:h.accountNames,onOpenSession:F,onFramesChanged:w}):d==="accounts"?t(Es,{projects:a,onOpenSession:F,onAccountsChanged:()=>{p()}}):t(xi,{accounts:h.accountNames,projects:a,onCreateWithAI:jt,onRunSkill:Ce,onProposeSkill:Pt});return l(ho,{sidebar:Nt,children:[!xe&&_,S.openTabs.length>0&&l("div",{class:"flex flex-col","aria-hidden":!xe,style:xe?{height:"100vh"}:{position:"absolute",top:0,left:0,right:0,height:"100vh",visibility:"hidden",pointerEvents:"none",zIndex:-1},children:[t(Os,{tabs:S.openTabs,activeIndex:S.activeTabIndex,onActivate:S.setActiveTabIndex,onClose:S.closeTab,onBack:R,allSessions:$e,openTabKeys:S.openTabKeys,onOpenSession:F,onNewTask:$=>{R(),u($)}}),t("div",{class:"flex-1 min-h-0 relative",children:S.openTabs.map(($,W)=>{const K=W===S.activeTabIndex,V=K&&xe;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(Dl,{session:$,active:V,onDone:()=>O($,()=>{S.closeTabByKey(G($))}),onOpenMemory:D})},G($))})})]}),g&&t(Ul,{projects:a,accounts:h.accountNames,initialAccount:h.filterAccount??(tn.value||void 0),initialProject:Ge.value||void 0,onClose:B,onCreated:$=>{y(!1),$&&F($),x()},onOpenAccounts:()=>P("accounts")}),q&&t(Zo,{openTabs:S.openTabs,sessions:e,projects:Lt,commands:fn,onOpenSession:F,onSelectProject:Et,onClose:E}),t(Cs,{open:k,accounts:h.accountNames,onClose:()=>b(!1),onCreated:$=>{b(!1),$&&F($),x()}}),T,t(gs,{}),qt.value&&t(Ss,{onClose:()=>{qt.value=!1},onInstalled:$=>{$.view&&P(`module:${$.id}`)}})]})}lo(t(Bs,{}),document.getElementById("app"));
30
+ `)[0],"error")}}catch{j("Failed to close the task","error")}},[x]),O=J(async($,W)=>{const K=await qn($,!0);if(K.state&&K.state.closeWarnings.length===0){await N($,W);return}L({session:$,state:K.state,error:K.error,onClosed:W})},[N]),T=t(Ds,{request:z,onCancel:()=>L(null),onConfirm:async()=>{const $=z;if($)try{await N($.session,$.onClosed)}finally{L(null)}}}),P=J($=>{je.value=!1,S.showList||S.goToList(),y(!1),f($)},[S.showList,S.goToList]),R=J(()=>P("list"),[P]),B=J(()=>y(!1),[]),A=J($=>{h.setFilterProject(h.filterProject===$?null:$),P(d==="memory"?"memory":"list")},[h.filterProject,h.setFilterProject,P,d]),M=J($=>{h.setFilterProject($),P("memory")},[h.setFilterProject,P]),F=J($=>{je.value=!1,y(!1),S.openTab($)},[S.openTab]),[q,he]=v(!1),E=J(()=>he(!1),[]),Z=J(()=>he(!0),[]);D(()=>{const $=W=>{const K=W.metaKey||W.ctrlKey,V=W.key.toLowerCase();if(K&&V==="j"){W.preventDefault(),xa();return}if(K&&V==="k"){W.preventDefault(),q?he(!1):Z();return}const ae=W.target;ae!=null&&ae.closest('input, textarea, select, [contenteditable="true"]')||K||W.altKey||q||g||k||(W.key==="/"?(W.preventDefault(),Z()):V==="n"?(W.preventDefault(),y(!0)):V==="p"&&(W.preventDefault(),b(!0)))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[q,g,k,Z]);const te=J(async($,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:$})})).json();X.ok&&X.session?(F(X.session),x(),j(V,"success")):j(X.error??"Failed to start session","error")}catch{j("Failed to start session","error")}},[F,x]),Se=J(($,W)=>{const K=$==="project"&&a[W]?W:void 0;return{account:$==="account"?W:K?a[K].account:o[0]||"default",project:K}},[o,a]),At=J(($,W,K)=>{const{account:V,project:ae}=Se($,W),X=$==="global"?"~/.claude/skills/":$==="account"?`~/.cw/accounts/${W}/skills/`:`${ae?a[ae].path:"<project>"}/.claude/skills/`,nt=["Use the skill-creator skill to create a new Claude Code skill.","",`The user wants: ${K}`,`Target scope: ${$}${$!=="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(nt,V,ae,"AI skill creation session started")},[a,Se,te]),Ce=J($=>{const{account:W,project:K}=Se($.scope,$.scopeRef);te(`Use the ${$.name} skill.`,W,K,`Session started with ${$.name}`)},[Se,te]),It=J(async($,W,K,V)=>{if(!$.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:$.project,task:Yl(W),description:Ql($,W,K),account:V,harness:"claude"})})).json();if(X.ok&&X.session)return F(X.session),x(),j(`Proposing a skill in ${$.project}`,"success"),!0;j(X.error??"Failed to start session","error")}catch{j("Failed to start session","error")}return!1},[F,x]);D(()=>{c||Qa().catch(()=>{})},[c]);const $e=ee(()=>e.filter($=>$.status==="active"),[e]),Be=ee(()=>S.openTabs.filter($=>$.status==="active"&&$.type!=="login").map($=>({key:G($),session:$})),[S.openTabs]),xe=!S.showList&&S.openTabs.length>0;D(()=>{const $=xe?S.openTabs[S.activeTabIndex]:void 0;ba.value=$?G($):null},[xe,S.openTabs,S.activeTabIndex]);const Lt=ie({openTabs:S.openTabs,spaces:e,openSession:F});Lt.current={openTabs:S.openTabs,spaces:e,openSession:F},D(()=>Do(($,W)=>{if(document.visibilityState==="visible"&&$===ba.value)return;const{openTabs:K,spaces:V,openSession:ae}=Lt.current,X=K.find(nt=>G(nt)===$)??V.find(nt=>G(nt)===$);X&&ka(`${ue(X)}: ${en(W).toLowerCase()}`,se(X)||X.account,$,()=>ae(X))}),[]),D(()=>_o(),[]);const Et=ie(P);Et.current=P,D(()=>Ho($=>{var K;const W=((K=ke.value.find(V=>V.id===$.moduleId))==null?void 0:K.displayName)??$.moduleId;ka(`${W}: ${$.title}`,$.body??"",`module:${$.moduleId}:${$.key}`,()=>Et.current(`module:${$.moduleId}`))}),[]);const tt=Object.values(Ie.value).filter(Je).length;D(()=>{document.title=tt>0?`(${tt}) Forge Console`:"Forge Console"},[tt]);const fa=ee(()=>{const $=new Map(Object.entries(a).map(([W,K])=>[W,K.account]));for(const W of e)se(W)&&!$.has(W.project)&&$.set(W.project,W.account);return Array.from($,([W,K])=>({name:W,account:K||"unassigned",count:$e.filter(V=>V.project===W).length,live:Be.some(V=>V.session.project===W)}))},[a,e,$e,Be]);D(()=>{h.filterProject&&(Ge.value=h.filterProject)},[h.filterProject]);const Nt=ee(()=>Object.keys(a),[a]),Ot=J($=>{h.setFilterProject($),P("list")},[h.setFilterProject,P]),gn=xe?"list":d,xn=ee(()=>[{id:"new-task",label:"New task",hint:"N",glyph:"+",token:"--blue",run:()=>u()},{id:"add-project",label:"Add project",hint:"P",glyph:"P",token:"--green",run:()=>b(!0)},...gr.map($=>({id:$.view,label:$.label,hint:$.view==="list"?"⌘L":"",glyph:$.glyph,token:$.token,run:()=>P($.view)})),...cr(ke.value).map($=>({id:`module:${$.id}`,label:$.displayName,hint:"",glyph:$.displayName.charAt(0).toUpperCase(),token:null,run:()=>P(`module:${$.id}`)})),{id:"add-module",label:"Add a module",hint:"",glyph:"+",token:null,run:()=>{Vt.value=!0}},{id:"appearance",label:"Toggle appearance",hint:"⌘J",glyph:"◐",token:null,run:xa}],[P,ke.value]),Wt=t(Qo,{view:gn,counts:{list:$e.length,accounts:h.accountNames.length,prototypes:m},projects:fa,accounts:h.accountNames,selectedProject:h.filterProject,live:Be,onNavigate:P,onSelectProject:A,onAddProject:()=>{je.value=!1,b(!0)},onOpenLive:F,onSearch:Z}),_=c?t("div",{class:"py-20 text-center text-ink2",children:"Loading…"}):d==="list"&&!C?t("div",{style:{padding:"56px 22px"},children:t(Oe,{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:()=>b(!0)}})}):d==="list"?t(Al,{spaces:h.filteredSpaces,allSpaces:e,projects:a,accountNames:h.accountNames,filterAccount:h.filterAccount,filterProject:h.filterProject,onFilterProject:h.setFilterProject,filterType:h.filterType,onFilterType:h.setFilterType,harnessNames:h.harnessNames,filterHarness:h.filterHarness,onFilterHarness:h.setFilterHarness,showDone:h.showDone,onShowDone:h.setShowDone,openTabKeys:S.openTabKeys,onSelectTask:F,onMarkDone:O,onNewTask:()=>u(),onCreateProject:()=>b(!0),onRefresh:()=>p(),onStarted:$=>{$&&F($),x()}}):d.startsWith("module:")?t(ws,{moduleId:d.slice(7),cwProject:h.filterProject,onBack:R},d):d==="qa"?t(Vi,{projects:a,preferred:h.filterProject??void 0}):d==="memory"?t(hs,{project:h.filterProject,onProject:h.setFilterProject}):d==="prototypes"?t(Ji,{accounts:h.accountNames,onOpenSession:F,onFramesChanged:w}):d==="accounts"?t(Es,{projects:a,onOpenSession:F,onAccountsChanged:()=>{p()}}):t(xi,{accounts:h.accountNames,projects:a,onCreateWithAI:At,onRunSkill:Ce,onProposeSkill:It});return l(ho,{sidebar:Wt,children:[!xe&&_,S.openTabs.length>0&&l("div",{class:"flex flex-col","aria-hidden":!xe,style:xe?{height:"100vh"}:{position:"absolute",top:0,left:0,right:0,height:"100vh",visibility:"hidden",pointerEvents:"none",zIndex:-1},children:[t(Os,{tabs:S.openTabs,activeIndex:S.activeTabIndex,onActivate:S.setActiveTabIndex,onClose:S.closeTab,onBack:R,allSessions:$e,openTabKeys:S.openTabKeys,onOpenSession:F,onNewTask:$=>{R(),u($)}}),t("div",{class:"flex-1 min-h-0 relative",children:S.openTabs.map(($,W)=>{const K=W===S.activeTabIndex,V=K&&xe;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(Dl,{session:$,active:V,onDone:()=>O($,()=>{S.closeTabByKey(G($))}),onOpenMemory:M})},G($))})})]}),g&&t(Ul,{projects:a,accounts:h.accountNames,initialAccount:h.filterAccount??(an.value||void 0),initialProject:Ge.value||void 0,onClose:B,onCreated:$=>{y(!1),$&&F($),x()},onOpenAccounts:()=>P("accounts")}),q&&t(Zo,{openTabs:S.openTabs,sessions:e,projects:Nt,commands:xn,onOpenSession:F,onSelectProject:Ot,onClose:E}),t(Cs,{open:k,accounts:h.accountNames,onClose:()=>b(!1),onCreated:$=>{b(!1),$&&F($),x()}}),T,t(gs,{}),Vt.value&&t(Ss,{onClose:()=>{Vt.value=!1},onInstalled:$=>{$.view&&P(`module:${$.id}`)}})]})}lo(t(Bs,{}),document.getElementById("app"));