herm-tui 1.11.0-dev.2 → 1.11.0-dev.4
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.
- package/index.js +10 -9
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -4098,7 +4098,7 @@ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid2
|
|
|
4098
4098
|
`,nl+1)).trim().startsWith("#")){end=nl;break}}end=nl}mark2(skH,end+1,"skills","Skills Catalog",makeSource("skills","skills/"))}let proj=text3.indexOf("# Project Context");if(proj>=0){let conv2=text3.indexOf("Conversation started:");mark2(proj,conv2>proj?conv2:text3.length,"project","Project Context",makeSource("AGENTS.md"))}let conv=text3.indexOf("Conversation started:");if(conv>=0)mark2(conv,text3.length,"meta","Session Metadata");let start=-1;for(let i=0;i<=text3.length;i++)if(i<text3.length&&!used[i]){if(start<0)start=i}else if(start>=0){let slice=text3.slice(start,i);if(slice.trim().length>0)sections.push({id:"other",label:"Other",chars:slice.length,tokens:count2(slice),text:slice});start=-1}return sections.sort((a,b2)=>text3.indexOf(a.text)-text3.indexOf(b2.text))}function classifyTools(tools){let system=[],mcp=[];for(let t2 of tools)if(t2.name.startsWith("mcp_"))mcp.push(t2);else system.push(t2);return{system,mcp}}function toolTokens(tool){return Math.ceil((tool.descriptionLength+tool.paramsLength)/CPT)}function build(opts){let pct=(t2)=>opts.contextLength>0?t2/opts.contextLength*100:0,result=[],byId2=new Map;for(let s of opts.sections)byId2.set(s.id,s);let promptChildren=opts.sections.filter((sec)=>SYSTEM_PROMPT_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),promptTok=promptChildren.reduce((s,c)=>s+c.tokens,0);if(promptTok>0)result.push({id:"system_prompt",label:"System Prompt",tokens:promptTok,percent:pct(promptTok),children:promptChildren});let{system:sysTools,mcp:mcpTools}=classifyTools(opts.tools),sysToolsTok=sysTools.reduce((s,t2)=>s+toolTokens(t2),0);if(sysToolsTok>0)result.push({id:"system_tools",label:"System Tools",tokens:sysToolsTok,percent:pct(sysToolsTok)});let mcpToolsTok=mcpTools.reduce((s,t2)=>s+toolTokens(t2),0);if(mcpToolsTok>0)result.push({id:"mcp_tools",label:"MCP Tools",tokens:mcpToolsTok,percent:pct(mcpToolsTok)});let memChildren=opts.sections.filter((sec)=>MEMORY_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),memTok=memChildren.reduce((s,c)=>s+c.tokens,0);if(memTok>0)result.push({id:"memory",label:"Memory",tokens:memTok,percent:pct(memTok),children:memChildren});let skillsSec=byId2.get("skills"),skillsTok=skillsSec?.tokens??opts.skillsTokens??0;if(skillsTok>0)result.push({id:"skills",label:"Skills",tokens:skillsTok,percent:pct(skillsTok),section:skillsSec});if(opts.conversationTokens>0){let ct=opts.conversationTokens;result.push({id:"conversation",label:"~Conversation",tokens:ct,percent:pct(ct)})}let taken=result.reduce((s,g)=>s+g.tokens,0),used=opts.usedTokens;if(typeof used!=="number"){let unknown2=Math.max(0,opts.contextLength-taken);if(unknown2>0)result.push({id:"unknown",label:"Unknown (live unavailable)",tokens:unknown2,percent:pct(unknown2)});return result}let unknown=Math.max(0,used-taken);if(unknown>0)result.push({id:"unknown",label:"Unknown / Provider Overhead",tokens:unknown,percent:pct(unknown)});let overage=Math.max(0,taken-used);if(overage>0)result.push({id:"overage",label:"Estimate Overage",tokens:overage,percent:pct(overage)});let free=Math.max(0,opts.contextLength-used);return result.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),result}function drill(group2){if(!group2.children||group2.children.length===0)return[];let total=group2.tokens;return group2.children.map((c)=>({...c,percent:total>0?c.tokens/total*100:0}))}function cells(segments,fallback="free"){let filled=segments.flatMap((seg)=>Array.from({length:Math.round(seg.percent/100*GRID)},()=>({id:seg.id}))),pad=Array.from({length:Math.max(0,GRID-filled.length)},()=>({id:fallback}));return[...filled,...pad].slice(0,GRID)}var import_react59=__toESM(require_react_production(),1);var FileLink=import_react59.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react59.useState(!1);return $jsx("box",{height:1,onMouseDown:()=>openFile(source.file),onMouseOver:()=>setHovered(!0),onMouseOut:()=>setHovered(!1),children:$jsx("text",{fg:theme.info,attributes:hovered?TextAttributes.UNDERLINE:TextAttributes.NONE,children:children2??source.label})})}),KVLink=(props)=>{let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx(FileLink,{source:props.source,children:props.text??props.source.label})})]})};var GOLDEN_ANGLE=137.50776405003785;function luminance(c){return 0.299*c.r+0.587*c.g+0.114*c.b}function rgbaToHsl(c){let{r,g,b:b2}=c,max=Math.max(r,g,b2),min=Math.min(r,g,b2),l=(max+min)/2,d2=max-min;if(d2===0)return[0,0,l];let s=l>0.5?d2/(2-max-min):d2/(max+min),h2;switch(max){case r:h2=(g-b2)/d2+(g<b2?6:0);break;case g:h2=(b2-r)/d2+2;break;default:h2=(r-g)/d2+4}return[h2*60,s,l]}function hslToRgba(h2,s,l){if(h2=(h2%360+360)%360/360,s===0)return RGBA.fromValues(l,l,l,1);let q3=l<0.5?l*(1+s):l+s-l*s,p=2*l-q3,ch=(t2)=>{if(t2<0)t2+=1;if(t2>1)t2-=1;if(t2<0.16666666666666666)return p+(q3-p)*6*t2;if(t2<0.5)return q3;if(t2<0.6666666666666666)return p+(q3-p)*(0.6666666666666666-t2)*6;return p};return RGBA.fromValues(ch(h2+0.3333333333333333),ch(h2),ch(h2-0.3333333333333333),1)}function categorical(seed,bg2,n){let[h0]=rgbaToHsl(seed),dark=luminance(bg2)<0.5,s=dark?0.6:0.7,l=dark?0.62:0.42,out=[];for(let i=0;i<n;i++)out.push(hslToRgba(h0+i*GOLDEN_ANGLE,s,l));return out}var DEFAULT_CTX=128000,COLS2=16,SLOTS2=["system_prompt","system_tools","mcp_tools","memory","skills","conversation","soul","mem0","user","project","meta","other","unknown","overage"],SLOT=Object.fromEntries(SLOTS2.map((id,i)=>[id,i])),REMOTE={tool_definitions:"system_tools",mcp:"mcp_tools",rules:"system_prompt",subagent_definitions:"system_tools"},ORDER2=["system_prompt","system_tools","mcp_tools","memory","skills","conversation"],LABEL2={system_prompt:"System Prompt",system_tools:"System Tools",mcp_tools:"MCP Tools",memory:"Memory",skills:"Skills",conversation:"Conversation"},rampCache=new WeakMap;function ramp2(theme){let r=rampCache.get(theme);if(!r)rampCache.set(theme,r=categorical(theme.primary,theme.background,SLOTS2.length));return r}function clr(id,theme){if(id==="free")return theme.borderSubtle;return ramp2(theme)[SLOT[id]??SLOT.other]}var fmt2=(n)=>{if(n>=1e6)return`${(n/1e6).toFixed(1)}M`;if(n>=1e4)return`${Math.round(n/1000)}k`;if(n>=1000)return`${(n/1000).toFixed(1)}k`;return String(n)},est=(s)=>s?count2(s):0,bar=(pct,w2=20)=>{let f=Math.round(Math.max(0,Math.min(100,pct))/100*w2);return`[${"\u2588".repeat(f)}${"\u2591".repeat(Math.max(0,w2-f))}]`},SectionPanel=import_react60.memo(({seg,theme})=>{let{syntaxStyle}=useTheme(),sec=seg.section;if(!sec)return null;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsxs("text",{children:[sec.chars.toLocaleString()," chars \xB7 ~",fmt2(sec.tokens)," tokens"]}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsx("markdown",{content:sec.text,fg:theme.markdownText,syntaxStyle})]})}),MemoryPanel=import_react60.memo(({seg,theme,label:label2,chars,limit,pct,entries:entries2,source})=>$jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:$jsx("strong",{children:label2})}),source?$jsxs($Fragment,{children:[$jsx("text",{children:" ("}),$jsx(FileLink,{source}),$jsx("text",{children:")"})]}):null]}),$jsxs("text",{children:[chars.toLocaleString()," / ",limit.toLocaleString()," chars (",pct,"%)"]}),$jsxs("text",{children:[bar(pct,25),pct>=95?" \u26A0 near limit":""]}),$jsx("text",{children:" "}),$jsxs("text",{children:[entries2.length," entries:"]}),entries2.map((e,i)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",e]},i))]})),SkillsPanel=import_react60.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line2 of sec.text.split(`
|
|
4099
4099
|
`)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react60.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label2=kind2==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind2==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind2,theme),children:"\u25FC"})," ",label2," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react60.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react60.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),toolsFromInfo=(info)=>{if(!info||info.tools===void 0)return null;let tools=Object.entries(info.tools).flatMap(([group2,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group2.length})));return{source:makeSource("state.db","session.info"),tools}},configuredContextLength=(config)=>{let n=config?.model?.context_length;return typeof n==="number"&&n>0?n:void 0},contextMeter=(usage,info,config)=>({max:usage?.context_max??info?.usage?.context_max??info?.context_max??configuredContextLength(config)??DEFAULT_CTX,used:usage?.context_used??info?.usage?.context_used??info?.context_used}),contextBreakdown=(data2)=>{if(!data2||typeof data2!=="object")return null;let raw=data2,max=Number(raw.context_max),used=Number(raw.context_used);if(!Number.isFinite(max)||max<=0||!Number.isFinite(used)||used<0)return null;if(!Array.isArray(raw.categories))return null;return{categories:raw.categories.flatMap((cat)=>{if(!cat||typeof cat!=="object")return[];let id=typeof cat.id==="string"?cat.id.trim():"",label2=typeof cat.label==="string"?cat.label.trim():"",tokens3=Number(cat.tokens);if(!id||!label2||!Number.isFinite(tokens3)||tokens3<0)return[];return[{id,label:label2,tokens:tokens3,color:typeof cat.color==="string"?cat.color:void 0}]}),context_max:max,context_used:Math.min(used,max),estimated_total:Number.isFinite(Number(raw.estimated_total))?Math.max(0,Number(raw.estimated_total)):0,model:typeof raw.model==="string"?raw.model:void 0}},remoteSegments=(data2,local)=>{let byId2=new Map(local.map((seg)=>[seg.id,seg])),bucket=new Map;for(let cat of data2.categories){let id=REMOTE[cat.id]??cat.id,prev=bucket.get(id);bucket.set(id,{label:byId2.get(id)?.label??prev?.label??cat.label,tokens:(prev?.tokens??0)+cat.tokens})}let pct=(n)=>data2.context_max>0?n/data2.context_max*100:0,segs=[...ORDER2,...bucket.keys().filter((id)=>!ORDER2.includes(id))].flatMap((id)=>{let cat=bucket.get(id);if(!cat||cat.tokens<=0)return[];let seg=byId2.get(id);return[{...seg??{},id,label:seg?.label??LABEL2[id]??cat.label,tokens:cat.tokens,percent:pct(cat.tokens)}]}),taken=segs.reduce((sum,seg)=>sum+seg.tokens,0),unknown=Math.max(0,data2.context_used-taken);if(unknown>0)segs.push({id:"unknown",label:"Unknown / Provider Overhead",tokens:unknown,percent:pct(unknown)});let free=Math.max(0,data2.context_max-data2.context_used);return segs.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),segs},Context=import_react60.memo(({messages=NO_MESSAGES,info,usage,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),[wire,setWire]=import_react60.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react60.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react60.useState(null),[selected,setSelected]=import_react60.useState(null),[drilled,setDrilled]=import_react60.useState(null),[remote2,setRemote]=import_react60.useState(null);import_react60.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let rev=usage?.context_used??info?.usage?.context_used??info?.context_used;import_react60.useEffect(()=>{let sid2=info?.session_id;if(!sid2){setRemote(null);return}let done=!1,timer2=setTimeout(()=>{gw.request("session.context_breakdown",{session_id:sid2}).then((data2)=>{if(!done)setRemote(contextBreakdown(data2))}).catch(()=>{if(!done)setRemote(null)})},300);return()=>{done=!0,clearTimeout(timer2)}},[gw,info?.session_id,info?.usage?.compressions,messages.length,rev]);let localMeter=contextMeter(usage,info,config??null),meter=remote2?{max:remote2.context_max,used:remote2.context_used}:localMeter,ctxLen=meter.max,used=meter.used,reliable=typeof used==="number",output=wire.output,pct=reliable&&ctxLen>0?Math.round(used/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react60.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react60.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react60.useMemo(()=>{let liveTools=toolsFromInfo(info);if(liveTools)return liveTools;if(info?.tools!==void 0)return liveTools;return toolsInfo},[info,toolsInfo]),local=import_react60.useMemo(()=>build({contextLength:ctxLen,usedTokens:used,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,used,sections,convTok,currentTools]),top=import_react60.useMemo(()=>remote2?remoteSegments(remote2,local):local,[remote2,local]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react60.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":reliable?"free":"unknown"),[view,drilledGroup,reliable]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react60.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react60.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react60.useRef(0),segs=view.filter((s)=>s.tokens>0),idx=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key3)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key3,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key3.name==="right")return setSel((p)=>p+1);if(key3.name==="left")return setSel((p)=>p-1);if(key3.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&¤tTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&¤tTools){let{mcp}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):reliable?$jsx("span",{fg:theme.info,children:" (click group to expand)"}):$jsxs("span",{fg:theme.warning,children:[" \xB7 live usage unavailable \xB7 limit ",fmt2(ctxLen)]})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,reliable&&!drilled?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})}):null]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:reliable?"\u2191\u2193 nav \xB7 click a group to drill in":"live usage unavailable \xB7 estimates shown with ~",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:reliable?`Context \xB7 ${fmt2(used)} / ${fmt2(ctxLen)} (${pct}%)`:`Context \xB7 live usage unavailable \xB7 limit ${fmt2(ctxLen)}`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[!drilled&&compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row3)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row3*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=!drilled&&row3*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row3))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react63=__toESM(require_react_production(),1);init_hermes_analytics();var import_react62=__toESM(require_react_production(),1);init_hermes_analytics();var query=(days,opts)=>Promise.resolve(io.analytics(days,opts));function useAnalyticsData(days,tick3,load4=query){let[data2,setData]=import_react62.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react62.useState(()=>cache3.get(days)?.byTool??null),[error,setError]=import_react62.useState(""),gen=import_react62.useRef(0);return import_react62.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null),setError("");let current=++gen.current;return load4(days,{tools:!1}).then((fast)=>{if(gen.current!==current)return;return setData(fast),load4(days).then((full)=>{if(gen.current!==current)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}).catch((err)=>{if(gen.current===current)setError(err instanceof Error?err.message:String(err))}),()=>{gen.current++}},[days,tick3,load4]),{data:data2,tools,error}}var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react63.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost2(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react63.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc5(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react63.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),dims=useTerminalDimensions(),[days,setDays]=import_react63.useState(7),[tick3,setTick]=import_react63.useState(0),{data:data2,tools,error}=useAnalyticsData(days,tick3,props.load),keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(keys.match("list.refresh",key3))return cache3.delete(days),setTick((n)=>n+1);if(key3.raw==="1")return setDays(1);if(key3.raw==="7")return setDays(7);if(key3.raw==="3")return setDays(30);if(key3.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react63.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost2(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:error?$jsx("text",{fg:theme.error,children:error}):$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:error})}):null,$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc5(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost2(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react65=__toESM(require_react_production(),1);import{tmpdir as tmpdir3}from"os";import{join as join10}from"path";import{rm}from"fs/promises";async function editInEditor(renderer,seed,suffix2=".md"){let cmd=process.env.VISUAL||process.env.EDITOR;if(!cmd)return;let path4=join10(tmpdir3(),`herm-${Date.now()}${suffix2}`);await Bun.write(path4,seed);let suspended=!1;try{renderer.suspend(),suspended=!0,renderer.currentRenderBuffer.clear();let argv=process.platform==="win32"?["cmd.exe","/d","/s","/c",`${cmd} "${path4.replaceAll('"','""')}"`]:["/bin/sh","-c",`exec ${cmd} "$1"`,"herm-editor",path4],code=await Bun.spawn(argv,{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(code!==0)throw Error(`editor exited ${code}`);return(await Bun.file(path4).text().catch(()=>"")).trim()||void 0}finally{if(await rm(path4,{force:!0}).catch(()=>{}),suspended&&!renderer.isDestroyed)try{renderer.currentRenderBuffer.clear()}finally{renderer.resume(),renderer.requestRender()}}}function buildJourneyRows(buckets){return buckets.flatMap((bucket,b2)=>[...b2>0?[{kind:"gap"}]:[],{kind:"slice",bucket},...bucket.nodes.map((node,i)=>({kind:"node",bucket,node,last:i===bucket.nodes.length-1}))])}var style=(theme,key3,hex2)=>{if(hex2&&/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(hex2))return RGBA.fromHex(hex2);if(key3==="skill")return theme.primary;if(key3==="memory")return theme.accent;if(key3==="label")return theme.text;if(key3==="dim")return theme.textMuted;if(key3==="bg")return theme.borderSubtle;return theme.textMuted},last2=(data2)=>data2?.frames.at(-1)?.grid??[],latest2=(rows3)=>{let i=[...rows3].reverse().findIndex((r)=>r.kind==="node");return i>=0?rows3.length-1-i:Math.max(0,rows3.length-1)},snap=(rows3,i,dir=1)=>{if(rows3.length===0)return 0;let at=Math.max(0,Math.min(rows3.length-1,i));if(rows3[at]?.kind!=="gap")return at;let rev=[...rows3].reverse().findIndex((r,n)=>rows3.length-1-n<at&&r.kind!=="gap");if(dir<0&&rev>=0)return rows3.length-1-rev;let fwd=rows3.findIndex((r,n)=>n>at&&r.kind!=="gap");if(fwd>=0)return fwd;return rev>=0?rows3.length-1-rev:at},message=(err)=>err instanceof Error?err.message:String(err),rid=(r,i)=>{if(!r)return`empty-${i}`;if(r.kind==="slice")return`slice-${r.bucket.index}-${r.bucket.date??r.bucket.label}`;if(r.kind==="node")return`node-${r.bucket.index}-${r.node.id}`;return`gap-${i}`},Journey=import_react65.memo((props)=>{let gw=useGateway(),theme=useTheme().theme,dialog=useDialog(),toast=useToast(),renderer=useRenderer(),dims=useTerminalDimensions(),keys=useKeys(),[data2,setData]=import_react65.useState(null),[err,setErr]=import_react65.useState(null),[sel,setSel]=import_react65.useState(0),[detail,setDetail]=import_react65.useState(null),[pane,setPane]=import_react65.useState("list"),[busy,setBusy]=import_react65.useState(!1),[tick3,setTick]=import_react65.useState(0),rows3=import_react65.useMemo(()=>buildJourneyRows(data2?.buckets??[]),[data2]),row3=rows3[Math.min(sel,Math.max(0,rows3.length-1))],node=row3?.kind==="node"?row3.node:void 0,chart=last2(data2),h2=Math.max(5,Math.min(8,Math.floor(dims.height*0.2))),cols=Math.max(40,dims.width-8),follow=useFollow("journey",(i)=>rid(rows3[i],i)),scroll=import_react65.useRef(null),seq=import_react65.useRef(0),jump=import_react65.useCallback((i)=>{let n=snap(rows3,i);setSel(n),follow.opts.scrollTo(n)},[rows3]),setListSel=import_react65.useCallback((next)=>{setSel((prev)=>{let target=typeof next==="function"?next(prev):next,n=snap(rows3,target,target-prev);return follow.opts.scrollTo(n),n})},[rows3]);import_react65.useEffect(()=>{let n=0,cb=async()=>{if(n++,n<2)return;follow.opts.scrollTo(sel),renderer.removeFrameCallback(cb)};return renderer.setFrameCallback(cb),()=>renderer.removeFrameCallback(cb)},[renderer,rows3,sel]),import_react65.useEffect(()=>{let n=++seq.current;setErr(null),setBusy(!0);let timer2=setTimeout(()=>{gw.request("learning.frames",{cols,rows:h2,frames:2}).then((r)=>{if(n!==seq.current)return;setData(r);let tree=buildJourneyRows(r.buckets??[]);setSel(latest2(tree)),setDetail(null),setPane("list")}).catch((e)=>{if(n===seq.current)setErr(message(e))}).finally(()=>{if(n===seq.current)setBusy(!1)})},120);return()=>{clearTimeout(timer2),seq.current++}},[gw,cols,h2,tick3]);let open2=import_react65.useCallback(async(target)=>{setBusy(!0),setErr(null);try{let r=await gw.request("learning.detail",{id:target.id});if(setDetail(r),setPane("detail"),!r.ok)toast.show({variant:"warning",message:r.message})}catch(e){setErr(message(e))}finally{setBusy(!1)}},[gw,toast]),edit=import_react65.useCallback(async()=>{if(!node)return;setBusy(!0),setErr(null);try{let info=await gw.request("learning.detail",{id:node.id});if(!info.ok){toast.show({variant:"warning",message:info.message});return}let text3=await editInEditor(renderer,info.content,info.kind==="skill"?".md":".txt");if(text3===void 0||text3.trim()===info.content.trim()){toast.show({variant:"info",message:"no changes"});return}let req={id:node.id,content:text3},r=await gw.request("learning.edit",req);if(toast.show({variant:r.ok?"success":"warning",message:r.message}),r.ok||/stale|refresh/i.test(r.message))setTick((n)=>n+1)}catch(e){setErr(message(e))}finally{setBusy(!1)}},[gw,node,renderer,toast]),del=import_react65.useCallback(async()=>{if(!node)return;if(!await openConfirm(dialog,{title:`Delete ${node.label}?`,body:`${node.fullLabel||node.label}
|
|
4100
4100
|
|
|
4101
|
-
This mutates the learning source through learning.delete.`,yes:"delete",danger:!0}))return;setBusy(!0),setErr(null);try{let req={id:node.id},r=await gw.request("learning.delete",req);if(toast.show({variant:r.ok?"success":"warning",message:r.message}),r.ok||/stale|refresh/i.test(r.message))setTick((n)=>n+1)}catch(e){setErr(message(e))}finally{setBusy(!1)}},[dialog,gw,node,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open()||busy)return;if(detail&&(key3.name==="tab"||keys.match("focus.cycle",key3))){setPane((p)=>p==="list"?"detail":"list");return}if(detail&&pane==="detail"){let page=Math.max(1,(scroll.current?.viewport.height??10)-1);if(key3.name==="escape"){setPane("list");return}if(key3.name==="up"||key3.name==="k"||key3.raw==="k"){scroll.current?.scrollBy(-1);return}if(key3.name==="down"||key3.name==="j"||key3.raw==="j"){scroll.current?.scrollBy(1);return}if(key3.name==="pageup"){scroll.current?.scrollBy(-page);return}if(key3.name==="pagedown"){scroll.current?.scrollBy(page);return}if(key3.name==="home"||key3.name==="g"){scroll.current?.scrollTo(0);return}if(key3.name==="end"||key3.raw==="G"||key3.name==="g"&&key3.shift){scroll.current?.scrollTo(scroll.current.scrollHeight);return}return}if(key3.name==="escape"&&detail){setDetail(null),setPane("list");return}if(handleListKey(keys,key3,{count:rows3.length,setSel:setListSel,...follow.opts,onActivate:()=>{if(node)open2(node)},onToggle:()=>{if(node)open2(node)},onRefresh:()=>setTick((n)=>n+1),onDelete:()=>void del()}))return;if(key3.name==="e"||key3.raw==="e"){edit();return}});let rowPick=import_react65.useCallback((i)=>jump(i),[jump]),rowOpen=import_react65.useCallback((i)=>{jump(i);let r=rows3[i];if(r?.kind==="node")open2(r.node)},[jump,open2,rows3]),hint=detail&&pane==="detail"?`\u2191\u2193/jk scroll ${keys.print("list.pageUp")}/${keys.print("list.pageDown")} page Tab list Esc list`:`${keys.print("list.activate")} detail ${keys.print("list.toggle")} detail e edit ${keys.print("list.delete")} delete ${keys.print("list.refresh")} reload${detail?" Tab detail Esc close":""}`;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:data2?`Journey \xB7 ${data2.count} learned item${data2.count===1?"":"s"}`:"Journey",error:err,focus:pane==="list",grow:detail?2:1,children:[!data2&&!err?$jsx(Loading,{}):null,!data2&&err?$jsx(ErrorState,{err}):null,data2&&data2.count===0?$jsx(Empty,{}):null,data2&&data2.count>0?$jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:[$jsx(Legend,{data:data2}),$jsx(Chart2,{rows:chart,theme}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",children:rows3.map((r,i)=>$jsx(Row2,{id:follow.id(i),row:r,index:i,active:i===sel,theme,pick:rowPick,open:rowOpen},rid(r,i)))})})]}):null]}),detail?$jsx(Detail2,{detail,box:scroll,focus:pane==="detail",theme}):null]}),$jsx(HintBar,{raw:busy?"loading\u2026":hint})]})}),Loading=()=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:$jsx("text",{fg:theme.textMuted,children:"assembling learning map\u2026"})})},Empty=()=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:$jsx("text",{fg:theme.textMuted,children:"No learning yet \u2014 skills and memories will appear here."})})},ErrorState=({err})=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:$jsx("text",{fg:theme.error,wrapMode:"word",children:err})})},Legend=({data:data2})=>{let theme=useTheme().theme,text3=[...data2.legend??[],...data2.categories??[]].map((i)=>`${i.glyph} ${i.label}`).join(" ")||data2.summary.join(" ");return $jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text3})})},Chart2=({rows:rows3,theme})=>$jsx("box",{flexDirection:"column",flexShrink:0,children:rows3.map((row3,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{wrapMode:"none",children:row3.map((run,n)=>$jsx("span",{fg:style(theme,run[1],run[3]),children:run[0]},n))})},i))}),Row2=import_react65.memo((props)=>{let bg2=props.active?props.theme.backgroundElement:void 0,caret=props.active?"\u25B8 ":" ";if(props.row.kind==="gap")return $jsx("box",{id:props.id,height:1});if(props.row.kind==="slice")return $jsx("box",{id:props.id,height:1,backgroundColor:bg2,onMouseMove:()=>props.pick(props.index),onMouseDown:()=>props.open(props.index),overflow:"hidden",children:$jsxs("text",{wrapMode:"none",children:[$jsx("span",{fg:props.theme.textMuted,children:caret}),$jsx("span",{fg:props.active?props.theme.accent:props.theme.primary,children:props.row.bucket.label}),$jsx("span",{fg:props.theme.textMuted,children:` ${props.row.bucket.total} total \xB7 ${props.row.bucket.memories} memories \xB7 ${props.row.bucket.skills} skills`})]})});return $jsx("box",{id:props.id,height:1,backgroundColor:bg2,onMouseMove:()=>props.pick(props.index),onMouseDown:()=>props.open(props.index),overflow:"hidden",children:$jsxs("text",{wrapMode:"none",children:[$jsx("span",{fg:props.theme.textMuted,children:caret}),$jsx("span",{fg:props.theme.textMuted,children:props.row.last?" \u2514\u2500 ":" \u251C\u2500 "}),$jsx("span",{fg:props.active?props.theme.accent:style(props.theme,props.row.node.style),children:`${props.row.node.glyph} ${trunc5(props.row.node.fullLabel||props.row.node.label,54)}`}),$jsx("span",{fg:props.theme.textMuted,children:props.row.node.meta?` ${props.row.node.meta}`:""})]})})}),Detail2=(props)=>$jsx(TabShell,{title:props.detail.ok?`${props.detail.kind} \xB7 ${props.detail.label}`:"Detail",focus:props.focus,grow:1,children:props.detail.ok?$jsx("scrollbox",{ref:props.box,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:props.detail.content.split(/\r?\n/).map((line2,i)=>$jsx("box",{minHeight:1,children:$jsx("text",{fg:props.theme.text,wrapMode:"word",children:line2||" "})},i))})}):$jsx("text",{fg:props.theme.warning,wrapMode:"word",children:props.detail.message})});var import_react67=__toESM(require_react_production(),1);var SubTabBar=import_react67.memo((props)=>$jsx(TabStrip,{...props}));var TABS=[{name:"Chat",description:"Main chat interface"},{name:"Sessions",description:"Sessions, context, analytics"},{name:"Profiles & Automation",description:"Profiles, cron jobs, kanban boards"},{name:"Config",description:"Config, env, skills, toolsets, memory"},{name:"Eikon",description:"Avatar studio & library"}],TAB_MAX=TABS.length-1,CHAT_TAB=0,SESSIONS_TAB=1,AUTOMATION_TAB=2,CONFIG_TAB=3,EIKON_TAB=4,SUB_TABS={[1]:["List","Context","Analytics","Journey"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Library","Catalog","Studio"]},TAB_SLASH={chat:{tab:0,sub:0},sessions:{tab:1,sub:0},context:{tab:1,sub:1},analytics:{tab:1,sub:2},insights:{tab:1,sub:2},journey:{tab:1,sub:3},learning:{tab:1,sub:3},"memory-graph":{tab:1,sub:3},kanban:{tab:2,sub:0},automation:{tab:2,sub:0},profiles:{tab:2,sub:1},agents:{tab:2,sub:1},cron:{tab:2,sub:2},config:{tab:3,sub:0},skills:{tab:3,sub:1},toolsets:{tab:3,sub:2},env:{tab:3,sub:3},memory:{tab:3,sub:4},library:{tab:4,sub:0},catalog:{tab:4,sub:1},studio:{tab:4,sub:2}};var SessionsGroup=import_react68.memo((props)=>{let labels=SUB_TABS[SESSIONS_TAB];import_react68.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info,usage:props.usage})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane,{visible:props.sub===3,children:$jsx(Journey,{focused:!!props.focused&&props.sub===3})})]})]})}),Pane=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react93=__toESM(require_react_production(),1);var import_react82=__toESM(require_react_production(),1);var acc=new Map;function record(ev,p){let id=p.subagent_id;if(!id)return;let now=Date.now()/1000;if(ev==="start"){acc.set(id,{subagent_id:id,parent_id:p.parent_id??null,depth:p.depth??0,goal:p.goal,model:p.model,started_at:now,tool_count:0,status:"running",trail:[]});return}let r=acc.get(id);if(!r)return;if(ev==="tool"&&p.tool_name){r.tool_count++,r.trail=[...r.trail??[],{name:p.tool_name,preview:p.tool_preview}].slice(-20);return}if(ev==="complete")r.status=p.status??"completed",r.finished_at=now,r.input_tokens=p.input_tokens,r.output_tokens=p.output_tokens,r.cost_usd=p.cost_usd}function trail(id){return acc.get(id)?.trail??[]}function flush(gw,sessionId){if(acc.size===0)return;let subagents=[...acc.values()];acc.clear();let label2=(subagents.filter((s)=>s.parent_id==null).slice(0,2).map((s)=>s.goal).join(" \xB7 ")||`${subagents.length} subagents`).slice(0,120),started=Math.min(...subagents.map((s)=>s.started_at));gw.request("spawn_tree.save",{session_id:sessionId,label:label2,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react71=__toESM(require_react_production(),1);var import_react69=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react69.useState(""),[cursor,setCursor]=import_react69.useState(0),mode=import_react69.useRef("kb"),moved=import_react69.useRef(!1),sb=import_react69.useRef(null),theme=useTheme().theme,opts=import_react69.useMemo(()=>props.options.map((o)=>({name:`${props.current==null?"":o.value===props.current?"\u25CF ":" "}${o.title}`,description:o.hint?[o.description,o.hint].filter(Boolean).join(" \u2014 "):o.description??"",value:o.value})),[props.current,props.options]),sel=props.current==null?0:Math.max(0,props.options.findIndex((o)=>o.value===props.current)),desc=props.options.some((o)=>!!o.description||!!o.hint),filtered=import_react69.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react69.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]),rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react69.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react69.useEffect(()=>{if(!props.current){setCursor(0);return}let i=filtered.findIndex((o)=>o.value===props.current),n=Math.max(0,i);setCursor(n),scrollTo(n)},[props.current,filtered]),import_react69.useEffect(()=>{if(!moved.current)return;moved.current=!1;let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key3)=>{if(!filterable)return;if(handleListKey(keys,key3,{count:filtered.length,setSel:(fn)=>{mode.current="kb",moved.current=!0,setCursor(fn)},scrollTo,page:Math.max(1,(sb.current?.viewport.height??10)-1),onActivate:()=>{let item=filtered[cursor];if(item)props.onSelect(item)}}))return;if(props.onKey?.(key3))return});let idx=0,entries2=Array.from(groups.entries());if(!filterable)return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),$jsx("select",{focused:!0,width:58,height:Math.min(16,Math.max(1,props.options.length*(desc?2:1))),options:opts,selectedIndex:sel,showDescription:desc,showScrollIndicator:props.options.length>8,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,fastScrollStep:Math.max(1,props.options.length),keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"pageup",action:"move-up-fast"},{name:"pagedown",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"}],onChange:(i)=>{let item=props.options[i];if(item&&props.onMove)props.onMove(item)},onSelect:(i)=>{let item=props.options[i];if(item)props.onSelect(item)}}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]});return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),filterable?$jsxs($Fragment,{children:[$jsx("input",{value:filter,onInput:(v2)=>{mode.current="kb",setFilter(v2)},placeholder:props.placeholder??"Type to filter...",focused:!0,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{height:1})]}):null,$jsxs("scrollbox",{ref:sb,scrollY:!0,maxHeight:16,focused:!filterable,contentOptions:{flexDirection:"column"},paddingRight:1,children:[filtered.length===0?$jsx("text",{fg:theme.textMuted,children:"No results found"}):null,entries2.map(([cat,items])=>{let elements=[];if(cat)elements.push($jsx("text",{fg:theme.textMuted,children:$jsx("strong",{children:cat})},`cat-${cat}`));return items.forEach((item)=>{let i=idx++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>{mode.current="mouse",moved.current=!0,setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")moved.current=!0,setCursor(i)},onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react71.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react71.useRef(new Map),enabled2=import_react71.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react71.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react71.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react71.useCallback((val)=>{enabled2.current=val},[]),open2=import_react71.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key3)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key3))return open2();for(let c of all())if(c.action&&keys.match(c.action,key3))return c.onSelect()});let value=import_react71.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");var import_react73=__toESM(require_react_production(),1);function openAlert(dialog,title,body){dialog.replace($jsx(Alert,{title,body,onClose:()=>dialog.clear()}))}var Alert=(props)=>{let theme=useTheme().theme,keys=useKeys(),[copied2,setCopied]=import_react73.useState(!1),doCopy=()=>{copy2(props.body),setCopied(!0),setTimeout(()=>setCopied(!1),900)};return useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.accept",key3))props.onClose();if(keys.match("dialog.copy",key3))doCopy()}),$jsxs("box",{flexDirection:"column",width:84,maxHeight:28,border:["left"],borderColor:theme.info,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingRight:2,paddingY:1,gap:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.info,children:"\u25C8 "}),$jsx("span",{fg:theme.text,children:props.title})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.body})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:`${keys.print("dialog.cancel")} close \xB7 ${keys.print("dialog.copy")} `})}),$jsx("box",{flexShrink:0,onMouseDown:(e)=>{e.stopPropagation(),doCopy()},children:$jsx("text",{fg:copied2?theme.success:theme.textMuted,children:$jsx("u",{children:copied2?"copied":"copy"})})})]})]})};var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="error"?theme.error:s==="timeout"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc5(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){dialog.replace($jsx("box",{width:40,height:3,children:$jsx("text",{children:"Loading spawn history\u2026"})}));let listToken=dialog.version();gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{if(dialog.version()!==listToken)return;let entries2=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries2.length?"filter\u2026":"no saved spawn trees",options:entries2.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc5(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries2.find((e)=>e.path===opt.value);dialog.replace($jsx("box",{width:40,height:3,children:$jsx("text",{children:"Loading spawn tree\u2026"})}));let token=dialog.version();gw.request("spawn_tree.load",{path:entry2.path}).then((snap2)=>{if(dialog.version()===token)dialog.replace($jsx(SnapshotView,{entry:entry2,snap:snap2}))}).catch((e)=>{if(dialog.version()===token)openAlert(dialog,"Spawn history",e instanceof Error?e.message:String(e))})}}))}).catch((e)=>{if(dialog.version()===listToken)openAlert(dialog,"Spawn history",e instanceof Error?e.message:String(e))})}var import_react76=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.accept",key3))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Required"})}),req.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null,opt.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react76.useState(!1);useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.deny",key3))return props.done(null);if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.done(force);if(key3.name==="space"||key3.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react78=__toESM(require_react_production(),1);import{existsSync as existsSync16,readFileSync as readFileSync9}from"fs";import{readdir as readdir2}from"fs/promises";import{homedir as homedir6}from"os";import{join as join11,basename as basename8,dirname as dirname8}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join11(home3(),".hermes");function root2(){let hh=hermesHome(),parent2=dirname8(hh);return basename8(parent2)==="profiles"?dirname8(parent2):hh}function profileNameFrom(hh){let parent2=dirname8(hh);return basename8(parent2)==="profiles"?basename8(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync9(join11(root2(),"active_profile"),"utf-8").trim()||null}catch{return null}}var ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/;function readModel(dir){try{let raw=readFileSync9(join11(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean3=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean3(m2),clean3(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join11(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync9(join11(dir,"gateway.pid"),"utf-8").trim(),pid2=raw.startsWith("{")?Number(JSON.parse(raw).pid):Number(raw);if(!Number.isFinite(pid2)||pid2<=0)return!1;return process.kill(pid2,0),!0}catch{return!1}}function soul(dir){try{return readFileSync9(join11(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path4=join11(dir,"distribution.yaml");if(!existsSync16(path4))return null;let data2=(()=>{try{return $parse(readFileSync9(path4,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src2=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join11(home3(),".local","bin",name);return{name,path:dir,is_default:name==="default",is_active:name===active,is_sticky:name===sticky,gateway_running:gatewayRunning(dir),model,provider,has_env:existsSync16(join11(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync16(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src2(dir,dir.replace(home3()+"/","~/")),config:src2(join11(dir,"config.yaml"),"config.yaml"),soul:src2(join11(dir,"SOUL.md"),"SOUL.md"),env:src2(join11(dir,".env"),".env"),distribution:src2(join11(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root2(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync16(r))jobs.push(info("default",r,active,sticky));let pr=join11(r,"profiles");if(existsSync16(pr))for(let e of await readdir2(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join11(pr,e.name),active,sticky))}return Promise.all(jobs)}function validateName(name,existing){if(!ID_RE.test(name))return"must match [a-z0-9][a-z0-9_-]{0,63}";if(existing.includes(name))return"already exists";if(["hermes","default","test","tmp","root","sudo"].includes(name))return"reserved name";return null}function readPrefs(dir){try{let raw=JSON.parse(readFileSync9(join11(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikon??(raw.eikonPath?basename8(raw.eikonPath,".eikon"):void 0),keys:raw.keys?Object.keys(raw.keys).length:0}}catch{return null}}async function profileStats(dir){let sessions=null,messages=null,dbPath=join11(dir,"state.db");if(existsSync16(dbPath))try{let db=new Database2(dbPath,{readwrite:!0,create:!1}),r=db.query("SELECT COUNT(*) AS s FROM sessions WHERE message_count > 0").get(),m2=db.query("SELECT COALESCE(SUM(message_count), 0) AS m FROM sessions").get();sessions=r.s,messages=m2.m,db.close()}catch{}let crons=null;try{let jobs=await Bun.file(join11(dir,"cron","jobs.json")).json();crons=Array.isArray(jobs)?jobs.length:jobs&&typeof jobs==="object"&&Array.isArray(jobs.jobs)?jobs.jobs.length:0}catch{crons=existsSync16(join11(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER3=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react78.useState(""),[cloneIdx,setCloneIdx]=import_react78.useState(0),[alias,setAlias]=import_react78.useState(!0),[field,setField]=import_react78.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit2=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key3)=>{if(key3.name==="escape")return done(null);if(key3.name==="tab")return moveField(key3.shift?-1:1);if(key3.name==="return")return submit2();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[a-z0-9_-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(field==="clone"){if(key3.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key3.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key3.name==="space"||key3.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react80=__toESM(require_react_production(),1);import{rmSync as rmSync3,mkdtempSync as mkdtempSync4}from"fs";import{join as join12}from"path";import{tmpdir as tmpdir4}from"os";var shq=(s)=>`'${s.replace(/'/g,"'\\''")}'`;function openInstallDistribution(dialog,gw){return new Promise((resolve4)=>{askSource(dialog,gw,(r)=>{dialog.clear(),resolve4(r)})})}function askSource(dialog,gw,done){dialog.replace($jsx(Step1,{onSubmit:(source)=>preview(dialog,gw,source,done),onCancel:()=>done(null)}))}async function preview(dialog,gw,source,done){let tmp=mkdtempSync4(join12(tmpdir4(),"herm-dist-preview-")),cleanup=()=>{try{rmSync3(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading2,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest3=readDistributionManifest(tmp);if(!manifest3){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest:manifest3,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react80.useState("");return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading2=(p)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.accept",key3)||keys.match("dialog.cancel",key3))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER4=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react80.useState(""),[alias,setAlias]=import_react80.useState(!1),[field,setField]=import_react80.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER4.indexOf(field);setField(ORDER4[(i+dir+ORDER4.length)%ORDER4.length])};useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel();if(key3.name==="tab")return move(key3.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key3))return fire();if(field==="alias"&&(key3.name==="space"||key3.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk2=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk2(n.kids,d2+1)};if(walk2(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk2=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk2(n.kids)};return walk2(nodes),p}var ProfileRow=import_react82.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react82.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react82.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react82.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react82.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react82.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc5(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk2=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk2(r.subagent_id)}};walk2(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react82.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc5(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc5(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react82.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react82.useState("profiles"),[pView,setPView]=import_react82.useState("list"),[profiles,setProfiles]=import_react82.useState([]),[deleg,setDeleg]=import_react82.useState(null),[liveMap,setLiveMap]=import_react82.useState(()=>new Map),[now,setNow]=import_react82.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react82.useState(0),[dSel,setDSel]=import_react82.useState(0),[err,setErr]=import_react82.useState(""),[delegErr,setDelegErr]=import_react82.useState(""),delegGen=import_react82.useRef(0),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk2=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk2(n.kids)};walk2(nodes)}let live=import_react82.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react82.useRef(void 0),[stats,setStats]=import_react82.useState(()=>new Map),[sticky,setSticky]=import_react82.useState(stickyDefault),loadProfiles=import_react82.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react82.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react82.useCallback(()=>{let current=++delegGen.current;gw.request("delegation.status").then((r)=>{if(delegGen.current!==current)return;setDeleg(r),setNow(Date.now()/1000),setDelegErr("")}).catch((e)=>{if(delegGen.current===current)setDelegErr(e instanceof Error?e.message:String(e))})},[gw]);import_react82.useEffect(loadDeleg,[loadDeleg]),import_react82.useEffect(()=>()=>{delegGen.current++},[]),import_react82.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react82.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react82.useCallback((i)=>setPSel(i),[]),dHover=import_react82.useCallback((i)=>setDSel(i),[]),pDelete=import_react82.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
|
|
4101
|
+
This mutates the learning source through learning.delete.`,yes:"delete",danger:!0}))return;setBusy(!0),setErr(null);try{let req={id:node.id},r=await gw.request("learning.delete",req);if(toast.show({variant:r.ok?"success":"warning",message:r.message}),r.ok||/stale|refresh/i.test(r.message))setTick((n)=>n+1)}catch(e){setErr(message(e))}finally{setBusy(!1)}},[dialog,gw,node,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open()||busy)return;if(detail&&(key3.name==="tab"||keys.match("focus.cycle",key3))){setPane((p)=>p==="list"?"detail":"list");return}if(detail&&pane==="detail"){let page=Math.max(1,(scroll.current?.viewport.height??10)-1);if(key3.name==="escape"){setPane("list");return}if(key3.name==="up"||key3.name==="k"||key3.raw==="k"){scroll.current?.scrollBy(-1);return}if(key3.name==="down"||key3.name==="j"||key3.raw==="j"){scroll.current?.scrollBy(1);return}if(key3.name==="pageup"){scroll.current?.scrollBy(-page);return}if(key3.name==="pagedown"){scroll.current?.scrollBy(page);return}if(key3.name==="home"||key3.name==="g"){scroll.current?.scrollTo(0);return}if(key3.name==="end"||key3.raw==="G"||key3.name==="g"&&key3.shift){scroll.current?.scrollTo(scroll.current.scrollHeight);return}return}if(key3.name==="escape"&&detail){setDetail(null),setPane("list");return}if(handleListKey(keys,key3,{count:rows3.length,setSel:setListSel,...follow.opts,onActivate:()=>{if(node)open2(node)},onToggle:()=>{if(node)open2(node)},onRefresh:()=>setTick((n)=>n+1),onDelete:()=>void del()}))return;if(key3.name==="e"||key3.raw==="e"){edit();return}});let rowPick=import_react65.useCallback((i)=>jump(i),[jump]),rowOpen=import_react65.useCallback((i)=>{jump(i);let r=rows3[i];if(r?.kind==="node")open2(r.node)},[jump,open2,rows3]),hint=detail&&pane==="detail"?`\u2191\u2193/jk scroll ${keys.print("list.pageUp")}/${keys.print("list.pageDown")} page Tab list Esc list`:`${keys.print("list.activate")} detail ${keys.print("list.toggle")} detail e edit ${keys.print("list.delete")} delete ${keys.print("list.refresh")} reload${detail?" Tab detail Esc close":""}`;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:data2?`Journey \xB7 ${data2.count} learned item${data2.count===1?"":"s"}`:"Journey",error:err,focus:pane==="list",grow:detail?2:1,children:[!data2&&!err?$jsx(Loading,{}):null,!data2&&err?$jsx(ErrorState,{err}):null,data2&&data2.count===0?$jsx(Empty,{}):null,data2&&data2.count>0?$jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:[$jsx(Legend,{data:data2}),$jsx(Chart2,{rows:chart,theme}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",children:rows3.map((r,i)=>$jsx(Row2,{id:follow.id(i),row:r,index:i,active:i===sel,theme,pick:rowPick,open:rowOpen},rid(r,i)))})})]}):null]}),detail?$jsx(Detail2,{detail,box:scroll,focus:pane==="detail",theme}):null]}),$jsx(HintBar,{raw:busy?"loading\u2026":hint})]})}),Loading=()=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:$jsx("text",{fg:theme.textMuted,children:"assembling learning map\u2026"})})},Empty=()=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:$jsx("text",{fg:theme.textMuted,children:"No learning yet \u2014 skills and memories will appear here."})})},ErrorState=({err})=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:$jsx("text",{fg:theme.error,wrapMode:"word",children:err})})},Legend=({data:data2})=>{let theme=useTheme().theme,text3=[...data2.legend??[],...data2.categories??[]].map((i)=>`${i.glyph} ${i.label}`).join(" ")||data2.summary.join(" ");return $jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text3})})},Chart2=({rows:rows3,theme})=>$jsx("box",{flexDirection:"column",flexShrink:0,children:rows3.map((row3,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{wrapMode:"none",children:row3.map((run,n)=>$jsx("span",{fg:style(theme,run[1],run[3]),children:run[0]},n))})},i))}),Row2=import_react65.memo((props)=>{let bg2=props.active?props.theme.backgroundElement:void 0,caret=props.active?"\u25B8 ":" ";if(props.row.kind==="gap")return $jsx("box",{id:props.id,height:1});if(props.row.kind==="slice")return $jsx("box",{id:props.id,height:1,backgroundColor:bg2,onMouseMove:()=>props.pick(props.index),onMouseDown:()=>props.open(props.index),overflow:"hidden",children:$jsxs("text",{wrapMode:"none",children:[$jsx("span",{fg:props.theme.textMuted,children:caret}),$jsx("span",{fg:props.active?props.theme.accent:props.theme.primary,children:props.row.bucket.label}),$jsx("span",{fg:props.theme.textMuted,children:` ${props.row.bucket.total} total \xB7 ${props.row.bucket.memories} memories \xB7 ${props.row.bucket.skills} skills`})]})});return $jsx("box",{id:props.id,height:1,backgroundColor:bg2,onMouseMove:()=>props.pick(props.index),onMouseDown:()=>props.open(props.index),overflow:"hidden",children:$jsxs("text",{wrapMode:"none",children:[$jsx("span",{fg:props.theme.textMuted,children:caret}),$jsx("span",{fg:props.theme.textMuted,children:props.row.last?" \u2514\u2500 ":" \u251C\u2500 "}),$jsx("span",{fg:props.active?props.theme.accent:style(props.theme,props.row.node.style),children:`${props.row.node.glyph} ${trunc5(props.row.node.fullLabel||props.row.node.label,54)}`}),$jsx("span",{fg:props.theme.textMuted,children:props.row.node.meta?` ${props.row.node.meta}`:""})]})})}),Detail2=(props)=>$jsx(TabShell,{title:props.detail.ok?`${props.detail.kind} \xB7 ${props.detail.label}`:"Detail",focus:props.focus,grow:1,children:props.detail.ok?$jsx("scrollbox",{ref:props.box,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:props.detail.content.split(/\r?\n/).map((line2,i)=>$jsx("box",{minHeight:1,children:$jsx("text",{fg:props.theme.text,wrapMode:"word",children:line2||" "})},i))})}):$jsx("text",{fg:props.theme.warning,wrapMode:"word",children:props.detail.message})});var import_react67=__toESM(require_react_production(),1);var SubTabBar=import_react67.memo((props)=>$jsx(TabStrip,{...props}));var TABS=[{name:"Chat",description:"Main chat interface"},{name:"Sessions",description:"Sessions, context, analytics"},{name:"Profiles & Automation",description:"Profiles, cron jobs, kanban boards"},{name:"Config",description:"Config, env, skills, toolsets, memory"},{name:"Eikon",description:"Avatar studio & library"}],TAB_MAX=TABS.length-1,CHAT_TAB=0,SESSIONS_TAB=1,AUTOMATION_TAB=2,CONFIG_TAB=3,EIKON_TAB=4,SUB_TABS={[1]:["List","Context","Analytics","Journey"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Library","Catalog","Studio"]},TAB_SLASH={chat:{tab:0,sub:0},sessions:{tab:1,sub:0},context:{tab:1,sub:1},analytics:{tab:1,sub:2},insights:{tab:1,sub:2},journey:{tab:1,sub:3},learning:{tab:1,sub:3},"memory-graph":{tab:1,sub:3},kanban:{tab:2,sub:0},automation:{tab:2,sub:0},profiles:{tab:2,sub:1},agents:{tab:2,sub:1},cron:{tab:2,sub:2},config:{tab:3,sub:0},skills:{tab:3,sub:1},toolsets:{tab:3,sub:2},env:{tab:3,sub:3},memory:{tab:3,sub:4},library:{tab:4,sub:0},catalog:{tab:4,sub:1},studio:{tab:4,sub:2}};var SessionsGroup=import_react68.memo((props)=>{let labels=SUB_TABS[SESSIONS_TAB];import_react68.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info,usage:props.usage})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane,{visible:props.sub===3,children:$jsx(Journey,{focused:!!props.focused&&props.sub===3})})]})]})}),Pane=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react93=__toESM(require_react_production(),1);var import_react82=__toESM(require_react_production(),1);var acc=new Map;function record(ev,p){let id=p.subagent_id;if(!id)return;let now=Date.now()/1000;if(ev==="start"){acc.set(id,{subagent_id:id,parent_id:p.parent_id??null,depth:p.depth??0,goal:p.goal,model:p.model,started_at:now,tool_count:0,status:"running",trail:[]});return}let r=acc.get(id);if(!r)return;if(ev==="tool"&&p.tool_name){r.tool_count++,r.trail=[...r.trail??[],{name:p.tool_name,preview:p.tool_preview}].slice(-20);return}if(ev==="complete")r.status=p.status??"completed",r.finished_at=now,r.input_tokens=p.input_tokens,r.output_tokens=p.output_tokens,r.cost_usd=p.cost_usd}function trail(id){return acc.get(id)?.trail??[]}function flush(gw,sessionId){if(acc.size===0)return;let subagents=[...acc.values()];acc.clear();let label2=(subagents.filter((s)=>s.parent_id==null).slice(0,2).map((s)=>s.goal).join(" \xB7 ")||`${subagents.length} subagents`).slice(0,120),started=Math.min(...subagents.map((s)=>s.started_at));gw.request("spawn_tree.save",{session_id:sessionId,label:label2,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react71=__toESM(require_react_production(),1);var import_react69=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react69.useState(""),[cursor,setCursor]=import_react69.useState(0),mode=import_react69.useRef("kb"),moved=import_react69.useRef(!1),sb=import_react69.useRef(null),theme=useTheme().theme,opts=import_react69.useMemo(()=>props.options.map((o)=>({name:`${props.current==null?"":o.value===props.current?"\u25CF ":" "}${o.title}`,description:o.hint?[o.description,o.hint].filter(Boolean).join(" \u2014 "):o.description??"",value:o.value})),[props.current,props.options]),sel=props.current==null?0:Math.max(0,props.options.findIndex((o)=>o.value===props.current)),desc=props.options.some((o)=>!!o.description||!!o.hint),filtered=import_react69.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react69.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]),rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react69.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react69.useEffect(()=>{if(!props.current){setCursor(0);return}let i=filtered.findIndex((o)=>o.value===props.current),n=Math.max(0,i);setCursor(n),scrollTo(n)},[props.current,filtered]),import_react69.useEffect(()=>{if(!moved.current)return;moved.current=!1;let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key3)=>{if(!filterable)return;if(handleListKey(keys,key3,{count:filtered.length,setSel:(fn)=>{mode.current="kb",moved.current=!0,setCursor(fn)},scrollTo,page:Math.max(1,(sb.current?.viewport.height??10)-1),onActivate:()=>{let item=filtered[cursor];if(item)props.onSelect(item)}}))return;if(props.onKey?.(key3))return});let idx=0,entries2=Array.from(groups.entries());if(!filterable)return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),$jsx("select",{focused:!0,width:58,height:Math.min(16,Math.max(1,props.options.length*(desc?2:1))),options:opts,selectedIndex:sel,showDescription:desc,showScrollIndicator:props.options.length>8,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,fastScrollStep:Math.max(1,props.options.length),keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"pageup",action:"move-up-fast"},{name:"pagedown",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"}],onChange:(i)=>{let item=props.options[i];if(item&&props.onMove)props.onMove(item)},onSelect:(i)=>{let item=props.options[i];if(item)props.onSelect(item)}}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]});return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),filterable?$jsxs($Fragment,{children:[$jsx("input",{value:filter,onInput:(v2)=>{mode.current="kb",setFilter(v2)},placeholder:props.placeholder??"Type to filter...",focused:!0,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{height:1})]}):null,$jsxs("scrollbox",{ref:sb,scrollY:!0,maxHeight:16,focused:!filterable,contentOptions:{flexDirection:"column"},paddingRight:1,children:[filtered.length===0?$jsx("text",{fg:theme.textMuted,children:"No results found"}):null,entries2.map(([cat,items])=>{let elements=[];if(cat)elements.push($jsx("text",{fg:theme.textMuted,children:$jsx("strong",{children:cat})},`cat-${cat}`));return items.forEach((item)=>{let i=idx++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>{mode.current="mouse",moved.current=!0,setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")moved.current=!0,setCursor(i)},onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react71.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react71.useRef(new Map),enabled2=import_react71.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react71.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react71.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react71.useCallback((val)=>{enabled2.current=val},[]),open2=import_react71.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key3)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key3))return open2();for(let c of all())if(c.action&&keys.match(c.action,key3))return c.onSelect()});let value=import_react71.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");var import_react73=__toESM(require_react_production(),1);function openAlert(dialog,title,body){dialog.replace($jsx(Alert,{title,body,onClose:()=>dialog.clear()}))}var Alert=(props)=>{let theme=useTheme().theme,keys=useKeys(),[copied2,setCopied]=import_react73.useState(!1),doCopy=()=>{copy2(props.body),setCopied(!0),setTimeout(()=>setCopied(!1),900)};return useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.accept",key3))props.onClose();if(keys.match("dialog.copy",key3))doCopy()}),$jsxs("box",{flexDirection:"column",width:84,maxHeight:28,border:["left"],borderColor:theme.info,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingRight:2,paddingY:1,gap:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.info,children:"\u25C8 "}),$jsx("span",{fg:theme.text,children:props.title})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.body})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:`${keys.print("dialog.cancel")} close \xB7 ${keys.print("dialog.copy")} `})}),$jsx("box",{flexShrink:0,onMouseDown:(e)=>{e.stopPropagation(),doCopy()},children:$jsx("text",{fg:copied2?theme.success:theme.textMuted,children:$jsx("u",{children:copied2?"copied":"copy"})})})]})]})};var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="error"?theme.error:s==="timeout"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc5(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){dialog.replace($jsx("box",{width:40,height:3,children:$jsx("text",{children:"Loading spawn history\u2026"})}));let listToken=dialog.version();gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{if(dialog.version()!==listToken)return;let entries2=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries2.length?"filter\u2026":"no saved spawn trees",options:entries2.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc5(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries2.find((e)=>e.path===opt.value);dialog.replace($jsx("box",{width:40,height:3,children:$jsx("text",{children:"Loading spawn tree\u2026"})}));let token=dialog.version();gw.request("spawn_tree.load",{path:entry2.path}).then((snap2)=>{if(dialog.version()===token)dialog.replace($jsx(SnapshotView,{entry:entry2,snap:snap2}))}).catch((e)=>{if(dialog.version()===token)openAlert(dialog,"Spawn history",e instanceof Error?e.message:String(e))})}}))}).catch((e)=>{if(dialog.version()===listToken)openAlert(dialog,"Spawn history",e instanceof Error?e.message:String(e))})}var import_react76=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.accept",key3))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Required"})}),req.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null,opt.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react76.useState(!1);useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.deny",key3))return props.done(null);if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.done(force);if(key3.name==="space"||key3.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react78=__toESM(require_react_production(),1);import{existsSync as existsSync16,readFileSync as readFileSync9}from"fs";import{readdir as readdir2}from"fs/promises";import{homedir as homedir6}from"os";import{join as join11,basename as basename8,dirname as dirname8}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join11(home3(),".hermes");function root2(){let hh=hermesHome(),parent2=dirname8(hh);return basename8(parent2)==="profiles"?dirname8(parent2):hh}function profileNameFrom(hh){let parent2=dirname8(hh);return basename8(parent2)==="profiles"?basename8(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync9(join11(root2(),"active_profile"),"utf-8").trim()||null}catch{return null}}var ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/;function resolveProfileHome(name){if(name==="default")return root2();if(!ID_RE.test(name))return null;let dir=join11(root2(),"profiles",name);return existsSync16(dir)?dir:null}function readModel(dir){try{let raw=readFileSync9(join11(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean3=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean3(m2),clean3(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join11(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync9(join11(dir,"gateway.pid"),"utf-8").trim(),pid2=raw.startsWith("{")?Number(JSON.parse(raw).pid):Number(raw);if(!Number.isFinite(pid2)||pid2<=0)return!1;return process.kill(pid2,0),!0}catch{return!1}}function soul(dir){try{return readFileSync9(join11(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path4=join11(dir,"distribution.yaml");if(!existsSync16(path4))return null;let data2=(()=>{try{return $parse(readFileSync9(path4,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src2=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join11(home3(),".local","bin",name);return{name,path:dir,is_default:name==="default",is_active:name===active,is_sticky:name===sticky,gateway_running:gatewayRunning(dir),model,provider,has_env:existsSync16(join11(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync16(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src2(dir,dir.replace(home3()+"/","~/")),config:src2(join11(dir,"config.yaml"),"config.yaml"),soul:src2(join11(dir,"SOUL.md"),"SOUL.md"),env:src2(join11(dir,".env"),".env"),distribution:src2(join11(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root2(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync16(r))jobs.push(info("default",r,active,sticky));let pr=join11(r,"profiles");if(existsSync16(pr))for(let e of await readdir2(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join11(pr,e.name),active,sticky))}return Promise.all(jobs)}function validateName(name,existing){if(!ID_RE.test(name))return"must match [a-z0-9][a-z0-9_-]{0,63}";if(existing.includes(name))return"already exists";if(["hermes","default","test","tmp","root","sudo"].includes(name))return"reserved name";return null}function readPrefs(dir){try{let raw=JSON.parse(readFileSync9(join11(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikon??(raw.eikonPath?basename8(raw.eikonPath,".eikon"):void 0),keys:raw.keys?Object.keys(raw.keys).length:0}}catch{return null}}async function profileStats(dir){let sessions=null,messages=null,dbPath=join11(dir,"state.db");if(existsSync16(dbPath))try{let db=new Database2(dbPath,{readwrite:!0,create:!1}),r=db.query("SELECT COUNT(*) AS s FROM sessions WHERE message_count > 0").get(),m2=db.query("SELECT COALESCE(SUM(message_count), 0) AS m FROM sessions").get();sessions=r.s,messages=m2.m,db.close()}catch{}let crons=null;try{let jobs=await Bun.file(join11(dir,"cron","jobs.json")).json();crons=Array.isArray(jobs)?jobs.length:jobs&&typeof jobs==="object"&&Array.isArray(jobs.jobs)?jobs.jobs.length:0}catch{crons=existsSync16(join11(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER3=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react78.useState(""),[cloneIdx,setCloneIdx]=import_react78.useState(0),[alias,setAlias]=import_react78.useState(!0),[field,setField]=import_react78.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit2=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key3)=>{if(key3.name==="escape")return done(null);if(key3.name==="tab")return moveField(key3.shift?-1:1);if(key3.name==="return")return submit2();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[a-z0-9_-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(field==="clone"){if(key3.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key3.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key3.name==="space"||key3.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react80=__toESM(require_react_production(),1);import{rmSync as rmSync3,mkdtempSync as mkdtempSync4}from"fs";import{join as join12}from"path";import{tmpdir as tmpdir4}from"os";var shq=(s)=>`'${s.replace(/'/g,"'\\''")}'`;function openInstallDistribution(dialog,gw){return new Promise((resolve4)=>{askSource(dialog,gw,(r)=>{dialog.clear(),resolve4(r)})})}function askSource(dialog,gw,done){dialog.replace($jsx(Step1,{onSubmit:(source)=>preview(dialog,gw,source,done),onCancel:()=>done(null)}))}async function preview(dialog,gw,source,done){let tmp=mkdtempSync4(join12(tmpdir4(),"herm-dist-preview-")),cleanup=()=>{try{rmSync3(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading2,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest3=readDistributionManifest(tmp);if(!manifest3){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest:manifest3,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react80.useState("");return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading2=(p)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.accept",key3)||keys.match("dialog.cancel",key3))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER4=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react80.useState(""),[alias,setAlias]=import_react80.useState(!1),[field,setField]=import_react80.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER4.indexOf(field);setField(ORDER4[(i+dir+ORDER4.length)%ORDER4.length])};useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel();if(key3.name==="tab")return move(key3.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key3))return fire();if(field==="alias"&&(key3.name==="space"||key3.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk2=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk2(n.kids,d2+1)};if(walk2(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk2=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk2(n.kids)};return walk2(nodes),p}var ProfileRow=import_react82.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react82.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react82.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react82.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react82.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react82.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc5(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk2=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk2(r.subagent_id)}};walk2(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react82.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc5(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc5(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react82.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react82.useState("profiles"),[pView,setPView]=import_react82.useState("list"),[profiles,setProfiles]=import_react82.useState([]),[deleg,setDeleg]=import_react82.useState(null),[liveMap,setLiveMap]=import_react82.useState(()=>new Map),[now,setNow]=import_react82.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react82.useState(0),[dSel,setDSel]=import_react82.useState(0),[err,setErr]=import_react82.useState(""),[delegErr,setDelegErr]=import_react82.useState(""),delegGen=import_react82.useRef(0),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk2=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk2(n.kids)};walk2(nodes)}let live=import_react82.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react82.useRef(void 0),[stats,setStats]=import_react82.useState(()=>new Map),[sticky,setSticky]=import_react82.useState(stickyDefault),loadProfiles=import_react82.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react82.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react82.useCallback(()=>{let current=++delegGen.current;gw.request("delegation.status").then((r)=>{if(delegGen.current!==current)return;setDeleg(r),setNow(Date.now()/1000),setDelegErr("")}).catch((e)=>{if(delegGen.current===current)setDelegErr(e instanceof Error?e.message:String(e))})},[gw]);import_react82.useEffect(loadDeleg,[loadDeleg]),import_react82.useEffect(()=>()=>{delegGen.current++},[]),import_react82.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react82.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react82.useCallback((i)=>setPSel(i),[]),dHover=import_react82.useCallback((i)=>setDSel(i),[]),pDelete=import_react82.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
|
|
4102
4102
|
|
|
4103
4103
|
Its gateway is running and will be stopped first (may take up to ~10s).`:"";if(!await openConfirm(dialog,{title:"Delete Profile?",body:`'${p.name}' \u2014 config, env, memory, skills, and sessions will be removed. This cannot be undone.${warn}`,yes:"delete",danger:!0}))return;sh(`hermes profile delete ${p.name} -y`).then(()=>{toast.show({variant:"success",message:`Deleted '${p.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,dialog,toast,loadProfiles]),pSwitch=import_react82.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_active||!props.onSwitchProfile)return;if(await openConfirm(dialog,{title:`Switch to '${p.name}'?`,body:"The gateway restarts under this profile's HERMES_HOME. The current session ends (it stays in the outgoing profile's history).",yes:"switch"}))props.onSwitchProfile(p.path,p.name)},[dialog,props.onSwitchProfile]),pUpdate=import_react82.useCallback(async(p,force)=>{let cmd2=`hermes profile update ${p.name} -y${force?" --force-config":""}`;toast.show({variant:"info",message:`Updating '${p.name}'\u2026`});try{await sh(cmd2),toast.show({variant:"success",message:`Updated '${p.name}'`})}catch(err2){let error=err2 instanceof Error?err2:Error(String(err2));if(!p.is_active||!props.onSwitchProfile||!/gateway (?:exited|restarted)/i.test(error.message)){toast.show({variant:"error",message:error.message});return}}if(p.is_active&&props.onSwitchProfile){props.onSwitchProfile(p.path,p.name);return}loadProfiles()},[sh,toast,loadProfiles,props.onSwitchProfile]),pEnter=import_react82.useCallback((i)=>{setPSel(i);let p=live.current.profiles[i];if(!p)return;openProfileMenu(dialog,p,{switch:props.onSwitchProfile?()=>pSwitch(i):void 0,sticky:(pp)=>sh(`hermes profile use ${pp.name}`).then(()=>{toast.show({variant:"success",message:`Sticky default \u2192 '${pp.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),unsticky:()=>sh("hermes profile use --clear").then(()=>{toast.show({variant:"info",message:"Cleared sticky default"}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),export:(pp)=>sh(`hermes profile export ${pp.name}`).then((out)=>toast.show({variant:"success",message:trunc5(out.trim()||`Exported '${pp.name}'`,80)})).catch((e)=>toast.show({variant:"error",message:e.message})),remove:()=>pDelete(i),update:(pp,force)=>pUpdate(pp,force)})},[sh,dialog,toast,loadProfiles,pDelete,pSwitch,pUpdate,props.onSwitchProfile]),dKill=import_react82.useCallback(async(i)=>{let r=live.current.active[i];if(!r)return;if(!await openConfirm(dialog,{title:"Interrupt subagent?",body:`${trunc5(r.goal,120)}
|
|
4104
4104
|
|
|
@@ -4124,32 +4124,33 @@ Moves to 'archived' and ends any open run. Children stay; their dependency on th
|
|
|
4124
4124
|
|
|
4125
4125
|
Reset these slots to auto so they follow the main model?`,yes:"reset stale",no:"keep"})){toast.show({variant:"warning",message:`Aux still pinned to another provider: ${names}. Press X to reset all to auto.`});return}for(let slot of stale){let r=await resetAux(gw,slot.key);if(r.failed.length){toast.show({variant:"error",message:`${slot.label}: ${r.failed.map((f)=>f.err).join("; ")}`});return}}toast.show({variant:"success",message:`Reset ${stale.length} aux slot${stale.length===1?"":"s"} \u2192 auto`}),load4()};openModelPicker(dialog,gw,{title:s.kind==="main"?"Set main model":`Set auxiliary \xB7 ${s.label}`,onApply:async(prov,model)=>{let token=dialog.version(),r=await assign(gw,s.key,prov,model);if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});if(toast.show({variant:"success",message:s.kind==="main"?`main \u2192 ${prov} \xB7 ${model}`:`${s.key} \u2192 ${prov} \xB7 ${model}`}),r.warning)toast.show({variant:"warning",message:r.warning});if(load4(),s.kind==="main"&&dialog.version()===token)await warnStaleAux(prov)}})},[gw,dialog,toast,load4,managed,raw]),unset=import_react96.useCallback((s)=>{if(managed||s.kind!=="aux"||s.auto)return;resetAux(gw,s.key).then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});toast.show({variant:"success",message:`${s.key} \u2192 auto`}),load4()})},[gw,toast,load4,managed]),unsetAll=import_react96.useCallback(()=>openConfirm(dialog,{title:"Reset all auxiliary slots to auto?",body:`${AUX_TASKS.length} slots. Each falls back to the main model.`,yes:"reset",danger:!0}).then((ok)=>{if(!ok)return;resetAux(gw,"all").then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:`${r.failed.length} failed`});toast.show({variant:"success",message:"All auxiliary slots \u2192 auto"}),load4()})}),[gw,dialog,toast,load4]),keys=useKeys();if(useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(keys.match("config.mode",key3)&&!editing&&!searching){setMode((m2)=>m2==="form"?"yaml":"form");return}if(keys.match("config.save",key3))return void save2();if(mode==="yaml"){if(key3.name==="backspace"){loads.current++,setYaml((prev)=>prev.slice(0,-1));return}if(key3.name==="return"){loads.current++,setYaml((prev)=>prev+`
|
|
4126
4126
|
`);return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){loads.current++,setYaml((prev)=>prev+key3.raw);return}return}if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setCursor(0);return}if(key3.name==="backspace"){setQuery((prev)=>prev.slice(0,-1)),setCursor(0);return}if(key3.name==="up"){setCursor((c)=>Math.max(0,c-1));return}if(key3.name==="down"){setCursor((c)=>Math.min(count3-1,c+1));return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setQuery((prev)=>prev+key3.raw),setCursor(0);return}return}if(editing){let f2=fields[cursor];if(key3.name==="escape"){if(setEditing(!1),setBuf(""),f2)setErr((e)=>{let{[f2.key]:_2,...rest}=e;return rest});return}if(key3.name==="return"){if(f2){let msg=check2(f2.key,buf);if(msg){setErr((e)=>({...e,[f2.key]:msg}));return}setErr((e)=>{let{[f2.key]:_2,...rest}=e;return rest});let val=f2.type==="number"?Number(buf)||0:buf;update(f2.key,val)}setEditing(!1),setBuf("");return}if(key3.name==="backspace"){setBuf((prev)=>prev.slice(0,-1));return}if(key3.raw&&key3.raw.length===1){setBuf((prev)=>prev+key3.raw);return}return}if(key3.name==="tab"){setFocus((f2)=>f2==="categories"?"fields":"categories");return}if(keys.match("list.search",key3)){setSearching(!0),setQuery(""),setCursor(0);return}if(focus==="categories"){if(key3.name==="up"){setCat((c)=>{let n=Math.max(0,c-1);return catFollow.opts.scrollTo(n),n}),setCursor(0);return}if(key3.name==="down"){setCat((c)=>{let n=Math.min(groups.length-1,c+1);return catFollow.opts.scrollTo(n),n}),setCursor(0);return}if(key3.name==="return"){setFocus("fields");return}return}if(onSlots){let s=slots[cursor];if(handleListKey(keys,key3,{count:count3,setSel:setCursor,...follow.opts,onActivate:s?()=>pick(s):void 0,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})}})||!s)return;if(key3.raw==="x")return unset(s);if(key3.raw==="X")return void unsetAll();return}let f=fields[cursor],writable=!managed;if(handleListKey(keys,key3,{count:count3,setSel:setCursor,...follow.opts,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onToggle:writable&&f?.type==="boolean"?()=>{let value2=getNested(rawRef.current,f.key);update(f.key,!(value2===void 0?f.value:value2))}:void 0,onActivate:f&&writable&&(f.type==="string"||f.type==="number")?()=>{setEditing(!0),setBuf(String(f.value??""))}:void 0})||!f||!writable)return;if(f.type==="select"&&f.options){let value2=getNested(rawRef.current,f.key),idx=f.options.indexOf(String(value2===void 0?f.value:value2));if(key3.raw==="l"||key3.raw==="]"){update(f.key,f.options[(idx+1)%f.options.length]);return}if(key3.raw==="h"||key3.raw==="["){update(f.key,f.options[(idx-1+f.options.length)%f.options.length]);return}}}),mode==="yaml")return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title:"Config \xB7 YAML",error:loadErr,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.text,children:yaml}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})})}),$jsx(HintBar,{pairs:[[keys.print("config.mode"),"form"],[keys.print("config.save"),"save"]]})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,children:[searching?$jsx("box",{height:1,paddingLeft:1,paddingRight:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:query2}),$jsx("span",{fg:theme.accent,children:"\u2588"}),$jsx("span",{fg:theme.textMuted,children:` ${count3} of ${all.length} \xB7 \u2191\u2193 nav \xB7 Esc close`})]})}):null,$jsxs("box",{flexDirection:"row",flexGrow:1,children:[searching?null:$jsx(TabShell,{title:"Config",grow:1,focus:focus==="categories",children:$jsx("scrollbox",{ref:catFollow.ref,scrollY:!0,flexGrow:1,children:groups.map((c,i)=>{let sel=i===cat,hot=sel&&focus==="categories",items=grouped.get(c)??[],n=c==="models"?slots.length:items.length,catDirty=items.some((f)=>changed(f.key));return $jsx("box",{id:catFollow.id(i),backgroundColor:hot?theme.backgroundElement:void 0,onMouseDown:()=>{setCat(i),setCursor(0),setFocus("categories")},children:$jsxs("text",{children:[$jsx("span",{fg:catDirty?theme.warning:theme.textMuted,children:catDirty?"\u25CF":" "}),$jsxs("span",{fg:hot?theme.accent:sel?theme.primary:theme.text,children:[sel?"\u25B8 ":" ",c]}),$jsx("span",{fg:theme.textMuted,children:` (${n})`})]})},c)})})}),$jsxs(TabShell,{title:onSlots?"models \xB7 applies immediately":searching?"Search":nChanged>0?`${active} \xB7 ${nChanged} unsaved`:active,grow:3,focus:focus==="fields"||searching,error:loadErr,children:[managed?$jsxs("box",{height:1,flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.warning,children:"\uD83D\uDD12 managed install \u2014 edit"}),$jsx(FileLink,{source:makeSource("config.yaml"),children:"config.yaml"}),$jsx("text",{fg:theme.warning,children:"via configuration.nix"})]}):null,onSlots?$jsxs("box",{flexDirection:"column",flexGrow:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Auxiliary tasks handle side-jobs. 'auto' = use main model. Per-task api_key/base_url/timeout live in the 'auxiliary' category."})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:slots.map((s,i)=>$jsx(SlotRow,{id:follow.id(i),s,on:i===cursor&&focus==="fields"},s.key))})]},"slots"):$jsxs($Fragment,{children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),searching?$jsx(Col,{w:12,fg:theme.textMuted,bold:!0,children:"Category"}):null,$jsx(Col,{w:40,fg:theme.textMuted,bold:!0,children:"Field"}),$jsx(Col,{grow:!0,min:6,fg:theme.textMuted,bold:!0,children:"Value"}),$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:9,fg:theme.textMuted,children:""})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching fields":"No fields in this category"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{if(s.head!==null)acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",s.head," "]})},`\xA7${s.head}`));return s.items.forEach((f,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(FieldRow2,{id:follow.id(i),field:f,active:i===cursor&&(focus==="fields"||searching),changed:changed(f.key),editing:editing&&i===cursor,buf,readonly:!!managed,error:err[f.key],badge:searching?groupOf(f.key):void 0},f.key))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]})]})]}),managed?$jsx(HintBar,{raw:`read-only \xB7 managed by ${managed}`}):onSlots?$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],["Enter","pick"],["x","reset"],["X","reset-all"],["Tab","categories"]]}):focus==="categories"&&!searching?$jsx(HintBar,{pairs:[["\u2191\u2193","select"],["Tab","fields"]]}):$jsx(HintBar,{pairs:[[keys.print("config.mode"),"yaml"],["Tab","categories"],["\u2191\u2193","nav"],[keys.print("list.search"),"search"],[keys.print("config.save"),"save"]],suffix:nChanged>0?`\u25CF ${nChanged} unsaved`:void 0})]})});var import_react100=__toESM(require_react_production(),1);var import_react98=__toESM(require_react_production(),1);var iso2=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},parseList=(stdout)=>stdout.split(`
|
|
4127
|
-
`).map((s)=>s.trim()).filter((s)=>s.length>0&&!s.startsWith("(")),shq2=(s)=>/^[A-Za-z0-9._-]+$/.test(s)?s:`'${s.replace(/'/g,"'\\''")}'`,CuratorDialog=()=>{let{theme,syntaxStyle}=useTheme(),gw=useGateway(),toast=useToast(),dialog=useDialog(),state3=useHome("curatorState"),cfg=useHome("config")?.curator,[report2,setReport]=import_react98.useState(null),[loaded,setLoaded]=import_react98.useState(!1),[busy2,setBusy]=import_react98.useState(null),busyRef=import_react98.useRef(null),[archived,setArchived]=import_react98.useState([]),[mode,setMode]=import_react98.useState("report"),[sel,setSel]=import_react98.useState(0),sb=import_react98.useRef(null);import_react98.useEffect(()=>{readLatestCuratorReport().then((r)=>{setReport(r),setLoaded(!0)}).catch(()=>setLoaded(!0))},[]);let refreshArchived=import_react98.useCallback(()=>{gw.request("shell.exec",{command:"hermes curator list-archived"}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());setArchived(parseList(r.stdout))}).catch((e)=>toast.show({variant:"error",message:trunc5(e instanceof Error?e.message:String(e),120)}))},[gw,toast]);import_react98.useEffect(()=>{refreshArchived()},[refreshArchived]);let sh=import_react98.useCallback((verb,ok)=>{if(busyRef.current)return;busyRef.current=verb,setBusy(verb),gw.request("shell.exec",{command:`hermes curator ${verb}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:ok}),home2.invalidate("curatorState")}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>{busyRef.current=null,setBusy(null)})},[gw,toast]),restore=import_react98.useCallback((name)=>{if(busyRef.current)return;busyRef.current="restore",setBusy("restore"),gw.request("shell.exec",{command:`hermes curator restore ${shq2(name)}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:`Restored ${name}`}),setArchived((prev)=>prev.filter((n)=>n!==name)),setSel((s)=>Math.max(0,s-1))}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>{busyRef.current=null,setBusy(null)})},[gw,toast]);useKeyboard((key3)=>{if(mode==="archived"){if(key3.name==="escape"){setMode("report");return}if(key3.raw==="a"){setMode("report");return}if(key3.name==="up")return setSel((s)=>Math.max(0,s-1));if(key3.name==="down")return setSel((s)=>Math.min(archived.length-1,s+1));if(key3.name==="return"){let name=archived[sel];if(name)restore(name);return}return}if(key3.name==="escape")return dialog.clear();if(key3.raw==="r")return sh("run","Curator run started (background)");if(key3.raw==="p")return state3?.paused?sh("resume","Curator resumed"):sh("pause","Curator paused");if(key3.raw==="a"&&archived.length>0)setSel(0),setMode("archived")}),import_react98.useEffect(()=>{if(mode==="archived")sb.current?.scrollChildIntoView(`arch-${sel}`)},[sel,mode]);let last4=iso2(state3?.last_run_at??null),due=last4&&cfg?last4+cfg.interval_hours*3600:null,status=cfg?.enabled===!1?"disabled":state3?.paused?"paused":"enabled",tint=status==="enabled"?theme.success:status==="paused"?theme.warning:theme.textMuted;return $jsxs("box",{flexDirection:"column",width:120,height:34,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Curator"})}),$jsx("span",{fg:tint,children:` \xB7 ${status}`})]}),busy2?$jsx("box",{marginLeft:2,children:$jsx(Spinner,{color:theme.textMuted,label:busy2})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:state3?`${state3.run_count} run${state3.run_count===1?"":"s"}${last4?" \xB7 last "+ago(last4):" \xB7 never"} \xB7 Esc to close`:"No curator state yet \xB7 Esc to close"})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:40,height:"100%",flexShrink:0,children:[$jsx(KVBlock,{rows:[["Next run",status!=="enabled"?`\u2014 (${status})`:due?until(due):"when idle"],["Last run",last4?ago(last4):"never"],["Duration",state3?.last_run_duration_seconds?dur2(state3.last_run_duration_seconds):void 0],["Archived",archived.length>0?String(archived.length):void 0]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Config \xB7 edit in Config tab"})}),$jsx(KVBlock,{rows:[["Interval",cfg?`${cfg.interval_hours}h`:"\u2014"],["Stale after",cfg?`${cfg.stale_after_days}d`:"\u2014"],["Archive after",cfg?`${cfg.archive_after_days}d`:"\u2014"]]}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"r "}),$jsx("span",{fg:theme.text,children:"run now"}),$jsx("span",{fg:theme.textMuted,children:" (background)"})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"p "}),$jsx("span",{fg:theme.text,children:state3?.paused?"resume":"pause"})]})}),archived.length>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"a "}),$jsx("span",{fg:theme.text,children:"archived skills"}),$jsx("span",{fg:theme.textMuted,children:` (${archived.length})`})]})}):null]}),state3?.last_run_summary?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Last run"})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("markdown",{content:state3.last_run_summary,fg:theme.markdownText,syntaxStyle})})]}):null]}),mode==="archived"?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Archived skills (${archived.length})`})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191\u2193 select \xB7 Enter restore \xB7 a/Esc back to report"})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,contentOptions:{flexDirection:"column"},children:archived.length===0?$jsx("text",{fg:theme.textMuted,children:"No archived skills."}):archived.map((name,i)=>$jsx("box",{id:`arch-${i}`,height:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>restore(name),children:$jsxs("text",{fg:i===sel?theme.text:theme.textMuted,children:[i===sel?"\u25B8 ":" ",name]})},name))})]}):!loaded?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading report\u2026"})}):report2?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Report \xB7 ${report2.runId}`})})}),$jsx(KVLink,{label:"File",source:report2.source,text:report2.source.relative}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx("markdown",{content:report2.content||"(empty)",fg:theme.markdownText,syntaxStyle})})})]}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No runs yet \u2014 curator has not completed a cycle."})})]})]})},openCurator=(dialog)=>dialog.replace($jsx(CuratorDialog,{}),void 0,{ownCancel:!0});var NO_EVENTS=[],iso3=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},SkillRow=import_react100.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,bg2=props.selected?theme.backgroundElement:void 0,used=iso3(u3?.last_used_at)??iso3(u3?.last_viewed_at),stale=u3?.state==="stale",archived=u3?.state==="archived";return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:theme.warning,children:u3?.pinned?"\uD83D\uDCCC":" "}),$jsx(Marquee,{grow:!0,min:8,active:props.selected,fg:archived?theme.textMuted:props.selected?theme.accent:theme.text,children:s.name}),archived?$jsx(Col,{w:10,fg:theme.textMuted,children:"archived"}):stale?$jsx(Col,{w:10,fg:theme.warning,children:"stale"}):$jsx(Col,{w:10,fg:theme.textMuted,children:used?ago(used):""})]})}),HitRow=import_react100.memo((props)=>{let theme=useTheme().theme,on=props.selected;return $jsxs("box",{flexDirection:"row",height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:on?theme.accent:theme.text,children:props.hit.name}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,children:props.hit.description||"\u2014"})]})}),bycat=(skills)=>skills.reduce((map,s)=>{let cat=s.category||"uncategorized";return map.set(cat,[...map.get(cat)??[],s]),map},new Map),line3=(e)=>{switch(e.kind){case"absorbed":return`absorbed ${e.sources.map((s)=>`\`${s}\``).join(", ")}`;case"merged":return`merged into \`${e.into}\`${e.reason?` \u2014 ${e.reason}`:""}`;case"transition":return`${e.from} \u2192 ${e.to}`;case"pruned":return`pruned${e.reason?` \u2014 ${e.reason}`:""}`;case"added":return"created by curator"}},DetailPanel2=import_react100.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,used=iso3(u3?.last_used_at),viewed=iso3(u3?.last_viewed_at),patched=iso3(u3?.last_patched_at);return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Detail"})}),u3?.pinned?$jsx("span",{fg:theme.warning,children:" \uD83D\uDCCC pinned"}):null,u3?.state==="stale"?$jsx("span",{fg:theme.warning,children:" \xB7 stale"}):null,u3?.state==="archived"?$jsx("span",{fg:theme.textMuted,children:" \xB7 archived"}):null]})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:s.name})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Category",s.category||"uncategorized",theme.info],["Tags",s.tags.length>0?s.tags.join(", "):void 0],u3?["Used",u3.use_count>0?`${u3.use_count}\xD7 \xB7 last ${used?ago(used):"never"}`:"never"]:null,u3&&viewed?["Viewed",`${u3.view_count}\xD7 \xB7 last ${ago(viewed)}`]:null,u3&&patched?["Patched",`${u3.patch_count}\xD7 \xB7 last ${ago(patched)}`]:null].filter(Boolean)}),$jsx(KVLink,{label:"File",source:s.source,text:s.source.relative}),$jsx("box",{height:1}),s.description?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:s.description})}):$jsx("text",{fg:theme.textMuted,children:"No description"}),props.events.length>0?$jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Curator lineage"})}),props.events.map((e,i)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:ago(e.at)})}),$jsx("box",{flexGrow:1,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:line3(e)})})]},i))]}):u3?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No curator events for this skill"})}):null]})}),EmptyState=import_react100.memo((props)=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:props.searching?"No matching skills on hub":"No skills found in ~/.hermes/skills/"})})})}),HistoryPanel=import_react100.memo((props)=>{let{theme,syntaxStyle}=useTheme(),dialog=useDialog(),keys=useKeys(),follow=useFollow("skills-history"),[runs,setRuns]=import_react100.useState(()=>listCuratorRuns()),[sel,setSel]=import_react100.useState(0),[open3,setOpen]=import_react100.useState(!1),[body,setBody]=import_react100.useState(""),run=runs[sel];import_react100.useEffect(()=>{if(!open3||!run)return;let live=!0;return readCuratorReport(run.id).then((t2)=>{if(live)setBody(t2)}),()=>{live=!1}},[open3,run?.id]);let moveSel=import_react100.useCallback((v2)=>{setOpen(!1),setSel(v2)},[]);return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;handleListKey(keys,key3,{count:runs.length,setSel:moveSel,...follow.opts,onActivate:()=>setOpen((o)=>!o),onRefresh:()=>setRuns(listCuratorRuns())})}),$jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:props.focused?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Curator History"})}),$jsx("span",{fg:theme.textMuted,children:` ${runs.length} run${runs.length===1?"":"s"}${runs[0]?` \xB7 last ${ago(runs[0].at)}`:""}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select \xB7 Enter expand \xB7 ${keys.print("list.refresh")} reload \xB7 h close`})}),$jsx("box",{height:1}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:"no runs in ~/.hermes/logs/curator/"}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:runs.map((r,i)=>{let on=i===sel;return $jsxs("box",{id:follow.id(i),flexDirection:"column",children:[$jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),setOpen((o)=>i===sel?!o:!0)},children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:12,fg:on?theme.accent:theme.text,children:ago(r.at)}),$jsx(Col,{grow:!0,fg:theme.textMuted,children:`${r.before}\u2192${r.after} arch ${r.archived} cons ${r.consolidated}${r.added?` +${r.added}`:""}`})]}),on&&open3?$jsx("box",{marginLeft:2,marginTop:1,marginBottom:1,children:$jsx("markdown",{content:body||"\u2026",fg:theme.markdownText,syntaxStyle})}):null]},r.id)})})})]})}),Skills=import_react100.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),usage=useHome("skillUsage")??{},curator=useHome("curatorState"),lineage2=import_react100.useRef(indexCuratorLineage());import_react100.useEffect(()=>{lineage2.current=indexCuratorLineage()},[curator?.run_count]);let[skills,setSkills]=import_react100.useState([]),[selected,setSelected]=import_react100.useState(0),[searching,setSearching]=import_react100.useState(!1),[query2,setQuery]=import_react100.useState(""),[hits,setHits]=import_react100.useState([]),[sort,setSort]=import_react100.useState("name"),[history,setHistory]=import_react100.useState(!1),seq=import_react100.useRef(0),listSeq=import_react100.useRef(0),load4=import_react100.useCallback(()=>{let id=++listSeq.current;gw.request("skills.manage",{action:"list"}).then((res)=>{if(listSeq.current!==id)return;let raw=res.skills??{},rows3=Object.entries(raw).flatMap(([cat,names])=>names.map((n)=>{let source=makeSource(`skills/${cat}/${n}/SKILL.md`,`${n}/SKILL.md`),fm=readSkillFrontmatter(source);return{source,category:cat,name:n,description:fm.description,tags:fm.tags,tokenEstimate:count2(`${n} ${fm.description}`)}}));rows3.sort((a,b2)=>a.source.relative.localeCompare(b2.source.relative)),setSkills(rows3)}).catch((err)=>{if(listSeq.current===id)toast.show({variant:"error",message:err.message})})},[gw,toast]);import_react100.useEffect(()=>{return load4(),()=>{listSeq.current++}},[load4]),import_react100.useEffect(()=>{let id=++seq.current;if(!searching||!query2.trim()){setHits([]);return}let t2=setTimeout(()=>{gw.request("skills.manage",{action:"search",query:query2}).then((r)=>{if(seq.current!==id)return;setHits(r.results??[]),setSelected(0)}).catch((err)=>{if(seq.current!==id)return;setHits([]),toast.show({variant:"error",message:err.message})})},150);return()=>clearTimeout(t2)},[gw,toast,query2,searching]);let flat=[...sort==="used"?new Map([["by recency",[...skills].sort((a,b2)=>{let ta=iso3(usage[a.name]?.last_used_at)??iso3(usage[a.name]?.last_viewed_at)??0;return(iso3(usage[b2.name]?.last_used_at)??iso3(usage[b2.name]?.last_viewed_at)??0)-ta})]]):bycat(skills)].flatMap(([cat,items])=>[{type:"header",category:cat},...items.map((s)=>({type:"skill",skill:s}))]),skillRows=flat.filter((r)=>r.type==="skill"),count3=searching?hits.length:skillRows.length,current=!searching&&skillRows[selected]?.type==="skill"?skillRows[selected].skill:null,follow=useFollow("sk"),exit=import_react100.useCallback(()=>{setSearching(!1),setQuery(""),setHits([]),setSelected(0)},[]),install2=import_react100.useCallback(async(name)=>{if(!await openConfirm(dialog,{title:"Install skill?",body:name,yes:"install"}))return;gw.request("skills.manage",{action:"install",query:name}).then(()=>{toast.show({variant:"success",message:`Installed ${name}`}),exit(),load4()}).catch((e)=>toast.show({variant:"error",message:`Install failed: ${e.message}`}))},[dialog,gw,toast,exit,load4]),keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){exit();return}if(key3.name==="backspace"){setQuery((p)=>p.slice(0,-1)),setSelected(0);return}if(key3.name==="up")return setSelected((p)=>Math.max(0,p-1));if(key3.name==="down")return setSelected((p)=>Math.min(count3-1,p+1));if(key3.name==="return"){let hit=hits[selected];if(hit)install2(hit.name);return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" ")setQuery((p)=>p+key3.raw),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="s"){setSort((p)=>p==="name"?"used":"name"),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="c"){openCurator(dialog);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="h"){setHistory((h2)=>!h2);return}if(history){if(key3.name==="escape")return setHistory(!1);return}handleListKey(keys,key3,{count:count3,setSel:setSelected,...follow.opts,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onSearch:()=>{setSearching(!0),setQuery(""),setHits([]),setSelected(0)}})});let skillIdx=-1;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Hub Search (${hits.length})`:`Skills (${skills.length}${sort==="used"?" \xB7 by use":""})`,children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query2}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,searching?null:$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,bold:!0,children:"Name"})]}),searching?null:$jsx("box",{height:1}),count3===0?$jsx(EmptyState,{searching}):searching?$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:hits.map((h2,i)=>$jsx(HitRow,{hit:h2,selected:i===selected,onHover:()=>setSelected(i)},h2.name))})}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:flat.map((row3,i)=>{if(row3.type==="header")return $jsx("box",{marginTop:i>0?1:0,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE ${row3.category}`})})},`h-${row3.category}`);skillIdx++;let idx=skillIdx;return $jsx(SkillRow,{id:follow.id(idx),skill:row3.skill,usage:usage[row3.skill.name],selected:idx===selected,onSelect:()=>setSelected(idx),onHover:()=>setSelected(idx)},row3.skill.name)})}),!searching&&curator?$jsx("box",{height:1,flexShrink:0,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"curator \xB7 "}),curator.paused?$jsx("span",{fg:theme.warning,children:"paused"}):curator.last_run_at?$jsx("span",{fg:theme.textMuted,children:`${curator.run_count} run${curator.run_count===1?"":"s"} \xB7 last ${ago(iso3(curator.last_run_at)??0)}`}):$jsx("span",{fg:theme.textMuted,children:"never run"})]})}):null]}),history?$jsx(HistoryPanel,{focused:!!props.focused&&!searching}):current?$jsx(DetailPanel2,{skill:current,usage:usage[current.name],events:lineage2.current.get(current.name)??NO_EVENTS}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter","install"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],[keys.print("list.search"),"search hub"],["s","sort"],["c","curator"],["h","history"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react102=__toESM(require_react_production(),1);var kindOf=(ts)=>ts.name.includes(":")?"mcp":ts.name.startsWith("hermes-")?"platform":"core",KIND_LABEL={core:"core",platform:"platform bundles",mcp:"mcp"},group2=(list2)=>{let by={core:[],platform:[],mcp:[]};for(let ts of list2)by[kindOf(ts)].push(ts);return["core","platform","mcp"].filter((k2)=>by[k2].length>0).map((k2)=>({kind:k2,items:by[k2]}))},Row3=import_react102.memo((props)=>{let theme=useTheme().theme,ts=props.ts,bg2=props.selected?theme.backgroundElement:void 0,unavail=ts.available===!1,glyph=unavail?"\u25CC":ts.enabled?"\u25CF":"\u25CB",glyphFg=unavail?theme.warning:ts.enabled?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphFg,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:ts.name}),$jsx(Col,{w:9,fg:theme.info,right:!0,children:`${ts.tool_count} tools`})]})}),DetailPanel3=import_react102.memo((props)=>{let theme=useTheme().theme,ts=props.ts,unavail=ts.available===!1;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"40%",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:ts.name})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:KIND_LABEL[kindOf(ts)]})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",unavail?"unavailable":ts.enabled?"enabled":"disabled",unavail?theme.warning:ts.enabled?theme.success:theme.textMuted],["Tools",String(ts.tool_count),theme.info],["Includes",ts.includes?.length?ts.includes.join(", "):void 0,theme.text],["Requires",ts.requirements?.length?ts.requirements.join(", "):void 0,unavail?theme.warning:theme.text]]}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:ts.description||"\u2014"})}),ts.tools?.length?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Tools (",ts.tools.length,"):"]})}),$jsx("scrollbox",{flexGrow:1,scrollY:!0,children:ts.tools.map((n)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",n]},n))})]}):null]})}),Toolsets=import_react102.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),[list2,setList]=import_react102.useState([]),[sel,setSel]=import_react102.useState(0),[err,setErr]=import_react102.useState(null),rev=import_react102.useRef(0),loads=import_react102.useRef(0),writes=import_react102.useRef(Promise.resolve()),known=import_react102.useRef(new Map),secs=group2(list2),flat=secs.flatMap((s)=>s.items),live=import_react102.useRef({flat,sel});live.current={flat,sel};let load4=import_react102.useCallback(()=>{let gen=++loads.current;gw.request("toolsets.list",{}).then((r)=>{if(loads.current!==gen)return;let next2=r.toolsets??[];known.current=new Map(next2.map((t2)=>[t2.name,t2.enabled])),setList(next2),setErr(null)}).catch((e)=>{if(loads.current===gen)setErr(e instanceof Error?e.message:String(e))})},[gw]);import_react102.useEffect(()=>{return load4(),()=>{rev.current++,loads.current++}},[load4]);let toggle=import_react102.useCallback(()=>{let ts2=live.current.flat[live.current.sel];if(!ts2)return;if(ts2.available===!1){toast.show({variant:"warning",message:`${ts2.name} is unavailable`});return}let enabled2=!ts2.enabled,action=enabled2?"enable":"disable",gen=++rev.current;loads.current++,live.current={...live.current,flat:live.current.flat.map((t2)=>t2.name===ts2.name?{...t2,enabled:enabled2}:t2)},setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:enabled2}:t2)),writes.current=writes.current.then(async()=>{try{let r=await gw.request("tools.configure",{action,names:[ts2.name]}),authoritative=Array.isArray(r.enabled_toolsets)?new Set(r.enabled_toolsets):null;if(authoritative)known.current=new Map(live.current.flat.map((t2)=>[t2.name,authoritative.has(t2.name)]));if(rev.current!==gen)return;if(r.unknown?.includes(ts2.name)){setList((prev)=>prev.map((t2)=>({...t2,enabled:known.current.get(t2.name)??t2.enabled}))),toast.show({variant:"warning",message:`${ts2.name} is not configurable`});return}if(r.missing_servers?.length&&ts2.name.includes(":")){let server=ts2.name.split(":",1)[0];if(r.missing_servers.includes(server)){setList((prev)=>prev.map((t2)=>({...t2,enabled:known.current.get(t2.name)??t2.enabled}))),toast.show({variant:"warning",message:`MCP server '${server}' not in config`});return}}if(authoritative)setList((prev)=>prev.map((t2)=>({...t2,enabled:authoritative.has(t2.name)})));else load4()}catch(e){if(rev.current!==gen)return;setList((prev)=>prev.map((t2)=>({...t2,enabled:known.current.get(t2.name)??t2.enabled}))),toast.show({variant:"error",message:e instanceof Error?e.message:String(e)})}})},[gw,toast,load4]),count3=flat.length,ts=flat[sel]??null,follow=useFollow("ts"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:count3,setSel,...follow.opts,onToggle:toggle,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})}});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:`Toolsets (${count3})`,error:err,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:9,fg:theme.textMuted,bold:!0,right:!0,children:"Tools"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:"No toolsets found"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{return acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",KIND_LABEL[s.kind]," (",s.items.length,") "]})},`\xA7${s.kind}`)),s.items.forEach((t2,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(Row3,{id:follow.id(i),ts:t2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},t2.name))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]}),ts?$jsx(DetailPanel3,{ts}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.toggle"),"toggle"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react103=__toESM(require_react_production(),1);var mask=(val)=>"\u2022".repeat(Math.min(val.length,12)),VarRow=import_react103.memo((props)=>{let theme=useTheme().theme,set3=props.value!==void 0,bg2=props.selected?theme.backgroundElement:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onClick,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:props.selected?theme.accent:theme.text,children:props.name}),$jsx(Col,{w:8,fg:set3?theme.success:theme.textMuted,children:set3?" SET ":"UNSET"}),$jsx(Col,{grow:!0,min:4,fg:props.shown?theme.text:theme.textMuted,children:set3?props.shown?props.value:mask(props.value):"\u2014"})]})}),Env=import_react103.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),vars=useHome("env")??{},[sel,setSel]=import_react103.useState(0),[reveal,setReveal]=import_react103.useState(new Set),[collapsed,setCollapsed]=import_react103.useState({}),[searching,setSearching]=import_react103.useState(!1),[query2,setQuery]=import_react103.useState(""),known=new Set(ENV_CATALOG.flatMap((g)=>g.keys)),extra=Object.keys(vars).filter((k2)=>!known.has(k2)).sort(),rows3=(extra.length>0?[...ENV_CATALOG,{category:"Other",keys:extra}]:ENV_CATALOG).flatMap((g)=>{let keys2=searching&&query2.trim()?g.keys.filter((k2)=>k2.toLowerCase().includes(query2.toLowerCase())):g.keys;if(keys2.length===0)return[];let hide=collapsed[g.category]??!1,header={type:"header",category:g.category,collapsed:hide};if(hide)return[header];return[header,...keys2.map((key3)=>({type:"var",key:key3,value:vars[key3]}))]}),count3=rows3.length,cur=rows3[sel],setKeys=rows3.flatMap((r)=>r.type==="var"&&r.value!==void 0?[r.key]:[]),follow=useFollow("env"),edit=import_react103.useCallback(async(key3,initial)=>{let val=await openTextPrompt(dialog,{title:`Edit ${key3}`,label:"Value",initial});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} saved`})},[dialog,toast]),add=import_react103.useCallback(async()=>{let key3=await openTextPrompt(dialog,{title:"New Variable",label:"Name (e.g. FOO_API_KEY)"});if(!key3)return;let val=await openTextPrompt(dialog,{title:`Set ${key3}`,label:"Value"});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} added`})},[dialog,toast]),del=import_react103.useCallback(async(key3)=>{if(!await openConfirm(dialog,{title:"Delete Variable",body:`Remove ${key3} from .env?`,yes:"delete",danger:!0}))return;await removeEnvVar(key3),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} removed`})},[dialog,toast]),revealAll=import_react103.useCallback(()=>setReveal((s)=>s.size===setKeys.length&&setKeys.length>0?new Set:new Set(setKeys)),[setKeys]),activateAt=import_react103.useCallback((i)=>{let r=rows3[i];if(r?.type==="header")return setCollapsed((p)=>({...p,[r.category]:!p[r.category]}));if(r?.type==="var"){if(r.value!==void 0&&!reveal.has(r.key))return setReveal((s)=>new Set(s).add(r.key));return void edit(r.key,r.value??"")}},[rows3,reveal,edit]),activate=import_react103.useCallback(()=>activateAt(sel),[activateAt,sel]),rowClick=import_react103.useCallback((i)=>{setSel(i),activateAt(i)},[activateAt]),keys=useKeys();return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setSel(0);return}if(key3.name==="backspace"){setQuery((q4)=>q4.slice(0,-1)),setSel(0);return}if(key3.name==="up")return setSel((p)=>Math.max(0,p-1));if(key3.name==="down")return setSel((p)=>Math.min(count3-1,p+1));if(key3.name==="return")return setSearching(!1),activate();if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setQuery((q4)=>q4+key3.raw),setSel(0);return}return}handleListKey(keys,key3,{count:count3,setSel,...follow.opts,onActivate:activate,onToggle:revealAll,onNew:add,onDelete:()=>{if(cur?.type==="var"&&cur.value!==void 0)del(cur.key)},onSearch:()=>{setSearching(!0),setQuery(""),setSel(0)},onRefresh:()=>{home2.invalidate("env"),toast.show({variant:"info",message:"Reloaded",duration:1000})}})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:searching?"Env (searching)":"Env / API Keys",children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query2}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:28,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:8,fg:theme.textMuted,bold:!0,children:"Status"}),$jsx(Col,{grow:!0,min:4,fg:theme.textMuted,bold:!0,children:"Value"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching variables":"No variables configured"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((row3,i)=>row3.type==="header"?$jsx("box",{id:follow.id(i),marginTop:i>0?1:0,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>rowClick(i),children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`${row3.collapsed?"\u25B8":"\u25BE"} ${row3.category}`})})},`h-${row3.category}`):$jsx(VarRow,{id:follow.id(i),name:row3.key,value:row3.value,shown:reveal.has(row3.key),selected:i===sel,onHover:()=>setSel(i),onClick:()=>rowClick(i)},row3.key))})},"list")]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","move"],["Enter","reveal/edit"],["Esc","cancel"]]:[["\u2191\u2193","move"],[keys.print("list.activate"),"reveal/edit"],[keys.print("list.toggle"),"show-all"],[keys.print("list.new"),"new"],[keys.print("list.delete"),"delete"],[keys.print("list.search"),"search"],[keys.print("list.refresh"),"reload"]]})]})});var import_react105=__toESM(require_react_production(),1);function usageColor(pct,theme){if(pct>=95)return theme.error;if(pct>=80)return theme.warning;return theme.success}function bar2(pct,w2){let filled=Math.round(pct/100*w2);return"\u2588".repeat(filled)+"\u2591".repeat(w2-filled)}var DESC={builtin:"File-based \xA7-delimited entries (MEMORY.md + USER.md). Always active.",mem0:"Server-side LLM fact extraction with semantic search and reranking.",honcho:"AI-native cross-session user modeling with dialectic Q&A.",hindsight:"Knowledge graph with entity resolution and multi-strategy retrieval.",holographic:"Local SQLite fact store with FTS5, trust scoring, HRR retrieval.",openviking:"Session-managed memory with tiered retrieval.",retaindb:"Cloud memory API with hybrid search and 7 memory types.",byterover:"Persistent knowledge tree via brv CLI.",supermemory:"Semantic long-term memory with profile recall and session ingest."},Memory=import_react105.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),gw=useGateway(),[sel,setSel]=import_react105.useState(0),config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),providers=useHome("memoryProviders")??[],activity=useHome("memoryActivity")??[],cfg=config?.memory,active=cfg?.provider||"",cur=providers[sel],on=!!cur&&(cur.name==="builtin"||cur.name===active),toggle=async()=>{if(!cur||cur.name==="builtin")return;let isOn=cur.name===active;if(!await openConfirm(dialog,{title:isOn?"Deactivate memory provider?":"Activate memory provider?",body:isOn?`Clear '${cur.name}' as the active provider (revert to built-in only).`:`Set '${cur.name}' as the active provider. Ensure required env vars are set (Env tab).`,yes:isOn?"deactivate":"activate"}))return;let{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"memory.provider",to:isOn?"":cur.name}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),home2.invalidate("memoryProviders"),toast.show({variant:"success",message:isOn?"Deactivated":`Activated ${cur.name} \u2014 new sessions pick this up`})},keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:providers.length,setSel,onToggle:toggle,onRefresh:()=>{home2.invalidate("memoryProviders"),home2.invalidate("memoryActivity"),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),feed=!cur?[]:cur.name==="builtin"?activity:activity.filter((a)=>a.provider===cur.name);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:"Memory Providers",grow:1,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:providers.map((p,i)=>{let pOn=p.name==="builtin"||p.name===active,has2=Object.keys(p.config).length>0,dot=pOn?"\u25CF":has2?"\u25D0":"\u25CB",fg2=pOn?theme.success:has2?theme.warning:theme.textMuted,tag=pOn?"active":has2?"configured":"";return $jsxs("box",{flexDirection:"column",marginBottom:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseDown:()=>setSel(i),onMouseMove:()=>setSel(i),children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[dot," "]}),$jsx("span",{fg:i===sel?theme.accent:theme.text,children:p.name}),tag?$jsxs("span",{fg:fg2,children:[" (",tag,")"]}):null]})}),$jsx("box",{height:1,overflow:"hidden",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:DESC[p.name]||"\u2014"})})]},p.name)})})}),$jsx(TabShell,{title:cur?.name??"Provider",grow:2,children:cur?$jsx(ProviderDetail,{provider:cur,active,cfg,memory,userProfile,feed}):$jsx("text",{fg:theme.textMuted,children:"Select a provider"})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.toggle"),"activate"]],suffix:on?"\u25CF active":"\u25CB inactive"})]})}),ProviderDetail=import_react105.memo((props)=>{let theme=useTheme().theme,p=props.provider,on=p.name==="builtin"||p.name===props.active;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:DESC[p.name]||"Memory provider"})}),$jsx("box",{height:1}),p.name==="builtin"?$jsxs("box",{flexDirection:"column",children:[props.cfg?$jsxs($Fragment,{children:[$jsx(KVBlock,{rows:[["Notes",props.cfg.memory_enabled?"enabled":"disabled",props.cfg.memory_enabled?theme.success:theme.error],["Profile",props.cfg.user_profile_enabled?"enabled":"disabled",props.cfg.user_profile_enabled?theme.success:theme.error]]}),$jsx("box",{height:1})]}):null,$jsx(CapacityBar,{title:"Notes (MEMORY.md)",info:props.memory??null}),$jsx("box",{height:1}),$jsx(CapacityBar,{title:"Profile (USER.md)",info:props.userProfile??null})]}):null,p.name!=="builtin"&&on&&props.cfg?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Agent Settings"})})}),$jsx(KVBlock,{rows:[["Nudge",`every ${props.cfg.nudge_interval} turns`],["Flush",`after ${props.cfg.flush_min_turns} turns`]]}),$jsx("box",{height:1})]}):null,Object.keys(p.config).length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Local Configuration"})})}),$jsx(KVBlock,{rows:Object.entries(p.config).map(([k2,v2])=>[k2,String(v2)])})]}):p.name!=="builtin"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No local config found. Run `hermes memory setup` to configure."})}):null,$jsx(ActivityFeed,{items:props.feed,own:p.name})]})})}),OP_GLYPH={write:"+",read:"?"},ActivityFeed=import_react105.memo((props)=>{let theme=useTheme().theme,all=props.own==="builtin",nW=props.items.filter((a)=>a.op==="write").length;return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"Recent Activity"})}),props.items.length?$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",nW," writes, ",props.items.length-nW," reads"]}):null]})}),props.items.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No memory-tool calls in the last ~2000 messages"})}):null,props.items.map((a,i)=>$jsx("box",{height:1,flexDirection:"row",overflow:"hidden",children:$jsxs("text",{children:[$jsxs("span",{fg:a.op==="write"?theme.success:theme.textMuted,children:[OP_GLYPH[a.op]," "]}),$jsx("span",{fg:theme.textMuted,children:ago(a.ts).padEnd(8)}),all&&a.provider!=="builtin"?$jsxs("span",{fg:theme.primary,children:[a.provider,"\xB7"]}):null,$jsx("span",{fg:theme.text,children:a.verb}),$jsxs("span",{fg:theme.textMuted,children:[" ",a.summary]})]})},i))]})}),CapacityBar=import_react105.memo((props)=>{let theme=useTheme().theme;if(!props.info)return $jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.title,": unavailable"]})});let color=usageColor(props.info.usagePercent,theme);return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:props.title}),$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",props.info.entryCount," entries"]})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:color,children:bar2(props.info.usagePercent,20)}),$jsxs("span",{fg:theme.textMuted,children:[" ",props.info.charCount,"/",props.info.charLimit," (",props.info.usagePercent,"%)"]})]})})]})});var ConfigGroup=import_react106.memo((props)=>{let labels=SUB_TABS[CONFIG_TAB];import_react106.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane3,{visible:props.sub===0,children:$jsx(Config2,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane3,{visible:props.sub===1,children:$jsx(Skills,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane3,{visible:props.sub===2,children:$jsx(Toolsets,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane3,{visible:props.sub===3,children:$jsx(Env,{focused:!!props.focused&&props.sub===3})}),$jsx(Pane3,{visible:props.sub===4,children:$jsx(Memory,{focused:!!props.focused&&props.sub===4})})]})]})}),Pane3=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react122=__toESM(require_react_production(),1);var import_react115=__toESM(require_react_production(),1);import{existsSync as existsSync23}from"fs";import{basename as basename11}from"path";var import_react107=__toESM(require_react_production(),1);var PathPrompt=(props)=>{let theme=useTheme().theme,[value2,setValue]=import_react107.useState(props.initial??""),[items,setItems]=import_react107.useState([]),seq=import_react107.useRef(0),ok=(it)=>it.meta==="dir"||!props.filter||props.filter.test(it.text);return import_react107.useEffect(()=>{if(!value2.trim()){setItems([]);return}let me2=++seq.current,t2=setTimeout(()=>{props.gw.request("complete.path",{word:value2}).then((r)=>{if(seq.current===me2)setItems((r.items??[]).filter(ok).slice(0,5))}).catch(()=>{if(seq.current===me2)setItems([])})},120);return()=>clearTimeout(t2)},[value2,props.gw]),useKeyboard((key3)=>{if(key3.name!=="tab")return;key3.preventDefault();let hit=items[0];if(hit)setValue(hit.text)}),$jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value:value2,onInput:setValue,onSubmit:()=>{let v2=value2.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),items.length>0?items.map((it)=>$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:it.text})}),it.meta?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:` ${it.meta}`})}):null]},it.text)):null,items.length>0?$jsx("box",{height:1}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value2.trim()?`Tab complete \xB7 Enter confirm \xB7 Esc cancel${items.length>0?` \xB7 ${items.length} match${items.length===1?"":"es"}`:""}`:"Type a path \xB7 Esc cancel"})})]})};function openPathPrompt(dialog,gw,opts){return new Promise((resolve4)=>{dialog.replace($jsx(PathPrompt,{title:opts.title,label:opts.label,initial:opts.initial,filter:opts.filter,gw,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var import_react109=__toESM(require_react_production(),1);var BASE=`
|
|
4127
|
+
`).map((s)=>s.trim()).filter((s)=>s.length>0&&!s.startsWith("(")),shq2=(s)=>/^[A-Za-z0-9._-]+$/.test(s)?s:`'${s.replace(/'/g,"'\\''")}'`,CuratorDialog=()=>{let{theme,syntaxStyle}=useTheme(),gw=useGateway(),toast=useToast(),dialog=useDialog(),state3=useHome("curatorState"),cfg=useHome("config")?.curator,[report2,setReport]=import_react98.useState(null),[loaded,setLoaded]=import_react98.useState(!1),[busy2,setBusy]=import_react98.useState(null),busyRef=import_react98.useRef(null),[archived,setArchived]=import_react98.useState([]),[mode,setMode]=import_react98.useState("report"),[sel,setSel]=import_react98.useState(0),sb=import_react98.useRef(null);import_react98.useEffect(()=>{readLatestCuratorReport().then((r)=>{setReport(r),setLoaded(!0)}).catch(()=>setLoaded(!0))},[]);let refreshArchived=import_react98.useCallback(()=>{gw.request("shell.exec",{command:"hermes curator list-archived"}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());setArchived(parseList(r.stdout))}).catch((e)=>toast.show({variant:"error",message:trunc5(e instanceof Error?e.message:String(e),120)}))},[gw,toast]);import_react98.useEffect(()=>{refreshArchived()},[refreshArchived]);let sh=import_react98.useCallback((verb,ok)=>{if(busyRef.current)return;busyRef.current=verb,setBusy(verb),gw.request("shell.exec",{command:`hermes curator ${verb}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:ok}),home2.invalidate("curatorState")}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>{busyRef.current=null,setBusy(null)})},[gw,toast]),restore=import_react98.useCallback((name)=>{if(busyRef.current)return;busyRef.current="restore",setBusy("restore"),gw.request("shell.exec",{command:`hermes curator restore ${shq2(name)}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:`Restored ${name}`}),setArchived((prev)=>prev.filter((n)=>n!==name)),setSel((s)=>Math.max(0,s-1))}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>{busyRef.current=null,setBusy(null)})},[gw,toast]);useKeyboard((key3)=>{if(mode==="archived"){if(key3.name==="escape"){setMode("report");return}if(key3.raw==="a"){setMode("report");return}if(key3.name==="up")return setSel((s)=>Math.max(0,s-1));if(key3.name==="down")return setSel((s)=>Math.min(archived.length-1,s+1));if(key3.name==="return"){let name=archived[sel];if(name)restore(name);return}return}if(key3.name==="escape")return dialog.clear();if(key3.raw==="r")return sh("run","Curator run started (background)");if(key3.raw==="p")return state3?.paused?sh("resume","Curator resumed"):sh("pause","Curator paused");if(key3.raw==="a"&&archived.length>0)setSel(0),setMode("archived")}),import_react98.useEffect(()=>{if(mode==="archived")sb.current?.scrollChildIntoView(`arch-${sel}`)},[sel,mode]);let last4=iso2(state3?.last_run_at??null),due=last4&&cfg?last4+cfg.interval_hours*3600:null,status=cfg?.enabled===!1?"disabled":state3?.paused?"paused":"enabled",tint=status==="enabled"?theme.success:status==="paused"?theme.warning:theme.textMuted;return $jsxs("box",{flexDirection:"column",width:120,height:34,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Curator"})}),$jsx("span",{fg:tint,children:` \xB7 ${status}`})]}),busy2?$jsx("box",{marginLeft:2,children:$jsx(Spinner,{color:theme.textMuted,label:busy2})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:state3?`${state3.run_count} run${state3.run_count===1?"":"s"}${last4?" \xB7 last "+ago(last4):" \xB7 never"} \xB7 Esc to close`:"No curator state yet \xB7 Esc to close"})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:40,height:"100%",flexShrink:0,children:[$jsx(KVBlock,{rows:[["Next run",status!=="enabled"?`\u2014 (${status})`:due?until(due):"when idle"],["Last run",last4?ago(last4):"never"],["Duration",state3?.last_run_duration_seconds?dur2(state3.last_run_duration_seconds):void 0],["Archived",archived.length>0?String(archived.length):void 0]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Config \xB7 edit in Config tab"})}),$jsx(KVBlock,{rows:[["Interval",cfg?`${cfg.interval_hours}h`:"\u2014"],["Stale after",cfg?`${cfg.stale_after_days}d`:"\u2014"],["Archive after",cfg?`${cfg.archive_after_days}d`:"\u2014"]]}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"r "}),$jsx("span",{fg:theme.text,children:"run now"}),$jsx("span",{fg:theme.textMuted,children:" (background)"})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"p "}),$jsx("span",{fg:theme.text,children:state3?.paused?"resume":"pause"})]})}),archived.length>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"a "}),$jsx("span",{fg:theme.text,children:"archived skills"}),$jsx("span",{fg:theme.textMuted,children:` (${archived.length})`})]})}):null]}),state3?.last_run_summary?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Last run"})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("markdown",{content:state3.last_run_summary,fg:theme.markdownText,syntaxStyle})})]}):null]}),mode==="archived"?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Archived skills (${archived.length})`})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191\u2193 select \xB7 Enter restore \xB7 a/Esc back to report"})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,contentOptions:{flexDirection:"column"},children:archived.length===0?$jsx("text",{fg:theme.textMuted,children:"No archived skills."}):archived.map((name,i)=>$jsx("box",{id:`arch-${i}`,height:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>restore(name),children:$jsxs("text",{fg:i===sel?theme.text:theme.textMuted,children:[i===sel?"\u25B8 ":" ",name]})},name))})]}):!loaded?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading report\u2026"})}):report2?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Report \xB7 ${report2.runId}`})})}),$jsx(KVLink,{label:"File",source:report2.source,text:report2.source.relative}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx("markdown",{content:report2.content||"(empty)",fg:theme.markdownText,syntaxStyle})})})]}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No runs yet \u2014 curator has not completed a cycle."})})]})]})},openCurator=(dialog)=>dialog.replace($jsx(CuratorDialog,{}),void 0,{ownCancel:!0});var NO_EVENTS=[],meta=(hit)=>{let parts2=[];if(hit.identifier)parts2.push(hit.identifier);if(hit.source)parts2.push(hit.source);if(hit.trust_level)parts2.push(hit.trust_level);return parts2.join(" \xB7 ")},iso3=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},SkillRow=import_react100.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,bg2=props.selected?theme.backgroundElement:void 0,used=iso3(u3?.last_used_at)??iso3(u3?.last_viewed_at),stale=u3?.state==="stale",archived=u3?.state==="archived";return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:theme.warning,children:u3?.pinned?"\uD83D\uDCCC":" "}),$jsx(Marquee,{grow:!0,min:8,active:props.selected,fg:archived?theme.textMuted:props.selected?theme.accent:theme.text,children:s.name}),archived?$jsx(Col,{w:10,fg:theme.textMuted,children:"archived"}):stale?$jsx(Col,{w:10,fg:theme.warning,children:"stale"}):$jsx(Col,{w:10,fg:theme.textMuted,children:used?ago(used):""})]})}),HitRow=import_react100.memo((props)=>{let theme=useTheme().theme,on=props.selected,info2=meta(props.hit);return $jsxs("box",{flexDirection:"column",minHeight:info2?2:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onSelect,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:on?theme.accent:theme.text,children:props.hit.name}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,children:props.hit.description||"\u2014"})]}),info2?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.info,children:info2})]}):null]})}),bycat=(skills)=>skills.reduce((map,s)=>{let cat=s.category||"uncategorized";return map.set(cat,[...map.get(cat)??[],s]),map},new Map),line3=(e)=>{switch(e.kind){case"absorbed":return`absorbed ${e.sources.map((s)=>`\`${s}\``).join(", ")}`;case"merged":return`merged into \`${e.into}\`${e.reason?` \u2014 ${e.reason}`:""}`;case"transition":return`${e.from} \u2192 ${e.to}`;case"pruned":return`pruned${e.reason?` \u2014 ${e.reason}`:""}`;case"added":return"created by curator"}},DetailPanel2=import_react100.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,used=iso3(u3?.last_used_at),viewed=iso3(u3?.last_viewed_at),patched=iso3(u3?.last_patched_at);return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Detail"})}),u3?.pinned?$jsx("span",{fg:theme.warning,children:" \uD83D\uDCCC pinned"}):null,u3?.state==="stale"?$jsx("span",{fg:theme.warning,children:" \xB7 stale"}):null,u3?.state==="archived"?$jsx("span",{fg:theme.textMuted,children:" \xB7 archived"}):null]})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:s.name})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Category",s.category||"uncategorized",theme.info],["Tags",s.tags.length>0?s.tags.join(", "):void 0],u3?["Used",u3.use_count>0?`${u3.use_count}\xD7 \xB7 last ${used?ago(used):"never"}`:"never"]:null,u3&&viewed?["Viewed",`${u3.view_count}\xD7 \xB7 last ${ago(viewed)}`]:null,u3&&patched?["Patched",`${u3.patch_count}\xD7 \xB7 last ${ago(patched)}`]:null].filter(Boolean)}),$jsx(KVLink,{label:"File",source:s.source,text:s.source.relative}),$jsx("box",{height:1}),s.description?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:s.description})}):$jsx("text",{fg:theme.textMuted,children:"No description"}),props.events.length>0?$jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Curator lineage"})}),props.events.map((e,i)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:ago(e.at)})}),$jsx("box",{flexGrow:1,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:line3(e)})})]},i))]}):u3?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No curator events for this skill"})}):null]})}),EmptyState=import_react100.memo((props)=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:props.searching?"No matching skills on hub":"No skills found in ~/.hermes/skills/"})})})}),HistoryPanel=import_react100.memo((props)=>{let{theme,syntaxStyle}=useTheme(),dialog=useDialog(),keys=useKeys(),follow=useFollow("skills-history"),[runs,setRuns]=import_react100.useState(()=>listCuratorRuns()),[sel,setSel]=import_react100.useState(0),[open3,setOpen]=import_react100.useState(!1),[body,setBody]=import_react100.useState(""),run=runs[sel];import_react100.useEffect(()=>{if(!open3||!run)return;let live=!0;return readCuratorReport(run.id).then((t2)=>{if(live)setBody(t2)}),()=>{live=!1}},[open3,run?.id]);let moveSel=import_react100.useCallback((v2)=>{setOpen(!1),setSel(v2)},[]);return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;handleListKey(keys,key3,{count:runs.length,setSel:moveSel,...follow.opts,onActivate:()=>setOpen((o)=>!o),onRefresh:()=>setRuns(listCuratorRuns())})}),$jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:props.focused?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Curator History"})}),$jsx("span",{fg:theme.textMuted,children:` ${runs.length} run${runs.length===1?"":"s"}${runs[0]?` \xB7 last ${ago(runs[0].at)}`:""}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select \xB7 Enter expand \xB7 ${keys.print("list.refresh")} reload \xB7 h close`})}),$jsx("box",{height:1}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:"no runs in ~/.hermes/logs/curator/"}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:runs.map((r,i)=>{let on=i===sel;return $jsxs("box",{id:follow.id(i),flexDirection:"column",children:[$jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),setOpen((o)=>i===sel?!o:!0)},children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:12,fg:on?theme.accent:theme.text,children:ago(r.at)}),$jsx(Col,{grow:!0,fg:theme.textMuted,children:`${r.before}\u2192${r.after} arch ${r.archived} cons ${r.consolidated}${r.added?` +${r.added}`:""}`})]}),on&&open3?$jsx("box",{marginLeft:2,marginTop:1,marginBottom:1,children:$jsx("markdown",{content:body||"\u2026",fg:theme.markdownText,syntaxStyle})}):null]},r.id)})})})]})}),Skills=import_react100.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),usage=useHome("skillUsage")??{},curator=useHome("curatorState"),lineage2=import_react100.useRef(indexCuratorLineage());import_react100.useEffect(()=>{lineage2.current=indexCuratorLineage()},[curator?.run_count]);let[skills,setSkills]=import_react100.useState([]),[selected,setSelected]=import_react100.useState(0),[searching,setSearching]=import_react100.useState(!1),[query2,setQuery]=import_react100.useState(""),[hits,setHits]=import_react100.useState([]),[sort,setSort]=import_react100.useState("name"),[history,setHistory]=import_react100.useState(!1),seq=import_react100.useRef(0),listSeq=import_react100.useRef(0),load4=import_react100.useCallback(()=>{let id=++listSeq.current;gw.request("skills.manage",{action:"list"}).then((res)=>{if(listSeq.current!==id)return;let raw=res.skills??{},rows3=Object.entries(raw).flatMap(([cat,names])=>names.map((n)=>{let source=makeSource(`skills/${cat}/${n}/SKILL.md`,`${n}/SKILL.md`),fm=readSkillFrontmatter(source);return{source,category:cat,name:n,description:fm.description,tags:fm.tags,tokenEstimate:count2(`${n} ${fm.description}`)}}));rows3.sort((a,b2)=>a.source.relative.localeCompare(b2.source.relative)),setSkills(rows3)}).catch((err)=>{if(listSeq.current===id)toast.show({variant:"error",message:err.message})})},[gw,toast]);import_react100.useEffect(()=>{return load4(),()=>{listSeq.current++}},[load4]),import_react100.useEffect(()=>{let id=++seq.current;if(!searching||!query2.trim()){setHits([]);return}let t2=setTimeout(()=>{gw.request("skills.manage",{action:"search",query:query2}).then((r)=>{if(seq.current!==id)return;setHits(r.results??[]),setSelected(0)}).catch((err)=>{if(seq.current!==id)return;setHits([]),toast.show({variant:"error",message:err.message})})},150);return()=>clearTimeout(t2)},[gw,toast,query2,searching]);let flat=[...sort==="used"?new Map([["by recency",[...skills].sort((a,b2)=>{let ta=iso3(usage[a.name]?.last_used_at)??iso3(usage[a.name]?.last_viewed_at)??0;return(iso3(usage[b2.name]?.last_used_at)??iso3(usage[b2.name]?.last_viewed_at)??0)-ta})]]):bycat(skills)].flatMap(([cat,items])=>[{type:"header",category:cat},...items.map((s)=>({type:"skill",skill:s}))]),skillRows=flat.filter((r)=>r.type==="skill"),count3=searching?hits.length:skillRows.length,current=!searching&&skillRows[selected]?.type==="skill"?skillRows[selected].skill:null,follow=useFollow("sk"),exit=import_react100.useCallback(()=>{setSearching(!1),setQuery(""),setHits([]),setSelected(0)},[]),install2=import_react100.useCallback(async(hit)=>{let query3=hit.identifier??hit.name;if(!await openConfirm(dialog,{title:"Install skill?",body:query3,yes:"install"}))return;gw.request("skills.manage",{action:"install",query:query3}).then(()=>{toast.show({variant:"success",message:`Installed ${query3}`}),exit(),load4()}).catch((e)=>toast.show({variant:"error",message:`Install failed: ${e.message}`}))},[dialog,gw,toast,exit,load4]),keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){exit();return}if(key3.name==="backspace"){setQuery((p)=>p.slice(0,-1)),setSelected(0);return}if(key3.name==="up")return setSelected((p)=>Math.max(0,p-1));if(key3.name==="down")return setSelected((p)=>Math.min(count3-1,p+1));if(key3.name==="return"){let hit=hits[selected];if(hit)install2(hit);return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" ")setQuery((p)=>p+key3.raw),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="s"){setSort((p)=>p==="name"?"used":"name"),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="c"){openCurator(dialog);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="h"){setHistory((h2)=>!h2);return}if(history){if(key3.name==="escape")return setHistory(!1);return}handleListKey(keys,key3,{count:count3,setSel:setSelected,...follow.opts,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onSearch:()=>{setSearching(!0),setQuery(""),setHits([]),setSelected(0)}})});let skillIdx=-1;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Hub Search (${hits.length})`:`Skills (${skills.length}${sort==="used"?" \xB7 by use":""})`,children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query2}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,searching?null:$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,bold:!0,children:"Name"})]}),searching?null:$jsx("box",{height:1}),count3===0?$jsx(EmptyState,{searching}):searching?$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:hits.map((h2,i)=>$jsx(HitRow,{hit:h2,selected:i===selected,onHover:()=>setSelected(i),onSelect:()=>install2(h2)},h2.identifier??h2.name))})}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:flat.map((row3,i)=>{if(row3.type==="header")return $jsx("box",{marginTop:i>0?1:0,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE ${row3.category}`})})},`h-${row3.category}`);skillIdx++;let idx=skillIdx;return $jsx(SkillRow,{id:follow.id(idx),skill:row3.skill,usage:usage[row3.skill.name],selected:idx===selected,onSelect:()=>setSelected(idx),onHover:()=>setSelected(idx)},row3.skill.name)})}),!searching&&curator?$jsx("box",{height:1,flexShrink:0,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"curator \xB7 "}),curator.paused?$jsx("span",{fg:theme.warning,children:"paused"}):curator.last_run_at?$jsx("span",{fg:theme.textMuted,children:`${curator.run_count} run${curator.run_count===1?"":"s"} \xB7 last ${ago(iso3(curator.last_run_at)??0)}`}):$jsx("span",{fg:theme.textMuted,children:"never run"})]})}):null]}),history?$jsx(HistoryPanel,{focused:!!props.focused&&!searching}):current?$jsx(DetailPanel2,{skill:current,usage:usage[current.name],events:lineage2.current.get(current.name)??NO_EVENTS}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter","install"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],[keys.print("list.search"),"search hub"],["s","sort"],["c","curator"],["h","history"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react102=__toESM(require_react_production(),1);var kindOf=(ts)=>ts.name.includes(":")?"mcp":ts.name.startsWith("hermes-")?"platform":"core",KIND_LABEL={core:"core",platform:"platform bundles",mcp:"mcp"},group2=(list2)=>{let by={core:[],platform:[],mcp:[]};for(let ts of list2)by[kindOf(ts)].push(ts);return["core","platform","mcp"].filter((k2)=>by[k2].length>0).map((k2)=>({kind:k2,items:by[k2]}))},Row3=import_react102.memo((props)=>{let theme=useTheme().theme,ts=props.ts,bg2=props.selected?theme.backgroundElement:void 0,unavail=ts.available===!1,glyph=unavail?"\u25CC":ts.enabled?"\u25CF":"\u25CB",glyphFg=unavail?theme.warning:ts.enabled?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphFg,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:ts.name}),$jsx(Col,{w:9,fg:theme.info,right:!0,children:`${ts.tool_count} tools`})]})}),DetailPanel3=import_react102.memo((props)=>{let theme=useTheme().theme,ts=props.ts,unavail=ts.available===!1;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"40%",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:ts.name})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:KIND_LABEL[kindOf(ts)]})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",unavail?"unavailable":ts.enabled?"enabled":"disabled",unavail?theme.warning:ts.enabled?theme.success:theme.textMuted],["Tools",String(ts.tool_count),theme.info],["Includes",ts.includes?.length?ts.includes.join(", "):void 0,theme.text],["Requires",ts.requirements?.length?ts.requirements.join(", "):void 0,unavail?theme.warning:theme.text]]}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:ts.description||"\u2014"})}),ts.tools?.length?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Tools (",ts.tools.length,"):"]})}),$jsx("scrollbox",{flexGrow:1,scrollY:!0,children:ts.tools.map((n)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",n]},n))})]}):null]})}),Toolsets=import_react102.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),[list2,setList]=import_react102.useState([]),[sel,setSel]=import_react102.useState(0),[err,setErr]=import_react102.useState(null),rev=import_react102.useRef(0),loads=import_react102.useRef(0),writes=import_react102.useRef(Promise.resolve()),known=import_react102.useRef(new Map),secs=group2(list2),flat=secs.flatMap((s)=>s.items),live=import_react102.useRef({flat,sel});live.current={flat,sel};let load4=import_react102.useCallback(()=>{let gen=++loads.current;gw.request("toolsets.list",{}).then((r)=>{if(loads.current!==gen)return;let next2=r.toolsets??[];known.current=new Map(next2.map((t2)=>[t2.name,t2.enabled])),setList(next2),setErr(null)}).catch((e)=>{if(loads.current===gen)setErr(e instanceof Error?e.message:String(e))})},[gw]);import_react102.useEffect(()=>{return load4(),()=>{rev.current++,loads.current++}},[load4]);let toggle=import_react102.useCallback(()=>{let ts2=live.current.flat[live.current.sel];if(!ts2)return;if(ts2.available===!1){toast.show({variant:"warning",message:`${ts2.name} is unavailable`});return}let enabled2=!ts2.enabled,action=enabled2?"enable":"disable",gen=++rev.current;loads.current++,live.current={...live.current,flat:live.current.flat.map((t2)=>t2.name===ts2.name?{...t2,enabled:enabled2}:t2)},setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:enabled2}:t2)),writes.current=writes.current.then(async()=>{try{let r=await gw.request("tools.configure",{action,names:[ts2.name]}),authoritative=Array.isArray(r.enabled_toolsets)?new Set(r.enabled_toolsets):null;if(authoritative)known.current=new Map(live.current.flat.map((t2)=>[t2.name,authoritative.has(t2.name)]));if(rev.current!==gen)return;if(r.unknown?.includes(ts2.name)){setList((prev)=>prev.map((t2)=>({...t2,enabled:known.current.get(t2.name)??t2.enabled}))),toast.show({variant:"warning",message:`${ts2.name} is not configurable`});return}if(r.missing_servers?.length&&ts2.name.includes(":")){let server=ts2.name.split(":",1)[0];if(r.missing_servers.includes(server)){setList((prev)=>prev.map((t2)=>({...t2,enabled:known.current.get(t2.name)??t2.enabled}))),toast.show({variant:"warning",message:`MCP server '${server}' not in config`});return}}if(authoritative)setList((prev)=>prev.map((t2)=>({...t2,enabled:authoritative.has(t2.name)})));else load4()}catch(e){if(rev.current!==gen)return;setList((prev)=>prev.map((t2)=>({...t2,enabled:known.current.get(t2.name)??t2.enabled}))),toast.show({variant:"error",message:e instanceof Error?e.message:String(e)})}})},[gw,toast,load4]),count3=flat.length,ts=flat[sel]??null,follow=useFollow("ts"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:count3,setSel,...follow.opts,onToggle:toggle,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})}});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:`Toolsets (${count3})`,error:err,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:9,fg:theme.textMuted,bold:!0,right:!0,children:"Tools"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:"No toolsets found"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{return acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",KIND_LABEL[s.kind]," (",s.items.length,") "]})},`\xA7${s.kind}`)),s.items.forEach((t2,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(Row3,{id:follow.id(i),ts:t2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},t2.name))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]}),ts?$jsx(DetailPanel3,{ts}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.toggle"),"toggle"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react103=__toESM(require_react_production(),1);var mask=(val)=>"\u2022".repeat(Math.min(val.length,12)),VarRow=import_react103.memo((props)=>{let theme=useTheme().theme,set3=props.value!==void 0,bg2=props.selected?theme.backgroundElement:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onClick,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:props.selected?theme.accent:theme.text,children:props.name}),$jsx(Col,{w:8,fg:set3?theme.success:theme.textMuted,children:set3?" SET ":"UNSET"}),$jsx(Col,{grow:!0,min:4,fg:props.shown?theme.text:theme.textMuted,children:set3?props.shown?props.value:mask(props.value):"\u2014"})]})}),Env=import_react103.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),vars=useHome("env")??{},[sel,setSel]=import_react103.useState(0),[reveal,setReveal]=import_react103.useState(new Set),[collapsed,setCollapsed]=import_react103.useState({}),[searching,setSearching]=import_react103.useState(!1),[query2,setQuery]=import_react103.useState(""),known=new Set(ENV_CATALOG.flatMap((g)=>g.keys)),extra=Object.keys(vars).filter((k2)=>!known.has(k2)).sort(),rows3=(extra.length>0?[...ENV_CATALOG,{category:"Other",keys:extra}]:ENV_CATALOG).flatMap((g)=>{let keys2=searching&&query2.trim()?g.keys.filter((k2)=>k2.toLowerCase().includes(query2.toLowerCase())):g.keys;if(keys2.length===0)return[];let hide=collapsed[g.category]??!1,header={type:"header",category:g.category,collapsed:hide};if(hide)return[header];return[header,...keys2.map((key3)=>({type:"var",key:key3,value:vars[key3]}))]}),count3=rows3.length,cur=rows3[sel],setKeys=rows3.flatMap((r)=>r.type==="var"&&r.value!==void 0?[r.key]:[]),follow=useFollow("env"),edit=import_react103.useCallback(async(key3,initial)=>{let val=await openTextPrompt(dialog,{title:`Edit ${key3}`,label:"Value",initial});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} saved`})},[dialog,toast]),add=import_react103.useCallback(async()=>{let key3=await openTextPrompt(dialog,{title:"New Variable",label:"Name (e.g. FOO_API_KEY)"});if(!key3)return;let val=await openTextPrompt(dialog,{title:`Set ${key3}`,label:"Value"});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} added`})},[dialog,toast]),del=import_react103.useCallback(async(key3)=>{if(!await openConfirm(dialog,{title:"Delete Variable",body:`Remove ${key3} from .env?`,yes:"delete",danger:!0}))return;await removeEnvVar(key3),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} removed`})},[dialog,toast]),revealAll=import_react103.useCallback(()=>setReveal((s)=>s.size===setKeys.length&&setKeys.length>0?new Set:new Set(setKeys)),[setKeys]),activateAt=import_react103.useCallback((i)=>{let r=rows3[i];if(r?.type==="header")return setCollapsed((p)=>({...p,[r.category]:!p[r.category]}));if(r?.type==="var"){if(r.value!==void 0&&!reveal.has(r.key))return setReveal((s)=>new Set(s).add(r.key));return void edit(r.key,r.value??"")}},[rows3,reveal,edit]),activate=import_react103.useCallback(()=>activateAt(sel),[activateAt,sel]),rowClick=import_react103.useCallback((i)=>{setSel(i),activateAt(i)},[activateAt]),keys=useKeys();return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setSel(0);return}if(key3.name==="backspace"){setQuery((q4)=>q4.slice(0,-1)),setSel(0);return}if(key3.name==="up")return setSel((p)=>Math.max(0,p-1));if(key3.name==="down")return setSel((p)=>Math.min(count3-1,p+1));if(key3.name==="return")return setSearching(!1),activate();if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setQuery((q4)=>q4+key3.raw),setSel(0);return}return}handleListKey(keys,key3,{count:count3,setSel,...follow.opts,onActivate:activate,onToggle:revealAll,onNew:add,onDelete:()=>{if(cur?.type==="var"&&cur.value!==void 0)del(cur.key)},onSearch:()=>{setSearching(!0),setQuery(""),setSel(0)},onRefresh:()=>{home2.invalidate("env"),toast.show({variant:"info",message:"Reloaded",duration:1000})}})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:searching?"Env (searching)":"Env / API Keys",children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query2}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:28,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:8,fg:theme.textMuted,bold:!0,children:"Status"}),$jsx(Col,{grow:!0,min:4,fg:theme.textMuted,bold:!0,children:"Value"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching variables":"No variables configured"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((row3,i)=>row3.type==="header"?$jsx("box",{id:follow.id(i),marginTop:i>0?1:0,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>rowClick(i),children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`${row3.collapsed?"\u25B8":"\u25BE"} ${row3.category}`})})},`h-${row3.category}`):$jsx(VarRow,{id:follow.id(i),name:row3.key,value:row3.value,shown:reveal.has(row3.key),selected:i===sel,onHover:()=>setSel(i),onClick:()=>rowClick(i)},row3.key))})},"list")]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","move"],["Enter","reveal/edit"],["Esc","cancel"]]:[["\u2191\u2193","move"],[keys.print("list.activate"),"reveal/edit"],[keys.print("list.toggle"),"show-all"],[keys.print("list.new"),"new"],[keys.print("list.delete"),"delete"],[keys.print("list.search"),"search"],[keys.print("list.refresh"),"reload"]]})]})});var import_react105=__toESM(require_react_production(),1);function usageColor(pct,theme){if(pct>=95)return theme.error;if(pct>=80)return theme.warning;return theme.success}function bar2(pct,w2){let filled=Math.round(pct/100*w2);return"\u2588".repeat(filled)+"\u2591".repeat(w2-filled)}var DESC={builtin:"File-based \xA7-delimited entries (MEMORY.md + USER.md). Always active.",mem0:"Server-side LLM fact extraction with semantic search and reranking.",honcho:"AI-native cross-session user modeling with dialectic Q&A.",hindsight:"Knowledge graph with entity resolution and multi-strategy retrieval.",holographic:"Local SQLite fact store with FTS5, trust scoring, HRR retrieval.",openviking:"Session-managed memory with tiered retrieval.",retaindb:"Cloud memory API with hybrid search and 7 memory types.",byterover:"Persistent knowledge tree via brv CLI.",supermemory:"Semantic long-term memory with profile recall and session ingest."},Memory=import_react105.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),gw=useGateway(),[sel,setSel]=import_react105.useState(0),config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),providers=useHome("memoryProviders")??[],activity=useHome("memoryActivity")??[],cfg=config?.memory,active=cfg?.provider||"",cur=providers[sel],on=!!cur&&(cur.name==="builtin"||cur.name===active),toggle=async()=>{if(!cur||cur.name==="builtin")return;let isOn=cur.name===active;if(!await openConfirm(dialog,{title:isOn?"Deactivate memory provider?":"Activate memory provider?",body:isOn?`Clear '${cur.name}' as the active provider (revert to built-in only).`:`Set '${cur.name}' as the active provider. Ensure required env vars are set (Env tab).`,yes:isOn?"deactivate":"activate"}))return;let{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"memory.provider",to:isOn?"":cur.name}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),home2.invalidate("memoryProviders"),toast.show({variant:"success",message:isOn?"Deactivated":`Activated ${cur.name} \u2014 new sessions pick this up`})},keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:providers.length,setSel,onToggle:toggle,onRefresh:()=>{home2.invalidate("memoryProviders"),home2.invalidate("memoryActivity"),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),feed=!cur?[]:cur.name==="builtin"?activity:activity.filter((a)=>a.provider===cur.name);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:"Memory Providers",grow:1,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:providers.map((p,i)=>{let pOn=p.name==="builtin"||p.name===active,has2=Object.keys(p.config).length>0,dot=pOn?"\u25CF":has2?"\u25D0":"\u25CB",fg2=pOn?theme.success:has2?theme.warning:theme.textMuted,tag=pOn?"active":has2?"configured":"";return $jsxs("box",{flexDirection:"column",marginBottom:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseDown:()=>setSel(i),onMouseMove:()=>setSel(i),children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[dot," "]}),$jsx("span",{fg:i===sel?theme.accent:theme.text,children:p.name}),tag?$jsxs("span",{fg:fg2,children:[" (",tag,")"]}):null]})}),$jsx("box",{height:1,overflow:"hidden",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:DESC[p.name]||"\u2014"})})]},p.name)})})}),$jsx(TabShell,{title:cur?.name??"Provider",grow:2,children:cur?$jsx(ProviderDetail,{provider:cur,active,cfg,memory,userProfile,feed}):$jsx("text",{fg:theme.textMuted,children:"Select a provider"})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.toggle"),"activate"]],suffix:on?"\u25CF active":"\u25CB inactive"})]})}),ProviderDetail=import_react105.memo((props)=>{let theme=useTheme().theme,p=props.provider,on=p.name==="builtin"||p.name===props.active;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:DESC[p.name]||"Memory provider"})}),$jsx("box",{height:1}),p.name==="builtin"?$jsxs("box",{flexDirection:"column",children:[props.cfg?$jsxs($Fragment,{children:[$jsx(KVBlock,{rows:[["Notes",props.cfg.memory_enabled?"enabled":"disabled",props.cfg.memory_enabled?theme.success:theme.error],["Profile",props.cfg.user_profile_enabled?"enabled":"disabled",props.cfg.user_profile_enabled?theme.success:theme.error]]}),$jsx("box",{height:1})]}):null,$jsx(CapacityBar,{title:"Notes (MEMORY.md)",info:props.memory??null}),$jsx("box",{height:1}),$jsx(CapacityBar,{title:"Profile (USER.md)",info:props.userProfile??null})]}):null,p.name!=="builtin"&&on&&props.cfg?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Agent Settings"})})}),$jsx(KVBlock,{rows:[["Nudge",`every ${props.cfg.nudge_interval} turns`],["Flush",`after ${props.cfg.flush_min_turns} turns`]]}),$jsx("box",{height:1})]}):null,Object.keys(p.config).length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Local Configuration"})})}),$jsx(KVBlock,{rows:Object.entries(p.config).map(([k2,v2])=>[k2,String(v2)])})]}):p.name!=="builtin"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No local config found. Run `hermes memory setup` to configure."})}):null,$jsx(ActivityFeed,{items:props.feed,own:p.name})]})})}),OP_GLYPH={write:"+",read:"?"},ActivityFeed=import_react105.memo((props)=>{let theme=useTheme().theme,all=props.own==="builtin",nW=props.items.filter((a)=>a.op==="write").length;return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"Recent Activity"})}),props.items.length?$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",nW," writes, ",props.items.length-nW," reads"]}):null]})}),props.items.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No memory-tool calls in the last ~2000 messages"})}):null,props.items.map((a,i)=>$jsx("box",{height:1,flexDirection:"row",overflow:"hidden",children:$jsxs("text",{children:[$jsxs("span",{fg:a.op==="write"?theme.success:theme.textMuted,children:[OP_GLYPH[a.op]," "]}),$jsx("span",{fg:theme.textMuted,children:ago(a.ts).padEnd(8)}),all&&a.provider!=="builtin"?$jsxs("span",{fg:theme.primary,children:[a.provider,"\xB7"]}):null,$jsx("span",{fg:theme.text,children:a.verb}),$jsxs("span",{fg:theme.textMuted,children:[" ",a.summary]})]})},i))]})}),CapacityBar=import_react105.memo((props)=>{let theme=useTheme().theme;if(!props.info)return $jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.title,": unavailable"]})});let color=usageColor(props.info.usagePercent,theme);return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:props.title}),$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",props.info.entryCount," entries"]})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:color,children:bar2(props.info.usagePercent,20)}),$jsxs("span",{fg:theme.textMuted,children:[" ",props.info.charCount,"/",props.info.charLimit," (",props.info.usagePercent,"%)"]})]})})]})});var ConfigGroup=import_react106.memo((props)=>{let labels=SUB_TABS[CONFIG_TAB];import_react106.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane3,{visible:props.sub===0,children:$jsx(Config2,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane3,{visible:props.sub===1,children:$jsx(Skills,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane3,{visible:props.sub===2,children:$jsx(Toolsets,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane3,{visible:props.sub===3,children:$jsx(Env,{focused:!!props.focused&&props.sub===3})}),$jsx(Pane3,{visible:props.sub===4,children:$jsx(Memory,{focused:!!props.focused&&props.sub===4})})]})]})}),Pane3=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react122=__toESM(require_react_production(),1);var import_react115=__toESM(require_react_production(),1);import{existsSync as existsSync23}from"fs";import{basename as basename11}from"path";var import_react107=__toESM(require_react_production(),1);var PathPrompt=(props)=>{let theme=useTheme().theme,[value2,setValue]=import_react107.useState(props.initial??""),[items,setItems]=import_react107.useState([]),seq=import_react107.useRef(0),ok=(it)=>it.meta==="dir"||!props.filter||props.filter.test(it.text);return import_react107.useEffect(()=>{if(!value2.trim()){setItems([]);return}let me2=++seq.current,t2=setTimeout(()=>{props.gw.request("complete.path",{word:value2}).then((r)=>{if(seq.current===me2)setItems((r.items??[]).filter(ok).slice(0,5))}).catch(()=>{if(seq.current===me2)setItems([])})},120);return()=>clearTimeout(t2)},[value2,props.gw]),useKeyboard((key3)=>{if(key3.name!=="tab")return;key3.preventDefault();let hit=items[0];if(hit)setValue(hit.text)}),$jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value:value2,onInput:setValue,onSubmit:()=>{let v2=value2.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),items.length>0?items.map((it)=>$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:it.text})}),it.meta?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:` ${it.meta}`})}):null]},it.text)):null,items.length>0?$jsx("box",{height:1}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value2.trim()?`Tab complete \xB7 Enter confirm \xB7 Esc cancel${items.length>0?` \xB7 ${items.length} match${items.length===1?"":"es"}`:""}`:"Type a path \xB7 Esc cancel"})})]})};function openPathPrompt(dialog,gw,opts){return new Promise((resolve4)=>{dialog.replace($jsx(PathPrompt,{title:opts.title,label:opts.label,initial:opts.initial,filter:opts.filter,gw,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var import_react109=__toESM(require_react_production(),1);var BASE=`
|
|
4128
4128
|
high contrast, light subject on dark, black background`,BINDS=[{name:"return",action:"submit"},{name:"return",shift:!0,action:"newline"}],Generate=(props)=>{let theme=useTheme().theme,ta=import_react109.useRef(null),flight=import_react109.useRef(!1),[prompt,setPrompt]=import_react109.useState(props.lastPrompt??BASE),[useSeed,setUseSeed]=import_react109.useState(!!props.seed),[secs,setSecs]=import_react109.useState(2),[busy2,setBusy]=import_react109.useState(!1),[err,setErr]=import_react109.useState(null),[field,setField]=import_react109.useState("prompt");import_react109.useEffect(()=>{ta.current?.setCursor(0,0)},[]);let fields=props.kind==="video"?props.seed?["prompt","seed","seconds","submit"]:["prompt","seconds","submit"]:props.seed?["prompt","seed","submit"]:["prompt","submit"],advance=()=>setField((f)=>fields[(fields.indexOf(f)+1)%fields.length]),submit2=()=>{let p=prompt.trim(),bare=!props.lastPrompt&&p===BASE.trim();if(!p||bare||flight.current){if(bare)setErr("describe the subject on line 1");return}flight.current=!0,setBusy(!0),setErr(null),props.run(props.kind,p,{seed:props.seed&&useSeed?props.seed:void 0,seconds:props.kind==="video"?secs:void 0,aspect:props.kind==="video"?"1:1":"square"}).then((r)=>{if("err"in r){setErr(r.err),setBusy(!1);return}props.onDone(r.path,p)}).catch((e)=>{setErr(e instanceof Error?e.message:String(e)),setBusy(!1)}).finally(()=>{flight.current=!1})};useKeyboard((key3)=>{if(busy2)return;if(key3.name==="tab"){key3.preventDefault();let i=fields.indexOf(field),next2=fields[(i+(key3.shift?fields.length-1:1))%fields.length];setField(next2);return}if(field==="prompt")return;if(key3.name==="return")return field==="submit"?submit2():advance();if(field==="seed"&&(key3.name==="space"||key3.name==="left"||key3.name==="right")){setUseSeed((v2)=>!v2);return}if(field==="seconds"){if(key3.name==="left")return setSecs((v2)=>Math.max(1,v2-1));if(key3.name==="right")return setSecs((v2)=>Math.min(4,v2+1))}if(field==="submit"&&key3.name==="space")submit2()});let lbl=(id,text3)=>$jsx("box",{width:12,flexShrink:0,children:$jsxs("text",{fg:field===id?theme.accent:theme.textMuted,children:[field===id?"\u25B8 ":" ",text3]})});return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Generate ${props.kind} \u2014 ${props.state}`})})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",children:[lbl("prompt","Prompt"),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("textarea",{ref:ta,initialValue:prompt,keyBindings:BINDS,onSubmit:advance,onContentChange:()=>{if(ta.current)setPrompt(ta.current.plainText)},focused:field==="prompt",placeholder:props.kind==="image"?"describe the image\u2026":"describe the motion\u2026",textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field==="prompt"?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement,minHeight:4,maxHeight:6})})]}),props.seed?$jsxs("box",{height:1,flexDirection:"row",marginTop:1,children:[lbl("seed","Seed"),$jsx("box",{flexGrow:1,minWidth:0,height:1,children:$jsx("text",{fg:field==="seed"?theme.text:theme.textMuted,children:useSeed?"\u25CF base.png":"\u25CB none"})})]}):null,props.kind==="video"?$jsxs("box",{height:1,flexDirection:"row",marginTop:1,children:[lbl("seconds","Seconds"),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:1,max:4,value:secs,foregroundColor:field==="seconds"?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>setSecs(Math.round(v2))})}),$jsx("box",{width:6,height:1,children:$jsx("text",{fg:field==="seconds"?theme.text:theme.textMuted,children:` ${secs}s`})})]}):null,$jsxs("box",{marginTop:1,flexDirection:"row",children:[lbl("submit",""),$jsx("box",{flexGrow:1,minWidth:0,children:busy2?$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:"generating\u2026"})}):err?$jsx("text",{fg:theme.warning,wrapMode:"word",children:err}):$jsx("box",{height:1,children:$jsx("text",{fg:field==="submit"?theme.accent:theme.textMuted,children:"[Enter] generate"})})})]}),$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter next \xB7 Shift+Enter newline \xB7 Tab field \xB7 Esc cancel"})})]})};function openGenerate(dialog,run,opts){return new Promise((resolve4)=>{let token=0;dialog.replace($jsx(Generate,{...opts,run,onDone:(p,txt)=>{if(resolve4(p?{path:p,prompt:txt}:null),dialog.version()===token)dialog.clear()}}),()=>resolve4(null)),token=dialog.version()})}var import_react111=__toESM(require_react_production(),1);import{existsSync as existsSync21,readFileSync as readFileSync13,rmSync as rmSync5}from"fs";import{createHash as createHash6}from"crypto";import{isIP}from"net";import{tmpdir as tmpdir5}from"os";import{basename as basename10,dirname as dirname11,join as join16}from"path";var exports_eikon={};__export(exports_eikon,{writeStudio:()=>writeStudio,useInstalled:()=>useInstalled,update:()=>update,studioFile:()=>studioFile,sourceStatus:()=>sourceStatus,sourceStamp:()=>sourceStamp,sourceName:()=>sourceName,sourceFetchUrl:()=>sourceFetchUrl,sourceExt:()=>sourceExt,sourceDir:()=>sourceDir,save:()=>save2,revision:()=>revision,remove:()=>remove2,register:()=>register,readStudio:()=>readStudio,raw:()=>raw,rasterizers:()=>rasterizers,rasterizer:()=>rasterizer,probe:()=>probe,previewPackage:()=>previewPackage,pick:()=>pick,peekSource:()=>peekSource,parseEikonFile:()=>parseEikonFile,parseEikon:()=>parseEikon,onRevision:()=>onRevision,onRegistry:()=>onRegistry,notifyRevision:()=>notifyRevision,localSources:()=>localSources,loadCatalog:()=>loadCatalog2,list:()=>list2,lifecycle:()=>lifecycle,installPackage:()=>installPackage,inspectSource:()=>inspectSource,header:()=>header,hasLocalSource:()=>hasLocalSource,findSource:()=>findSource,file:()=>file,fetchSource:()=>fetchSource,ensure:()=>ensure,eikon:()=>exports_eikon,downloadSource:()=>downloadSource,dir:()=>dir,baked:()=>baked,attachSources:()=>attachSources,adopt:()=>adopt,adaptPackage:()=>adaptPackage});import{existsSync as existsSync20,mkdirSync as mkdirSync6,readdirSync as readdirSync8,copyFileSync as copyFileSync4,readFileSync as readFileSync12,writeFileSync as writeFileSync7,rmSync as rmSync4,statSync as statSync10,renameSync as renameSync3}from"fs";import{createHash as createHash5}from"crypto";import{join as join15,extname as extname2,basename as basename9,dirname as dirname10}from"path";import{existsSync as existsSync19,readFileSync as readFileSync11}from"fs";import{join as join14,dirname as dirname9}from"path";var locate2=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join14(d2,"assets/eikons");if(existsSync19(p))return p;let up=dirname9(d2);if(up===d2)break;d2=up}return join14(import.meta.dir,"../../../assets/eikons")},BUNDLED_EIKON_DIR=locate2(),packageEntrypoint=(dir)=>{let manifest3=join14(dir,"manifest.json");if(!existsSync19(manifest3))return;try{let entrypoints=JSON.parse(readFileSync11(manifest3,"utf8")).entrypoints,value2=entrypoints&&typeof entrypoints==="object"&&!Array.isArray(entrypoints)?entrypoints.default:void 0,path4=typeof value2==="string"?join14(dir,value2):void 0;return path4&&existsSync19(path4)?path4:void 0}catch{return}};function bundledEikonPath(name){if(!name)return;let id=name==="default"?"nous":name,dir=join14(BUNDLED_EIKON_DIR,id),entry3=packageEntrypoint(dir);if(entry3)return entry3;for(let p of[join14(dir,`${id}.eikon`),join14(BUNDLED_EIKON_DIR,`${id}.eikon`)])if(existsSync19(p))return p;return}import{deflateSync}from"zlib";import{spawnSync}from"child_process";import{statSync as statSync9}from"fs";var W2=48,H=24,FPS0=16,MAXF=256,S0={zoom:1,ox:0.5,oy:0.5},T0={contrast:1,invert:!0,flip:"none"},defaults=(r)=>Object.fromEntries(Object.entries(r.knobs).map(([k2,d2])=>[k2,d2.default])),caps3={chafa:chafaBin(),ffmpeg:spawnSync("ffmpeg",["-version"],{stdio:"ignore"}).status===0,ffprobe:spawnSync("ffprobe",["-version"],{stdio:"ignore"}).status===0};function probe(path4){if(!caps3.ffprobe)return null;let r=spawnSync("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",path4],{encoding:"utf8"});if(r.status!==0)return null;let m2=r.stdout.trim().match(/^(\d+),(\d+)/);return m2?{w:+m2[1],h:+m2[2]}:null}var clamp=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),SCALE=384,PLANE=SCALE*SCALE,VID=/\.(mp4|webm|mov|mkv|m4v|gif)$/i,clips=new Map,CLIP_CAP=8;function decode2(src3,fps=FPS0){let full=resolveImage(src3);if(!full)return Promise.resolve(`not found: ${src3}`);let mt=statSync9(full,{throwIfNoEntry:!1})?.mtimeMs??0,key3=`${full}:${mt}:${fps}`,got=clips.get(key3);if(got)return clips.delete(key3),clips.set(key3,got),got;if(!caps3.ffmpeg)return Promise.resolve("ffmpeg not installed");let video=VID.test(full),vf=[...video?[`fps=${fps}`]:[],`scale=${SCALE}:${SCALE}:force_original_aspect_ratio=increase`,`crop=${SCALE}:${SCALE}`].join(","),p=(async()=>{let ff=Bun.spawn(["ffmpeg","-hide_banner","-loglevel","error","-i",full,"-vf",vf,"-frames:v",video?String(MAXF):"1","-f","rawvideo","-pix_fmt","gray","-"],{stdout:"pipe",stderr:"pipe"}),[buf,err]=await Promise.all([new Response(ff.stdout).arrayBuffer().then((b2)=>new Uint8Array(b2)),new Response(ff.stderr).text()]);if(await ff.exited,ff.exitCode!==0)return`ffmpeg: ${err.trim()||"failed"}`;if(buf.length===0||buf.length%PLANE!==0)return`ffmpeg: bad read (${buf.length})`;let n=buf.length/PLANE;return{planes:Array.from({length:n},(_2,i)=>buf.subarray(i*PLANE,(i+1)*PLANE)),fps:video?fps:0,w:SCALE,h:SCALE}})();if(clips.size>=CLIP_CAP)clips.delete(clips.keys().next().value);return clips.set(key3,p),p}var prewarm=(src3,fps=FPS0)=>void decode2(src3,fps);function crop(clip,sp){let side=Math.max(1,Math.round(clip.w*clamp(sp.zoom,0.1,1))),x0=Math.round((clip.w-side)*clamp(sp.ox,0,1)),y0=Math.round((clip.h-side)*clamp(sp.oy,0,1)),n=clip.planes.length,gray=new Uint8Array(side*side*n);for(let f=0;f<n;f++){let pl=clip.planes[f],off=f*side*side;for(let y2=0;y2<side;y2++)gray.set(pl.subarray((y0+y2)*clip.w+x0,(y0+y2)*clip.w+x0+side),off+y2*side)}let enc2;return{gray,w:side,h:side,frames:n,png:()=>enc2??=png(gray,side,side*n)}}function png(gray,w2,h2){let be32=(n)=>new Uint8Array([n>>>24,n>>>16&255,n>>>8&255,n&255]),T2=png_crc,crc=(b2)=>{let c=4294967295;for(let i=0;i<b2.length;i++)c=T2[(c^b2[i])&255]^c>>>8;return~c>>>0},chunk=(tag,data2)=>{let t2=new TextEncoder().encode(tag),body=new Uint8Array(t2.length+data2.length);return body.set(t2),body.set(data2,4),[be32(data2.length),body,be32(crc(body))]},ihdr=new Uint8Array(13);ihdr.set(be32(w2),0),ihdr.set(be32(h2),4),ihdr[8]=8,ihdr[9]=0,ihdr[10]=0,ihdr[11]=0,ihdr[12]=0;let raw=new Uint8Array(h2*(w2+1));for(let y2=0;y2<h2;y2++)raw.set(gray.subarray(y2*w2,(y2+1)*w2),y2*(w2+1)+1);let idat=new Uint8Array(deflateSync(raw,{level:1})),parts2=[new Uint8Array([137,80,78,71,13,10,26,10]),...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))],out=new Uint8Array(parts2.reduce((n,p)=>n+p.length,0)),o=0;for(let p of parts2)out.set(p,o),o+=p.length;return out}var png_crc=(()=>{let t2=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k2=0;k2<8;k2++)c=c&1?3988292384^c>>>1:c>>>1;t2[n]=c>>>0}return t2})(),cache4=new Map,CAP3=256;function put(key3,v2){if(cache4.size>=CAP3)cache4.delete(cache4.keys().next().value);return cache4.set(key3,v2),v2}function hit(key3){let v2=cache4.get(key3);if(!v2)return;return cache4.delete(key3),cache4.set(key3,v2),v2}function resetCache(){cache4.clear(),clips.clear()}var keyOf=(r,src3,sp,tn,fps,k2)=>`${r}|${src3}|${fps}|${sp.zoom.toFixed(3)}:${sp.ox.toFixed(3)}:${sp.oy.toFixed(3)}|${tn.contrast.toFixed(2)}:${+tn.invert}:${tn.flip}|${JSON.stringify(k2)}`;async function cached2(r,src3,sp,tn,fps,k2,signal){let key3=keyOf(r.name,src3,sp,tn,fps,k2),got=hit(key3);if(got)return{frames:got};let cl=await decode2(src3,fps);if(typeof cl==="string")return{err:cl};if(signal?.aborted)return{err:"aborted"};let out=await r.render(tone(crop(cl,sp),tn),k2,signal);if("err"in out)return out;if(signal?.aborted)return{err:"aborted"};return{frames:put(key3,out.frames)}}function pad(rows3){let out=rows3.slice(0,H);while(out.length<H)out.push("");return out.map((l)=>{if(l.includes("\x1B["))return l;let cp=Array.from(l);return cp.length>=W2?cp.slice(0,W2).join(""):l+" ".repeat(W2-cp.length)})}function box(out,n){let rows3=out.replace(/\n$/,"").split(`
|
|
4129
4129
|
`);return Array.from({length:n},(_2,i)=>pad(rows3.slice(i*H,(i+1)*H)))}function thumb(frame,w2=16,h2=8){let fx=W2/w2,fy=H/h2;return Array.from({length:h2},(_2,y2)=>{let row3=Array.from(frame[Math.min(H-1,Math.floor(y2*fy+fy/2))]??""),n=row3.length;return Array.from({length:w2},(_3,x2)=>row3[Math.min(n-1,Math.floor(x2*fx+fx/2))]??" ").join("")})}function tone(win,t2){let{gray:g,w:w2,h:h2,frames:n}=win,sz=w2*h2,flip=t2.flip,con=clamp(t2.contrast,0.25,4);for(let f=0;f<n;f++){let o=f*sz;if(flip==="h"||flip==="hv")for(let y2=0;y2<h2;y2++){let ro=o+y2*w2;for(let x2=0;x2<w2>>1;x2++){let t3=g[ro+x2];g[ro+x2]=g[ro+w2-1-x2],g[ro+w2-1-x2]=t3}}if(flip==="v"||flip==="hv")for(let y2=0;y2<h2>>1;y2++){let a=g.subarray(o+y2*w2,o+(y2+1)*w2),b2=g.subarray(o+(h2-1-y2)*w2,o+(h2-y2)*w2),t3=new Uint8Array(a);a.set(b2),b2.set(t3)}}if(Math.abs(con-1)>0.001)for(let f=0;f<n;f++){let o=f*sz,sum=0;for(let i=0;i<sz;i++)sum+=g[o+i];let m2=sum/sz;for(let i=0;i<sz;i++)g[o+i]=clamp(Math.round((g[o+i]-m2)*con+m2),0,255)}if(t2.invert)for(let i=0;i<g.length;i++)g[i]=255-g[i];return win}var chafa={name:"chafa",knobs:{symbols:{kind:"cycle",options:["braille","block","ascii","sextant","quad","half","wedge"],default:"braille",hint:"Glyph family used to draw pixels. Braille is densest; block is boldest; ascii is most compatible."},fill:{kind:"cycle",options:["none","stipple","ascii","braille"],default:"none",hint:"Secondary glyph set used where the primary leaves gaps."},dither:{kind:"cycle",options:["none","ordered","diffusion","noise"],default:"none",hint:"Adds texture to smooth gradients so mid-tones don't band."}},available:()=>caps3.chafa?!0:"chafa not installed",async render(win,k2,signal){let bin=caps3.chafa;if(!bin)return{err:"chafa not installed"};let fill=String(k2.fill??"none"),args=[`--size=${W2}x${H*win.frames}`,"--format=symbols","--stretch","--colors=none",`--symbols=${String(k2.symbols??"braille")}`,...fill==="none"?[]:[`--fill=${fill}`],`--dither=${String(k2.dither??"none")}`,"--preprocess","off","-"];if(signal?.aborted)return{err:"aborted"};let ch=Bun.spawn([bin,...args],{stdin:win.png(),stdout:"pipe",stderr:"pipe"}),kill=()=>ch.kill();signal?.addEventListener("abort",kill,{once:!0});let[out,cerr]=await Promise.all([new Response(ch.stdout).text(),new Response(ch.stderr).text()]);if(await ch.exited,signal?.removeEventListener("abort",kill),signal?.aborted)return{err:"aborted"};if(ch.exitCode!==0)return{err:`chafa: ${cerr.trim()||"failed"}`};return{frames:box(out,win.frames)}}},DOT=[[1,8],[2,16],[4,32],[64,128]],RAMP=" .:-=+*#%@";function sample(g,w2,h2,fw,fh){let sx=w2/fw,sy=h2/fh;return(gx,gy)=>g[Math.min(h2-1,Math.floor(gy*sy))*w2+Math.min(w2-1,Math.floor(gx*sx))]}function mean(g){let s=0;for(let i=0;i<g.length;i++)s+=g[i];return s/g.length}function braille(g,w2,h2){let at=sample(g,w2,h2,W2*2,H*4),thr=mean(g),rows3=[];for(let y2=0;y2<H;y2++){let row3="";for(let x2=0;x2<W2;x2++){let bits=0;for(let dy=0;dy<4;dy++)for(let dx=0;dx<2;dx++)if(at(x2*2+dx,y2*4+dy)>thr)bits|=DOT[dy][dx];row3+=String.fromCodePoint(10240+bits)}rows3.push(row3)}return rows3}function block(g,w2,h2){let at=sample(g,w2,h2,W2,H),n=RAMP.length-1,rows3=[];for(let y2=0;y2<H;y2++){let row3="";for(let x2=0;x2<W2;x2++)row3+=RAMP[Math.round(at(x2,y2)/255*n)];rows3.push(row3)}return rows3}var native={name:"native",knobs:{symbols:{kind:"cycle",options:["braille","block"],default:"braille",hint:"Glyph family used to draw pixels. Braille is denser; block is bolder."}},available:()=>caps3.ffmpeg?!0:"ffmpeg not installed",async render(win,k2){let fn=k2.symbols==="block"?block:braille,sz=win.w*win.h;return{frames:Array.from({length:win.frames},(_2,i)=>fn(win.gray.subarray(i*sz,(i+1)*sz),win.w,win.h))}}},BUILTIN=[chafa,native];var exports_eikon_knobs={};__export(exports_eikon_knobs,{zoom:()=>zoom,unfork:()=>unfork,toStudio:()=>toStudio,swap:()=>swap,step:()=>step,slug:()=>slug2,setState:()=>setState,setSlider:()=>setSlider,reset:()=>reset2,pan:()=>pan,knobs:()=>exports_eikon_knobs,fresh:()=>fresh,fork:()=>fork,eff:()=>eff,edit:()=>edit,cycle:()=>cycle2,STATES:()=>STATES2});var STATES2=["idle","listening","thinking","speaking","working","error"],clamp2=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),round=(x2,p=3)=>+x2.toFixed(p),wrap=(arr3,cur,d2)=>arr3[(Math.max(0,arr3.indexOf(cur))+d2+arr3.length)%arr3.length];function fresh(name,r,seed){return{name,state:"idle",dims:null,dirty:!1,rasterizer:seed?.rasterizer??r.name,spatial:seed?.spatial??{...S0},tone:{...T0,...seed?.tone},fps:seed?.fps??FPS0,base:seed?.base??defaults(r),per:seed?.per??{},glyph:seed?.glyph??"\u25C6",sources:seed?.sources??{},prompts:seed?.prompts??{}}}var eff=(s,state3)=>s.per[state3]??s.base;function edit(s,fn){let own=s.per[s.state];return own?{...s,per:{...s.per,[s.state]:fn(own)},dirty:!0}:{...s,base:fn(s.base),dirty:!0}}var fork=(s)=>s.per[s.state]?s:{...s,per:{...s.per,[s.state]:{...s.base}},dirty:!0},unfork=(s)=>{if(!s.per[s.state])return s;let{[s.state]:_2,...rest}=s.per;return{...s,per:rest,dirty:!0}},setState=(s,state3)=>({...s,state:state3}),cycle2=(s,d2)=>setState(s,wrap(STATES2,s.state,d2));function step(k2,id,def2,d2){if(def2.kind==="cycle")return{...k2,[id]:wrap(def2.options,String(k2[id]??def2.default),d2)};if(def2.kind==="toggle")return{...k2,[id]:!(k2[id]??def2.default)};let cur=Number(k2[id]??def2.default);return{...k2,[id]:round(clamp2(cur+d2*def2.step,def2.min,def2.max))}}function setSlider(k2,id,def2,v2){if(def2.kind!=="slider")return k2;return{...k2,[id]:round(clamp2(v2,def2.min,def2.max))}}function pan(sp,dx,dy,fine=!1){let s=fine?0.01:0.03;return{zoom:sp.zoom,ox:round(clamp2(sp.ox+dx*s,0,1)),oy:round(clamp2(sp.oy+dy*s,0,1))}}function zoom(sp,d2,fine=!1){let s=fine?0.02:0.05;return{...sp,zoom:round(clamp2(sp.zoom+d2*s,0.1,1))}}function swap(s,r){return{...s,rasterizer:r.name,base:defaults(r),per:{},dirty:!0}}var reset2=(s,r)=>({...s,spatial:{...S0},tone:{...T0},base:defaults(r),per:{},dirty:!0}),slug2=(v2)=>v2.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")||"wip",toStudio=(s)=>({rasterizer:s.rasterizer,spatial:s.spatial,tone:s.tone,fps:s.fps,base:s.base,per:s.per,glyph:s.glyph,sources:s.sources,prompts:s.prompts});var ROOT=()=>hermesPath("eikons"),dir=(name)=>join15(ROOT(),name),file=(name)=>join15(dir(name),`${name}.eikon`),flat=(name)=>join15(ROOT(),`${name}.eikon`),sourceDir=(name)=>join15(dir(name),"source"),studioFile=(name)=>join15(dir(name),"studio.json");function ensure(name){return mkdirSync6(sourceDir(name),{recursive:!0}),{dir:dir(name),file:file(name),source:sourceDir(name)}}function manifest3(name){let p=join15(dir(name),"manifest.json");if(!existsSync20(p))return;try{let raw=JSON.parse(readFileSync12(p,"utf8"));if(raw&&typeof raw==="object")return raw}catch{}return}var LEGACY_SOURCE_URL="source_url",OBJ=(x2)=>!!x2&&typeof x2==="object"&&!Array.isArray(x2);function originObject(man){let o=man?.origin;return OBJ(o)?o:void 0}function origin(man){let src3=originObject(man)?.source;return typeof src3==="string"?src3:void 0}function legacySource(head){let src3=head?.[LEGACY_SOURCE_URL];return typeof src3==="string"?src3:void 0}function display2(man){return OBJ(man?.display)?man.display:void 0}function sourceInfo(man,head){let o=originObject(man),src3=typeof o?.source==="string"?o.source:legacySource(head),identity2=o?.identityKey??o?.sourceKey??o?.packageUrl??o?.repo??src3;return{kind:o?.kind??"unknown",...identity2?{identity:identity2}:{},...src3?{origin:src3}:{},...o?.repo?{repo:o.repo}:{},...o?.selector?{selector:o.selector}:{},...o?.catalogRoot?{catalogRoot:o.catalogRoot}:{},...o?.sha?{sha:o.sha}:{},...o?.packageUrl?{packageUrl:o.packageUrl}:{}}}function displayTitle(man){let disp=display2(man);return typeof disp?.title==="string"?disp.title:typeof man?.title==="string"?man.title:void 0}function displayAuthor(man){let disp=display2(man);return typeof disp?.author==="string"?disp.author:typeof man?.author==="string"?man.author:void 0}function sourceLabel(src3){let id=src3.repo??src3.identity??src3.origin??src3.packageUrl;if(!id)return src3.kind;if(src3.sha)return`${src3.kind} ${id}@${src3.sha.slice(0,12)}`;return`${src3.kind} ${id}`}function inspectResolved(src3,r,stat2){let{manifest:man,origin:o}=r,info2={kind:o.kind??"unknown",...o.identityKey||o.sourceKey||o.packageUrl||o.repo||o.source?{identity:o.identityKey??o.sourceKey??o.packageUrl??o.repo??o.source}:{},...o.source?{origin:o.source}:{},...o.repo?{repo:o.repo}:{},...o.selector?{selector:o.selector}:{},...o.catalogRoot?{catalogRoot:o.catalogRoot}:{},...o.sha?{sha:o.sha}:{},...o.packageUrl?{packageUrl:o.packageUrl}:{}},compatibility=OBJ(man.compatibility)?man.compatibility:void 0,poster2=typeof man.poster==="string"?man.poster:void 0,preview2=typeof man.preview==="string"?man.preview:void 0,out={name:r.name,...displayTitle(man)?{title:displayTitle(man)}:{},...displayAuthor(man)?{author:displayAuthor(man)}:{},...typeof man.version==="string"?{version:man.version}:{},source:info2,trust:r.trust.state,active:get2("eikon")===r.name,removable:!1,updateable:!0,updateAvailable:!1,dirty:!1,...poster2?{poster:poster2}:{},...preview2?{preview:preview2}:{},...compatibility?{compatibility}:{},installed:existsSync20(file(r.name)),sourceLabel:sourceLabel(info2),previewAvailable:Boolean(preview2||man.entrypoints?.default),posterAvailable:Boolean(poster2),...stat2?{n:stat2.n,bytes:stat2.bytes}:{},...r.trust.reason?{reason:r.trust.reason}:{}};if(!out.source.origin)out.source.origin=src3;return out}function changed(name){try{return dirty(dir(name))}catch{return!1}}function lifecycle(name,opts={}){let man=manifest3(name),head=header(file(name)),src3=sourceInfo(man,head),title=displayTitle(man),author=displayAuthor(man),version=typeof man?.version==="string"?man.version:void 0,compatibility=OBJ(man?.compatibility)?man.compatibility:void 0,installedAt=originObject(man)?.at,hasOrigin=Boolean(src3.origin??src3.packageUrl),isDirty=opts.dirty!==!1&&existsSync20(dir(name))?changed(name):!1;return{name,...title?{title}:{},...author?{author}:{},...version?{version}:{},source:src3,trust:originObject(man)?.trust??(src3.origin?"unverified":"unknown"),active:get2("eikon")===name,removable:existsSync20(file(name)),updateable:hasOrigin,updateAvailable:!1,dirty:isDirty,...typeof man?.poster==="string"?{poster:man.poster}:{},...typeof man?.preview==="string"?{preview:man.preview}:{},...compatibility?{compatibility}:{},...installedAt?{installedAt}:{}}}function list2(){let root3=ROOT();if(!existsSync20(root3))return[];return readdirSync8(root3,{withFileTypes:!0}).filter((e)=>e.isDirectory()&&existsSync20(join15(root3,e.name,`${e.name}.eikon`))).map((e)=>{let name=e.name;normalizeStoredSources(name);let man=manifest3(name),path4=join15(root3,name,`${name}.eikon`);return{name,file:path4,source:join15(root3,name,"source"),hasSource:hasLocalSource(name),sourceUrl:sourceUrl(man,header(path4)),manifest:man,lifecycle:lifecycle(name,{dirty:!1})}})}function raw(){let root3=ROOT();if(!existsSync20(root3))return[];return readdirSync8(root3,{withFileTypes:!0}).filter((e)=>e.isDirectory()).map((e)=>e.name)}var IMG=/\.(png|jpe?g|webp|gif|bmp)$/i,VID2=/\.(mp4|webm|mov|mkv)$/i,MEDIA_EXT={"image/png":".png","image/jpeg":".jpg","image/jpg":".jpg","image/webp":".webp","image/gif":".gif","image/bmp":".bmp","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","video/x-matroska":".mkv"};function slot(role){return role==="base"||STATES2.includes(role)}function sourceExt(man,rel2){let ext=extname2(rel2).toLowerCase();if(ext)return ext;let type=man?.files?.find((f)=>f.path===rel2)?.mediaType?.split(";")[0]?.trim().toLowerCase();return type?MEDIA_EXT[type]??"":""}function sourceName(man,role,rel2){return`${role}${sourceExt(man,rel2)}`}function sourceRefs(man){if(!man)return new Map;try{return new Map(entries(man).filter(([role])=>slot(String(role))).map(([role,rel2])=>[String(role),rel2]))}catch{return new Map}}function normalizeSources(name,sources){let man=manifest3(name),refs2=sourceRefs(man),root3=sourceDir(name);return Object.fromEntries(Object.entries(sources).map(([role,fname])=>{if(!fname)return[role,fname];let rel2=refs2.get(role),next2=rel2?sourceName(man,role,rel2):fname;if(next2===fname)return[role,fname];let from2=join15(root3,fname),to=join15(root3,next2);if(existsSync20(from2)&&!existsSync20(to))renameSync3(from2,to);return[role,existsSync20(to)?next2:fname]}))}function sameSources(a,b2){return JSON.stringify(a)===JSON.stringify(b2)}function normalizeStudioSources(name,s){let prev=s.sources??{},sources=normalizeSources(name,prev);if(sameSources(prev,sources))return s;let next2={...s,sources};return writeFileSync7(studioFile(name),JSON.stringify(next2,null,2)+`
|
|
4130
4130
|
`,"utf8"),next2}function normalizeStoredSources(name){try{readStudio(name)}catch{}}function fileOk(name){return IMG.test(name)||VID2.test(name)}function roleOf(name){let stem=basename9(name,extname2(name)).toLowerCase();if(stem==="base")return"base";return STATES2.includes(stem)?stem:void 0}function sourcePath(name,value2){return value2.includes("/")?value2:join15(sourceDir(name),value2)}function storedName(value2){return value2.includes("/")?basename9(value2):value2}function sourceFiles(name){let src3=sourceDir(name);if(!existsSync20(src3))return[];return readdirSync8(src3).filter(fileOk)}function byRole(files,role){return files.find((f)=>roleOf(f)===role)}function roles(state3){if(!state3)return["base","idle"];return state3==="idle"?["idle","base"]:[state3,"base","idle"]}function entryRole(value2,path4){if(value2==="source.base")return"base";if(value2?.startsWith("source.")){let role=value2.slice(7);if(role==="base")return"base";if(STATES2.includes(role))return role}return roleOf(path4)??"base"}function sourceEntries(man,strict=!1){if(!man)return[];try{let xs=entries(man).map(([role,path4])=>[role,path4]);if(xs.length)return xs}catch(err){if(strict)throw err}return(Array.isArray(man.files)?man.files:[]).flatMap((file2)=>{if(typeof file2==="string")return[[entryRole(void 0,file2)??"base",file2]];if(!OBJ(file2)||typeof file2.path!=="string"||!String(file2.role??"").startsWith("source"))return[];let role=entryRole(typeof file2.role==="string"?file2.role:void 0,file2.path);return role?[[role,file2.path]]:[]})}function sourceUrl(man,head){let src3=sourceInfo(man,head);return src3.packageUrl??src3.origin}function sourceFetchUrl(name){return sourceUrl(manifest3(name),header(file(name)))}function sourceStatus(name,state3,opts={}){let seed=opts.sources??readStudio(name)?.sources,files=sourceFiles(name),removed=new Set(Object.entries(seed??{}).flatMap(([role,value2])=>value2===null?[role]:[])),visible2=files.filter((f)=>{let role=roleOf(f);return!role||!removed.has(role)}),hit2=(role)=>{if(removed.has(role))return;let value2=seed?.[role];if(typeof value2==="string"&&value2){let path4=sourcePath(name,value2);if(existsSync20(path4)&&fileOk(path4))return{path:path4,file:storedName(value2),role,origin:opts.sources?"draft":"studio"}}let file2=byRole(visible2,role);return file2?{path:join15(sourceDir(name),file2),file:file2,role,origin:"discovered"}:void 0},found=roles(state3).map(hit2).find(Boolean),first=removed.size?void 0:visible2.find((f)=>IMG.test(f))??visible2.find((f)=>VID2.test(f)),src3=found??(first?{path:join15(sourceDir(name),first),file:first,role:roleOf(first),origin:"fallback"}:void 0),st=state3??"idle",own=Boolean(src3?.role&&(src3.role===st||st==="idle"&&src3.role==="base")),man=manifest3(name),pack=baked(name),head=header(file(name))??(pack?header(pack):void 0),url2=sourceUrl(man,head),downloadable=!src3&&Boolean(url2),size=src3?.path?(()=>{try{return statSync10(src3.path).size}catch{return}})():void 0;return{name,state:st,kind:src3?"local":downloadable?"downloadable":pack?"baked":"missing",...src3?.path?{path:src3.path}:{},...src3?.file?{file:src3.file}:{},...size!==void 0?{size}:{},...src3?.role?{role:src3.role}:{},...src3?.origin?{origin:src3.origin}:{},own,inherited:Boolean(src3&&!own),removed:roles(state3).some((role)=>removed.has(role)),downloadable,...url2?{sourceUrl:url2}:{}}}function localSources(name){return sourceFiles(name).map((file2)=>({file:file2,path:join15(sourceDir(name),file2),...roleOf(file2)?{role:roleOf(file2)}:{}}))}function hasLocalSource(name){if(sourceFiles(name).length>0)return!0;return Object.values(readStudio(name)?.sources??{}).some((value2)=>typeof value2==="string"&&fileOk(value2)&&existsSync20(sourcePath(name,value2)))}function sourceStamp(name){let src3=sourceDir(name),stats=[studioFile(name),existsSync20(file(name))?file(name):""].filter(Boolean).map((path4)=>{try{let st=statSync10(path4);return`${basename9(path4)}:${st.mtimeMs}:${st.size}`}catch{return`${basename9(path4)}:missing`}}),media=sourceFiles(name).sort().map((f)=>{try{let st=statSync10(join15(src3,f));return`${f}:${st.mtimeMs}:${st.size}`}catch{return`${f}:missing`}});return[...stats,...media].join("|")}function findSource(name,state3){return sourceStatus(name,state3).path}function adopt(name,from2,role="base"){let fname=`${role}${extname2(from2).toLowerCase()}`,dst=join15(ensure(name).source,fname);if(from2!==dst)copyFileSync4(from2,dst);return fname}function readStudio(name){let p=studioFile(name);if(!existsSync20(p))return;let raw2=JSON.parse(readFileSync12(p,"utf8"));if(!raw2||typeof raw2!=="object")return;return normalizeStudioSources(name,raw2)}function writeStudio(name,s){ensure(name),writeFileSync7(studioFile(name),JSON.stringify(s,null,2)+`
|
|
4131
4131
|
`,"utf8")}function header(path4){if(!existsSync20(path4))return;return peek2(path4)??void 0}function baked(name){let local=file(name);if(existsSync20(local))return local;let old=flat(name);if(existsSync20(old))return old;let target=(name==="default"?"nous":name).toLowerCase();for(let e of listEikons([BUNDLED_EIKON_DIR]))if(basename9(dirname10(e.path)).toLowerCase()===target||e.meta.name.toLowerCase()===target)return e.path;return}var registry=new Map(BUILTIN.map((r)=>[r.name,r])),subs2=new Set;function register(r){registry.set(r.name,r);for(let f of subs2)f();return()=>{if(registry.get(r.name)===r)registry.delete(r.name);for(let f of subs2)f()}}var rasterizers=()=>[...registry.values()],rasterizer=(name)=>registry.get(name),onRegistry=(fn)=>{return subs2.add(fn),()=>subs2.delete(fn)};function pick(prefer){let want=prefer&®istry.get(prefer);if(want&&want.available()===!0)return want;for(let r of registry.values())if(r.available()===!0)return r;return registry.get("native")}var rev=0,revSubs=new Set,revision=()=>rev,onRevision=(fn)=>{return revSubs.add(fn),()=>revSubs.delete(fn)},bump=()=>{rev++;for(let f of revSubs)f()},notifyRevision=bump;function serialize2(name,fps,clips2){let records=[{type:"header",eikon:1,id:name,title:name,author:{name:process.env.USER??"unknown"},size:{cols:W2,rows:H},defaultSignal:"state.idle",signals:defaultSignalMappings()}];for(let st of STATES2){let fs7=clips2.get(st);records.push({type:"clip",name:st,fps,frameCount:fs7.length,loopFrom:0}),fs7.forEach((f,i)=>records.push({type:"frame",clip:st,index:i,rows:f}))}return serializeLaunchStream(records)}function preserve(name,src3){if(!src3)return;let man=manifest3(name)??{name};if(origin(man))return;writeFileSync7(join15(dir(name),"manifest.json"),JSON.stringify({...man,origin:{source:src3,at:new Date().toISOString()}},null,2)+`
|
|
4132
4132
|
`,"utf8")}async function save2(s){let r=rasterizer(s.rasterizer)??pick(s.rasterizer),paths=ensure(s.name),sources={};for(let[role,p]of Object.entries(s.sources)){if(p===null){sources[role]=null;continue}if(!p)continue;let abs2=p.includes("/")?p:join15(paths.source,p);sources[role]=existsSync20(abs2)?adopt(s.name,abs2,role):p}let seen=new Map,clips2=new Map,blank=[Array.from({length:H},(_2,i)=>(i===H>>1?s.glyph.padStart(W2>>1):"").padEnd(W2))];for(let st of STATES2){let src3=sourceStatus(s.name,st,{sources}).path,k2=eff(s,st),key3=`${src3??""}|${JSON.stringify(k2)}`,fs7=seen.get(key3);if(!fs7){if(!src3)fs7=blank;else{let out=await cached2(r,src3,s.spatial,s.tone,s.fps,k2);if("err"in out)throw Error(out.err);fs7=out.frames}seen.set(key3,fs7)}clips2.set(st,fs7)}let head=header(paths.file);return preserve(s.name,legacySource(head)),await Bun.write(paths.file,serialize2(s.name,s.fps,clips2)),writeStudio(s.name,{...toStudio(s),sources}),bump(),paths.file}function useInstalled(name){if(!existsSync20(file(name))&&!baked(name))throw Error(`eikon '${name}' is not installed`);set("eikon",name),bump()}function remove2(name,opts={}){if(get2("eikon")===name&&!opts.confirmActive)return{type:"active-consequence",action:"remove",name,message:`Removing '${name}' will clear the active avatar. Pass confirmActive to remove it.`};if(rmSync4(dir(name),{recursive:!0,force:!0}),rmSync4(flat(name),{force:!0}),get2("eikon")===name)set("eikon",void 0);bump();return}async function update(name,opts={}){if(get2("eikon")===name&&!opts.confirmActive)return{type:"active-consequence",action:"update",name,message:`Updating '${name}' will change the active avatar's backing package. Pass confirmActive to update it.`};let info2=lifecycle(name),src3=info2.source.origin??info2.source.packageUrl;if(!src3)throw Error(`eikon '${name}' has no recorded source`);return fetchSource(src3,{name})}var peekSource=peek3;function stripManifestTrust(name){let p=join15(dir(name),"manifest.json");if(!existsSync20(p))return;let man=JSON.parse(readFileSync12(p,"utf8"));if(!("license"in man)&&!("provenance"in man))return;delete man.license,delete man.provenance,writeFileSync7(p,JSON.stringify(man,null,2)+`
|
|
4133
4133
|
`,"utf8")}function statResolved(r){let xs=entries(r.manifest),files=Array.isArray(r.manifest.files)?r.manifest.files:[],sizes=xs.map(([,rel2])=>files.find((f)=>f.path===rel2)?.size);if(sizes.every((n)=>typeof n==="number"))return{n:xs.length,bytes:sizes.reduce((a,b2)=>a+b2,0)};if(r.staged)return{n:xs.length,bytes:xs.reduce((sum,[,rel2])=>{let p=join15(r.staged,rel2);return existsSync20(p)?sum+statSync10(p).size:sum},0)};return}async function inspectSource(src3){let dl=/^http:\/\/localhost[:/]/.test(src3)?{allowPrivate:!0}:void 0,r=await resolve5(src3,{downloader:dl});return inspectResolved(src3,r,statResolved(r))}function attachSources(name,sources){let prev=readStudio(name);writeStudio(name,{...prev??toStudio(fresh(name,pick())),sources:{...prev?.sources,...sources}}),bump()}function digest(data2){return`sha256:${createHash5("sha256").update(data2).digest("hex")}`}function dlOpts(url2,opts={}){return/^http:\/\/localhost[:/]/.test(url2)?{allowPrivate:!0,...opts}:opts}function manUrl(url2){if(url2.endsWith("manifest.json"))return url2;return new URL("manifest.json",url2.endsWith("/")?url2:`${url2}/`).toString()}function specOf(man,rel2){return(Array.isArray(man.files)?man.files:[]).find((f)=>OBJ(f)&&f.path===rel2)}async function readManifest(url2,opts){let raw2=await downloadBytes(url2,opts),man=JSON.parse(Buffer.from(raw2).toString("utf8"));if(!OBJ(man))throw Error("source manifest: object required");return man}async function readSource(file2,base3,rel2,opts){let raw2=await downloadBytes(new URL(rel2,base3).toString(),opts),size=file2?.size;if(typeof size==="number"&&raw2.length!==size)throw Error(`source size mismatch: ${rel2}`);if(typeof file2?.digest==="string"&&digest(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}async function downloadSource(name,opts={}){let url2=sourceFetchUrl(name);if(!url2)throw Error(`eikon '${name}' has no published source`);let href=manUrl(url2),root3=href.slice(0,href.lastIndexOf("/")+1),dl=dlOpts(url2,opts.downloader),man=await readManifest(href,dl),xs=sourceEntries(man,!0);if(xs.length===0)throw Error(`eikon '${name}' has no published source media`);let dir2=ensure(name).source,pairs=await Promise.all(xs.map(async([role,rel2])=>{let file2=specOf(man,rel2),fname=sourceName(man,role,rel2);if(!fileOk(fname))throw Error(`source media type unsupported: ${rel2}`);return[role,fname,await readSource(file2,root3,rel2,dl)]})),sources={};return await Promise.all(pairs.map(async([role,fname,data2])=>{await Bun.write(join15(dir2,fname),data2),sources[role]=fname})),attachSources(name,sources),{name,sources,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}async function fetchSource(src3,opts){let out=await install(src3,ROOT(),opts);stripManifestTrust(out.name);let sources=normalizeSources(out.name,out.sources);return attachSources(out.name,sources),{name:out.name,sources,n:out.n,bytes:out.bytes}}var SAFE=/^[a-zA-Z0-9._/-]+$/;function safePath(path4){if(!path4||path4.startsWith("/")||path4.startsWith("./")||path4.includes("../")||path4==="..")return!1;if(!SAFE.test(path4))return!1;return!path4.split("/").includes("..")}function pkgErr(path4,msg){return Error(`${path4}: ${msg}`)}function launchOk(range){let lower=range.match(/>=?\s*(\d+)/);if(lower&&Number(lower[1])>1)return!1;let exact=range.match(/^\s*(\d+)(?:\.\d+)?\s*$/);if(exact&&Number(exact[1])!==1)return!1;if(/>=?\s*2\b|\^\s*2\b/.test(range))return!1;return!/^\s*>=?\s*99/.test(range)}function validatePkg(value2){if(!OBJ(value2))throw pkgErr("manifest","object required");let man=value2;if(man.kind!=="eikon.package")throw pkgErr("kind","must be eikon.package");if(!/^[a-z0-9][a-z0-9-]{1,63}$/.test(String(man.name??"")))throw pkgErr("name","safe package name required");if(!man.id||typeof man.id!=="string")throw pkgErr("id","safe id required");if(!OBJ(man.compatibility)||typeof man.compatibility.eikon!=="string")throw pkgErr("compatibility.eikon","required");if(!launchOk(man.compatibility.eikon))throw pkgErr("compatibility.eikon","must support launch major version 1");if(!OBJ(man.entrypoints)||typeof man.entrypoints.default!=="string"||!safePath(man.entrypoints.default))throw pkgErr("entrypoints.default","safe relative path required");for(let[k2,p]of Object.entries(man.entrypoints))if(typeof p!=="string"||!safePath(p))throw pkgErr(`entrypoints.${k2}`,"safe relative path required");for(let f of man.files??[])if(!f||typeof f.path!=="string"||!safePath(f.path))throw pkgErr("files.path","safe relative path required");if(man.poster&&!safePath(man.poster))throw pkgErr("poster","safe relative path required");return man}function asUrl(value2,base3){if(/^file:\/\//.test(value2))return value2;let out=new URL(value2,base3);if(out.protocol!=="http:"&&out.protocol!=="https:")throw pkgErr("packageUrl","http(s) URL required");return out.toString()}function relUrl(base3,path4){if(!path4)return;if(/^(https?|file):\/\//.test(path4))return asUrl(path4);if(!safePath(path4))throw pkgErr("path","safe relative path required");return new URL(path4,base3).toString()}function entryState(name,available2=!0){if(!available2)return"incompatible";if(get2("eikon")===name)return"active";if(existsSync20(file(name)))return"installed";return"available"}function normalize2(input,base3){if(!OBJ(input))throw pkgErr("catalog","entry object required");if(input.kind==="eikon.catalog.entry"){let entry3=input;return{...entry3,state:entryState(entry3.name,entry3.compatibility?.available!==!1)}}if(OBJ(input.manifest)&&typeof input.packageUrl==="string"){let man=validatePkg(input.manifest),packageUrl3=asUrl(input.packageUrl,base3),root3=packageUrl3.slice(0,packageUrl3.lastIndexOf("/")+1);return{kind:"eikon.catalog.entry",schemaVersion:"1.0",id:man.id,sourceKey:typeof input.sourceKey==="string"?input.sourceKey:packageUrl3,name:man.name,title:man.display?.title,author:man.display?.author,description:man.display?.description,glyph:man.display?.glyph,tags:man.display?.tags,poster:relUrl(root3,man.poster),packageUrl:packageUrl3,detailUrl:typeof input.detailUrl==="string"?asUrl(input.detailUrl,root3):void 0,compatibility:{eikon:man.compatibility.eikon,hosts:man.compatibility.hosts,available:launchOk(man.compatibility.eikon)},state:entryState(man.name,launchOk(man.compatibility.eikon))}}let name=String(input.name??"");if(!/^[a-z0-9][a-z0-9-]{1,63}$/.test(name))throw pkgErr("name","safe catalog name required");let source=typeof input.source==="string"?input.source:`${name}/`,packageUrl2=/^(https?|file):\/\//.test(source)?asUrl(source):base3?new URL(source,base3).toString():source,manifest4=packageUrl2.endsWith("manifest.json")?packageUrl2:new URL("manifest.json",packageUrl2.endsWith("/")?packageUrl2:`${packageUrl2}/`).toString();return{kind:"eikon.catalog.entry",schemaVersion:"1.0",id:name,sourceKey:packageUrl2,name,author:typeof input.author==="string"?input.author:void 0,title:typeof input.title==="string"?input.title:void 0,description:typeof input.description==="string"?input.description:void 0,tags:Array.isArray(input.tags)?input.tags.filter((x2)=>typeof x2==="string"):void 0,glyph:typeof input.glyph==="string"?input.glyph:void 0,poster:typeof input.poster==="string"?input.poster:void 0,packageUrl:manifest4,compatibility:{eikon:">=1 <2",available:!0},state:entryState(name)}}async function loadText(url2,fetcher=fetch){if(url2.startsWith("file://"))return readFileSync12(new URL(url2),"utf8");let res=await fetcher(url2);if(!res.ok)throw Error(`fetch: ${res.status} ${url2}`);return await res.text()}async function loadBytes(url2,fetcher=fetch,desc){if(url2.startsWith("file://"))return new Uint8Array(readFileSync12(new URL(url2)));let res=await fetcher(url2);if(!res.ok)throw Error(`fetch: ${res.status} ${url2}`);let enc2=res.headers.get("content-encoding");if(enc2&&enc2.toLowerCase()!=="identity"&&desc?.digest)throw pkgErr("runtime",`artifact must be served without Content-Encoding: ${enc2}`);return new Uint8Array(await res.arrayBuffer())}async function loadJson(url2,fetcher=fetch){return JSON.parse(await loadText(url2,fetcher))}async function loadCatalog2(index3=process.env.HERM_EIKON_MARKETPLACE||DEFAULT_PUBLIC_CATALOG,fetcher=fetch){let url2=index3.endsWith("index.json")?index3:`${index3.replace(/\/$/,"")}/index.json`,raw2=await loadJson(url2,fetcher);if(!Array.isArray(raw2))throw pkgErr("catalog","index array required");let base3=url2.slice(0,url2.lastIndexOf("/")+1);return raw2.map((item)=>normalize2(item,base3))}async function adaptPackage(manifest4,streamText,legacyText){let man=validatePkg(manifest4),body=streamText??legacyText;if(!body)throw pkgErr("entrypoints.default","stream data required");let eik=parseEikon(body);for(let st of STATES2)if(!eik.states.has(st))throw pkgErr(`states.${st}`,"canonical lifecycle state required");return{manifest:man,eikon:eik,states:[...STATES2],triggers:man.triggers,extensions:man.extensions}}async function loadPackage(url2,fetcher=fetch){return{man:validatePkg(await loadJson(url2,fetcher)),base:url2.slice(0,url2.lastIndexOf("/")+1)}}function runtimeDesc2(man,path4=man.entrypoints.default){let file2=man.files?.find((f)=>f.path===path4)??man.files?.find((f)=>f.role==="runtime");if(!file2||!file2.digest&&file2.size==null&&!file2.encoding&&file2.decodedSize==null&&!file2.decodedDigest)return;return{digest:file2.digest,size:file2.size,encoding:file2.encoding,decodedSize:file2.decodedSize,decodedDigest:file2.decodedDigest}}async function loadRuntime(man,base3,fetcher=fetch,path4=man.entrypoints.default){let desc=runtimeDesc2(man,path4),bytes=await loadBytes(new URL(path4,base3).toString(),fetcher,desc);return{bytes,text:decodeRuntimeBytes(bytes,{descriptor:desc})}}async function previewPackage(entry3,fetcher=fetch){let{man,base:base3}=await loadPackage(entry3.packageUrl,fetcher);return adaptPackage(man,(await loadRuntime(man,base3,fetcher)).text)}async function installPackage(src3,opts={}){let url2=typeof src3==="string"?src3:src3.packageUrl;return fetchSource(url2,{name:opts.name,downloader:opts.fetcher?{fetcher:opts.fetcher}:void 0})}var TOKEN=/(gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|Bearer\s+[A-Za-z0-9._~+/=-]+|token\s+[A-Za-z0-9._~+/=-]+|\*{3,})/gi,CTRL2=/[\u0000-\u001f\u007f-\u009f]/,SECRET2=/(\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|id_rsa$|id_ed25519$|token|secret|credential|password)/i,REPO=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,DEFAULT_REPO=process.env.EIKON_REPO??"liftaris/eikon";function submitPath(name){return file(name)}function targetRepo(){return DEFAULT_REPO}function publishedInfo(path4){let head=header(path4);if(typeof head?.source_url==="string"&&head.source_url.trim())return{source:head.source_url};let mf=join16(dirname11(path4),"manifest.json");if(!existsSync21(mf))return;try{let man=JSON.parse(readFileSync13(mf,"utf8")),src3=man.origin?.source??man.sourceUrl??man.source_url;if(typeof src3==="string"&&src3.trim())return{source:src3}}catch{}return}function redact(message2){return message2.replace(TOKEN,"[redacted]")}function failureText(xs){return xs.map((x2)=>redact(x2.message)).join(`
|
|
4134
|
-
`)}async function defaults2(input){let bundle;try{bundle=await previewSubmitBundle({path:input.path})}catch{}let
|
|
4135
|
-
`))}function publicText(abs2,rel2){if(/\.eikon$/i.test(rel2))return decodeRuntimeFile(abs2);if(/\.(json|md|txt|ya?ml)$/i.test(rel2))return readFileSync13(abs2,"utf8");return}function request(bundle,
|
|
4136
|
-
`);return{bundle,title,body}}function sanitize2(
|
|
4137
|
-
`));return next2}function secretLike(value2){return TOKEN.lastIndex=0,TOKEN.test(value2)||SECRET2.test(value2)}function clean3(value2){return value2.trim().replace(/\s+/g," ")}function authorName(value2){if(typeof value2==="string"&&value2.trim())return value2.trim();if(value2&&typeof value2==="object"&&!Array.isArray(value2)){let name=value2.name;if(typeof name==="string"&&name.trim())return name.trim()}return}function repo(value2){let clean4=value2.trim();if(!REPO.test(clean4))throw Error(`invalid submit repo: ${value2}`);return clean4}function unsafeUrl(value2){return(value2.match(/\b(?:https?|file|data|javascript):[^\s]+/gi)??[]).some((raw2)=>{let url2;try{url2=new URL(raw2)}catch{return!1}if(url2.protocol!=="http:"&&url2.protocol!=="https:")return!0;return privateHost2(url2.hostname)})}function privateHost2(host){let h2=host.toLowerCase().replace(/^\[|\]$/g,"");if(!h2||h2==="::"||h2==="localhost"||h2.endsWith(".localhost"))return!0;let ipv4=h2.match(/^(\d+)\.(\d+)\./);if(ipv4&&privateIpv42(Number(ipv4[1]),Number(ipv4[2])))return!0;if(h2.startsWith("fe80:")||/^f[cd][0-9a-f]{2}:/.test(h2))return!0;let mapped=h2.match(/^::ffff:(?:(\d+)\.(\d+)\.|([0-9a-f]{1,4}):([0-9a-f]{1,4}))/);if(mapped?.[1]&&privateIpv42(Number(mapped[1]),Number(mapped[2])))return!0;if(mapped?.[3]&&mapped?.[4]){let n=Number.parseInt(mapped[3],16)*65536+Number.parseInt(mapped[4],16);return privateIpv42(Math.floor(n/16777216),Math.floor(n/65536)&255)}return isIP(h2)!==0&&(h2==="0.0.0.0"||h2==="::1")}function privateIpv42(a,b2){if(a===10||a===127)return!0;if(a===169&&b2===254)return!0;if(a===192&&b2===168)return!0;return a===172&&b2>=16&&b2<=31}function fallbackUrl(target,name){return`https://github.com/${target}/compare/main...submit%2F${encodeURIComponent(name)}`}function steps(target,name){return[`Open ${target} on GitHub.`,`Create a submit/${name} branch with the prepared files.`,"Open a pull request using the Eikon submission template."]}function snap2(bundle){let hash2=createHash6("sha256");for(let file2 of bundle.files)hash2.update(file2.path),hash2.update("\x00"),hash2.update(String(file2.bytes)),hash2.update("\x00"),hash2.update(readFileSync13(file2.abs)),hash2.update("\x00");return hash2.digest("hex")}function source(path4){return{file:path4,relative:path4,label:basename10(path4)}}async function ghUser(){try{let p=Bun.spawn(["gh","api","user","-q",".login"],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(p.stdout).text(),p.exited]);return code===0&&out.trim()?out.trim():void 0}catch{return}}function cleanup(input){if(dirname11(input.bundleDir)!==tmpdir5()||!basename10(input.bundleDir).startsWith("eikon-submit-"))return;rmSync5(input.bundleDir,{recursive:!0,force:!0})}var FIELDS4=["title","author","description","glyph"];function openEikonSubmit(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Form3,{...opts,done:()=>{dialog.clear(),resolve4()}}),()=>resolve4())})}var Form3=(props)=>{let theme=useTheme().theme,touched=import_react111.useRef({}),flight=import_react111.useRef(!1),[busy2,setBusy]=import_react111.useState(!1),[status,setStatus]=import_react111.useState(""),[result,setResult]=import_react111.useState(null),[prepared,setPrepared]=import_react111.useState(null),[field,setField]=import_react111.useState("title"),[meta,setMeta]=import_react111.useState({title:props.name,author:"unknown",description:"Monochrome terminal avatar.",glyph:"\u25C6"});import_react111.useEffect(()=>{let dead=!1;return touched.current={},defaults2({path:props.path}).then((next2)=>{if(dead)return;setMeta((prev)=>({title:touched.current.title?prev.title:next2.title,author:touched.current.author?prev.author:next2.author,description:touched.current.description?prev.description:next2.description,glyph:touched.current.glyph?prev.glyph:next2.glyph}))}).catch((e)=>setStatus(`Defaults failed: ${redact(e instanceof Error?e.message:String(e))}`)),()=>{dead=!0}},[props.path]);let close2=()=>{if(prepared&&!status.includes("fallback"))cleanup(prepared);props.done()},edit2=(key3,value2)=>{if(touched.current[key3]=!0,setMeta((m2)=>({...m2,[key3]:value2})),prepared)cleanup(prepared);setPrepared(null),setResult(null)},prep=async()=>{if(flight.current)return;flight.current=!0,setBusy(!0),setResult(null);try{if(setStatus("Running registry preflight\u2026"),prepared)cleanup(prepared);let next2=await prepare({path:props.path,meta,includeSource:!1});setPrepared(next2),setStatus(`This will create a PR in ${next2.target} for review. Press Enter to submit.`)}catch(e){setStatus(`Submit failed: ${redact(e instanceof Error?e.message:String(e))}`)}finally{flight.current=!1,setBusy(!1)}},send=async()=>{if(flight.current)return;if(!prepared)return prep();flight.current=!0,setBusy(!0),setResult(null);try{setStatus("Submitting\u2026");let next2=await props.submit(prepared);if(setResult(next2),next2.kind==="submitted")cleanup(prepared),setStatus("Your Eikon has been submitted and is being reviewed.");else if(next2.kind==="setup-needed")setStatus(`GitHub CLI unavailable. Follow the manual PR instructions below. ${failureText(next2.failures)}`);else setStatus(`Submit failed. Follow the manual PR instructions below. ${failureText(next2.failures)}`)}catch(e){setStatus(`Submit failed. Follow the manual PR instructions below. ${redact(e instanceof Error?e.message:String(e))}`)}finally{flight.current=!1,setBusy(!1)}},open3=()=>{if(!prepared)return;let ok=openUrl(prepared.url);setStatus(ok?"Opened GitHub compare page":`Open failed; copy ${prepared.url}`)},move=(by)=>{let i=FIELDS4.indexOf(field);setField(FIELDS4[(i+by+FIELDS4.length)%FIELDS4.length])};useKeyboard((key3)=>{if(key3.name==="escape")return close2();if(busy2)return;if(!prepared&&key3.name==="up")return move(-1);if(!prepared&&key3.name==="down")return move(1);if(key3.name==="o"&&prepared)return open3();if(key3.name==="return")return void send()});let bad=status.startsWith("Submit failed"),warn=status.startsWith("GitHub")||status.includes("fallback")||status.includes("consent");return $jsxs("box",{flexDirection:"column",width:84,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Submit eikon"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.name," \xB7 official registry PR"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:targetRepo()})}),$jsx("box",{height:1}),!prepared?$jsx(Meta,{meta,field,setField,setMeta:edit2}):$jsx(Preview,{prepared,result}),$jsx("box",{height:1}),$jsx("text",{fg:bad?theme.error:warn?theme.warning:theme.textMuted,wrapMode:"word",children:status||(prepared?"Enter submit \xB7 o open GitHub compare \xB7 Esc cancel":"\u2191\u2193 field \xB7 Enter continue \xB7 Esc cancel")})]})};function Meta(props){return $jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:"gray",children:"Public metadata"}),$jsx(Input,{label:"title",value:props.meta.title,on:props.field==="title",setOn:()=>props.setField("title"),set:(v2)=>props.setMeta("title",v2)}),$jsx(Input,{label:"author",value:props.meta.author,on:props.field==="author",setOn:()=>props.setField("author"),set:(v2)=>props.setMeta("author",v2)}),$jsx(Input,{label:"description",value:props.meta.description,on:props.field==="description",setOn:()=>props.setField("description"),set:(v2)=>props.setMeta("description",v2)}),$jsx(Input,{label:"glyph",value:props.meta.glyph,on:props.field==="glyph",setOn:()=>props.setField("glyph"),set:(v2)=>props.setMeta("glyph",v2)})]})}function Input(props){let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",onMouseDown:props.setOn,children:[$jsx("box",{width:13,children:$jsxs("text",{fg:props.on?theme.primary:theme.textMuted,children:[props.on?"\u25B8 ":" ",props.label]})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value:props.value,onInput:props.set,focused:props.on,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]})}function Preview(props){let theme=useTheme().theme,manual=props.result?.kind==="setup-needed"||props.result?.kind==="backend-failed";return $jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:theme.textMuted,children:"Registry preflight"}),props.prepared.lint.map((line4)=>$jsx("text",{fg:theme.accent,children:line4},line4)),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"Package"}),$jsxs("text",{fg:theme.text,children:[props.prepared.files.length," files prepared for registry review"]}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,children:$jsx("text",{fg:theme.textMuted,children:"Bundle:"})}),$jsx(FileLink,{source:props.prepared.bundleSource,children:props.prepared.bundleDir})]}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"Metadata"}),$jsxs("text",{fg:theme.textMuted,children:["Title: ",props.prepared.meta.title]}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",props.prepared.meta.author]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Description: ",props.prepared.meta.description]}),$jsxs("text",{fg:theme.textMuted,children:["Glyph: ",props.prepared.meta.glyph]}),manual?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1}),$jsx("text",{fg:theme.warning,children:"Manual PR"}),props.prepared.steps.map((step2)=>$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["\u2022 ",step2]},step2)),$jsxs("text",{fg:theme.textMuted,children:["Compare: ",props.prepared.url]})]}):null]})}var exports_eikon_gen={};__export(exports_eikon_gen,{setProbe:()=>setProbe,setImpl:()=>setImpl,probeCached:()=>probeCached,probe:()=>probe2,generate:()=>generate,gen:()=>exports_eikon_gen,current:()=>current});import{existsSync as existsSync22,readFileSync as readFileSync14}from"fs";import{tmpdir as tmpdir6}from"os";import{join as join17}from"path";var ROOT2=()=>hermesPath("hermes-agent"),WIN=process.platform==="win32",PY=()=>{for(let v2 of["venv",".venv"]){let bin=WIN?`${ROOT2()}/${v2}/Scripts/python.exe`:`${ROOT2()}/${v2}/bin/python`;if(existsSync22(bin))return bin}return WIN?"python":"python3"},spawn4=(args)=>{try{return Bun.spawn([PY(),...args],{cwd:ROOT2(),env:env2(),stdout:"pipe",stderr:"pipe"})}catch(e){return e instanceof Error?e:Error(String(e))}};function dotenv(){let out={},path4=hermesPath(".env");if(!existsSync22(path4))return out;for(let raw2 of readFileSync14(path4,"utf8").split(`
|
|
4134
|
+
`)}async function defaults2(input){let bundle;try{bundle=await previewSubmitBundle({path:input.path})}catch{}let meta2=bundle?.meta,name=typeof meta2?.name==="string"?meta2.name:basename10(input.path).replace(/\.eikon$/i,""),author=authorName(meta2?.author)??await ghUser()??process.env.USER??"unknown",glyph=typeof meta2?.glyph==="string"&&meta2.glyph.trim()?meta2.glyph.trim():"\u25C6";return{title:typeof meta2?.title==="string"&&meta2.title.trim()?meta2.title.trim():name,author,description:"Monochrome terminal avatar.",glyph}}async function prepare(input){let meta2=sanitize2(input.meta??await defaults2(input)),target=repo(input.target??DEFAULT_REPO),bundle=await previewSubmitBundle({path:input.path,display:meta2}),want=`${bundle.meta.name}.eikon`;if(basename10(input.path)!==want)throw Error(`runtime filename must match eikon name: expected ${want}`);scan(bundle);let req=request(bundle,meta2,target);return{path:input.path,name:bundle.meta.name,files:bundle.files.map((f)=>({path:f.path,bytes:f.bytes})),meta:meta2,target,source:bundle.files.some((f)=>/\/source\/|\/states\//.test(f.path)),bundleDir:bundle.root,bundleSource:source(bundle.root),title:req.title,body:req.body,url:fallbackUrl(target,bundle.meta.name),steps:steps(target,bundle.meta.name),lint:bundle.lint,bundle,request:req,snapshot:snap2(bundle)}}async function submit2(input,backend3){if(snap2(input.bundle)!==input.snapshot)return{kind:"validation-failed",failures:[{code:"invalid-eikon",message:"staged submission changed after preview; review the bundle again"}]};try{scan(input.bundle)}catch(err){return{kind:"validation-failed",failures:[{code:"invalid-eikon",message:err instanceof Error?err.message:String(err)}]}}let be2=backend3??githubSubmitBackend(input.target),setup=await be2.check();if(!setup.ok)return{kind:"setup-needed",failures:[{code:"missing-auth",message:redact(setup.reason)}]};try{return await be2.create(request(input.bundle,input.meta,input.target))}catch(err){return{kind:"backend-failed",failures:[{code:"backend-failed",message:redact(err instanceof Error?err.message:String(err))}]}}}function scan(bundle){let errs=bundle.files.flatMap((file2)=>{let text3=publicText(file2.abs,file2.path);if(text3===void 0)return[];if(secretLike(text3))return[`${file2.path} looks secret-like`];if(unsafeUrl(text3))return[`${file2.path} contains private or unsafe URL`];return[]});if(errs.length)throw Error(errs.join(`
|
|
4135
|
+
`))}function publicText(abs2,rel2){if(/\.eikon$/i.test(rel2))return decodeRuntimeFile(abs2);if(/\.(json|md|txt|ya?ml)$/i.test(rel2))return readFileSync13(abs2,"utf8");return}function request(bundle,meta2,target){let title=`eikons: submit ${bundle.meta.name}`,body=[`Submits \`${bundle.meta.name}\` for official registry review.`,"",`Title: ${meta2.title}`,`Author: ${meta2.author}`,`Description: ${meta2.description}`,`Glyph: ${meta2.glyph}`,`Target: ${target}`,"","Registry preflight:",...bundle.lint].join(`
|
|
4136
|
+
`);return{bundle,title,body}}function sanitize2(meta2){let next2={title:clean3(meta2.title),author:clean3(meta2.author),description:clean3(meta2.description),glyph:clean3(meta2.glyph)},errs=Object.entries(next2).flatMap(([key3,value2])=>{if(!value2)return[`${key3} required`];if(CTRL2.test(value2))return[`${key3} contains control characters`];if(secretLike(value2))return[`${key3} looks secret-like`];if(unsafeUrl(value2))return[`${key3} contains private or unsafe URL`];return[]});if(Array.from(next2.glyph).length>2)errs.push("glyph must be one or two characters");if(errs.length)throw Error(errs.join(`
|
|
4137
|
+
`));return next2}function secretLike(value2){return TOKEN.lastIndex=0,TOKEN.test(value2)||SECRET2.test(value2)}function clean3(value2){return value2.trim().replace(/\s+/g," ")}function authorName(value2){if(typeof value2==="string"&&value2.trim())return value2.trim();if(value2&&typeof value2==="object"&&!Array.isArray(value2)){let name=value2.name;if(typeof name==="string"&&name.trim())return name.trim()}return}function repo(value2){let clean4=value2.trim();if(!REPO.test(clean4))throw Error(`invalid submit repo: ${value2}`);return clean4}function unsafeUrl(value2){return(value2.match(/\b(?:https?|file|data|javascript):[^\s]+/gi)??[]).some((raw2)=>{let url2;try{url2=new URL(raw2)}catch{return!1}if(url2.protocol!=="http:"&&url2.protocol!=="https:")return!0;return privateHost2(url2.hostname)})}function privateHost2(host){let h2=host.toLowerCase().replace(/^\[|\]$/g,"");if(!h2||h2==="::"||h2==="localhost"||h2.endsWith(".localhost"))return!0;let ipv4=h2.match(/^(\d+)\.(\d+)\./);if(ipv4&&privateIpv42(Number(ipv4[1]),Number(ipv4[2])))return!0;if(h2.startsWith("fe80:")||/^f[cd][0-9a-f]{2}:/.test(h2))return!0;let mapped=h2.match(/^::ffff:(?:(\d+)\.(\d+)\.|([0-9a-f]{1,4}):([0-9a-f]{1,4}))/);if(mapped?.[1]&&privateIpv42(Number(mapped[1]),Number(mapped[2])))return!0;if(mapped?.[3]&&mapped?.[4]){let n=Number.parseInt(mapped[3],16)*65536+Number.parseInt(mapped[4],16);return privateIpv42(Math.floor(n/16777216),Math.floor(n/65536)&255)}return isIP(h2)!==0&&(h2==="0.0.0.0"||h2==="::1")}function privateIpv42(a,b2){if(a===10||a===127)return!0;if(a===169&&b2===254)return!0;if(a===192&&b2===168)return!0;return a===172&&b2>=16&&b2<=31}function fallbackUrl(target,name){return`https://github.com/${target}/compare/main...submit%2F${encodeURIComponent(name)}`}function steps(target,name){return[`Open ${target} on GitHub.`,`Create a submit/${name} branch with the prepared files.`,"Open a pull request using the Eikon submission template."]}function snap2(bundle){let hash2=createHash6("sha256");for(let file2 of bundle.files)hash2.update(file2.path),hash2.update("\x00"),hash2.update(String(file2.bytes)),hash2.update("\x00"),hash2.update(readFileSync13(file2.abs)),hash2.update("\x00");return hash2.digest("hex")}function source(path4){return{file:path4,relative:path4,label:basename10(path4)}}async function ghUser(){try{let p=Bun.spawn(["gh","api","user","-q",".login"],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(p.stdout).text(),p.exited]);return code===0&&out.trim()?out.trim():void 0}catch{return}}function cleanup(input){if(dirname11(input.bundleDir)!==tmpdir5()||!basename10(input.bundleDir).startsWith("eikon-submit-"))return;rmSync5(input.bundleDir,{recursive:!0,force:!0})}var FIELDS4=["title","author","description","glyph"];function openEikonSubmit(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Form3,{...opts,done:()=>{dialog.clear(),resolve4()}}),()=>resolve4())})}var Form3=(props)=>{let theme=useTheme().theme,touched=import_react111.useRef({}),flight=import_react111.useRef(!1),[busy2,setBusy]=import_react111.useState(!1),[status,setStatus]=import_react111.useState(""),[result,setResult]=import_react111.useState(null),[prepared,setPrepared]=import_react111.useState(null),[field,setField]=import_react111.useState("title"),[meta2,setMeta]=import_react111.useState({title:props.name,author:"unknown",description:"Monochrome terminal avatar.",glyph:"\u25C6"});import_react111.useEffect(()=>{let dead=!1;return touched.current={},defaults2({path:props.path}).then((next2)=>{if(dead)return;setMeta((prev)=>({title:touched.current.title?prev.title:next2.title,author:touched.current.author?prev.author:next2.author,description:touched.current.description?prev.description:next2.description,glyph:touched.current.glyph?prev.glyph:next2.glyph}))}).catch((e)=>setStatus(`Defaults failed: ${redact(e instanceof Error?e.message:String(e))}`)),()=>{dead=!0}},[props.path]);let close2=()=>{if(prepared&&!status.includes("fallback"))cleanup(prepared);props.done()},edit2=(key3,value2)=>{if(touched.current[key3]=!0,setMeta((m2)=>({...m2,[key3]:value2})),prepared)cleanup(prepared);setPrepared(null),setResult(null)},prep=async()=>{if(flight.current)return;flight.current=!0,setBusy(!0),setResult(null);try{if(setStatus("Running registry preflight\u2026"),prepared)cleanup(prepared);let next2=await prepare({path:props.path,meta:meta2,includeSource:!1});setPrepared(next2),setStatus(`This will create a PR in ${next2.target} for review. Press Enter to submit.`)}catch(e){setStatus(`Submit failed: ${redact(e instanceof Error?e.message:String(e))}`)}finally{flight.current=!1,setBusy(!1)}},send=async()=>{if(flight.current)return;if(!prepared)return prep();flight.current=!0,setBusy(!0),setResult(null);try{setStatus("Submitting\u2026");let next2=await props.submit(prepared);if(setResult(next2),next2.kind==="submitted")cleanup(prepared),setStatus("Your Eikon has been submitted and is being reviewed.");else if(next2.kind==="setup-needed")setStatus(`GitHub CLI unavailable. Follow the manual PR instructions below. ${failureText(next2.failures)}`);else setStatus(`Submit failed. Follow the manual PR instructions below. ${failureText(next2.failures)}`)}catch(e){setStatus(`Submit failed. Follow the manual PR instructions below. ${redact(e instanceof Error?e.message:String(e))}`)}finally{flight.current=!1,setBusy(!1)}},open3=()=>{if(!prepared)return;let ok=openUrl(prepared.url);setStatus(ok?"Opened GitHub compare page":`Open failed; copy ${prepared.url}`)},move=(by)=>{let i=FIELDS4.indexOf(field);setField(FIELDS4[(i+by+FIELDS4.length)%FIELDS4.length])};useKeyboard((key3)=>{if(key3.name==="escape")return close2();if(busy2)return;if(!prepared&&key3.name==="up")return move(-1);if(!prepared&&key3.name==="down")return move(1);if(key3.name==="o"&&prepared)return open3();if(key3.name==="return")return void send()});let bad=status.startsWith("Submit failed"),warn=status.startsWith("GitHub")||status.includes("fallback")||status.includes("consent");return $jsxs("box",{flexDirection:"column",width:84,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Submit eikon"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.name," \xB7 official registry PR"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:targetRepo()})}),$jsx("box",{height:1}),!prepared?$jsx(Meta,{meta:meta2,field,setField,setMeta:edit2}):$jsx(Preview,{prepared,result}),$jsx("box",{height:1}),$jsx("text",{fg:bad?theme.error:warn?theme.warning:theme.textMuted,wrapMode:"word",children:status||(prepared?"Enter submit \xB7 o open GitHub compare \xB7 Esc cancel":"\u2191\u2193 field \xB7 Enter continue \xB7 Esc cancel")})]})};function Meta(props){return $jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:"gray",children:"Public metadata"}),$jsx(Input,{label:"title",value:props.meta.title,on:props.field==="title",setOn:()=>props.setField("title"),set:(v2)=>props.setMeta("title",v2)}),$jsx(Input,{label:"author",value:props.meta.author,on:props.field==="author",setOn:()=>props.setField("author"),set:(v2)=>props.setMeta("author",v2)}),$jsx(Input,{label:"description",value:props.meta.description,on:props.field==="description",setOn:()=>props.setField("description"),set:(v2)=>props.setMeta("description",v2)}),$jsx(Input,{label:"glyph",value:props.meta.glyph,on:props.field==="glyph",setOn:()=>props.setField("glyph"),set:(v2)=>props.setMeta("glyph",v2)})]})}function Input(props){let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",onMouseDown:props.setOn,children:[$jsx("box",{width:13,children:$jsxs("text",{fg:props.on?theme.primary:theme.textMuted,children:[props.on?"\u25B8 ":" ",props.label]})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value:props.value,onInput:props.set,focused:props.on,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]})}function Preview(props){let theme=useTheme().theme,manual=props.result?.kind==="setup-needed"||props.result?.kind==="backend-failed";return $jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:theme.textMuted,children:"Registry preflight"}),props.prepared.lint.map((line4)=>$jsx("text",{fg:theme.accent,children:line4},line4)),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"Package"}),$jsxs("text",{fg:theme.text,children:[props.prepared.files.length," files prepared for registry review"]}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,children:$jsx("text",{fg:theme.textMuted,children:"Bundle:"})}),$jsx(FileLink,{source:props.prepared.bundleSource,children:props.prepared.bundleDir})]}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"Metadata"}),$jsxs("text",{fg:theme.textMuted,children:["Title: ",props.prepared.meta.title]}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",props.prepared.meta.author]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Description: ",props.prepared.meta.description]}),$jsxs("text",{fg:theme.textMuted,children:["Glyph: ",props.prepared.meta.glyph]}),manual?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1}),$jsx("text",{fg:theme.warning,children:"Manual PR"}),props.prepared.steps.map((step2)=>$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["\u2022 ",step2]},step2)),$jsxs("text",{fg:theme.textMuted,children:["Compare: ",props.prepared.url]})]}):null]})}var exports_eikon_gen={};__export(exports_eikon_gen,{setProbe:()=>setProbe,setImpl:()=>setImpl,probeCached:()=>probeCached,probe:()=>probe2,generate:()=>generate,gen:()=>exports_eikon_gen,current:()=>current});import{existsSync as existsSync22,readFileSync as readFileSync14}from"fs";import{tmpdir as tmpdir6}from"os";import{join as join17}from"path";var ROOT2=()=>hermesPath("hermes-agent"),WIN=process.platform==="win32",PY=()=>{for(let v2 of["venv",".venv"]){let bin=WIN?`${ROOT2()}/${v2}/Scripts/python.exe`:`${ROOT2()}/${v2}/bin/python`;if(existsSync22(bin))return bin}return WIN?"python":"python3"},spawn4=(args)=>{try{return Bun.spawn([PY(),...args],{cwd:ROOT2(),env:env2(),stdout:"pipe",stderr:"pipe"})}catch(e){return e instanceof Error?e:Error(String(e))}};function dotenv(){let out={},path4=hermesPath(".env");if(!existsSync22(path4))return out;for(let raw2 of readFileSync14(path4,"utf8").split(`
|
|
4138
4138
|
`)){let ln=raw2.trim();if(!ln||ln.startsWith("#"))continue;let eq3=ln.indexOf("=");if(eq3<1)continue;let k2=ln.slice(0,eq3).replace(/^export\s+/,"").trim(),v2=ln.slice(eq3+1).trim();if(v2.startsWith('"')&&v2.endsWith('"')||v2.startsWith("'")&&v2.endsWith("'"))v2=v2.slice(1,-1);out[k2]=v2}return out}var env2=()=>{let base3=dotenv();for(let[k2,v2]of Object.entries(process.env))if(v2!==void 0)base3[k2]=v2;return base3},q4=(s)=>JSON.stringify(s);function code(kind2,prompt,o){if(kind2==="image")return["from tools.image_generation_tool import _handle_image_generate as g",`print(g({"prompt": ${q4(prompt)}, "aspect_ratio": ${q4(o.aspect??"square")}}))`].join("; ");let args=[`"prompt":${q4(prompt)}`,`"aspect_ratio":${q4(o.aspect??"1:1")}`];if(o.seconds)args.push(`"duration":${o.seconds}`);if(o.seed)args.push(`"image_url":${q4(o.seed)}`);return["from tools.video_generation_tool import _handle_video_generate as g",`print(g({${args.join(",")}}))`].join("; ")}async function probe2(){let root3=ROOT2();if(!existsSync22(root3))return{image:!1,video:!1};let src3=["import json","from tools.image_generation_tool import check_image_generation_requirements as ci","from tools.video_generation_tool import check_video_generation_requirements as cv","print(json.dumps({'image': bool(ci()), 'video': bool(cv())}))"].join("; "),r=spawn4(["-c",src3]);if(r instanceof Error)return{image:!1,video:!1};let out=await new Response(r.stdout).text();if(await r.exited!==0)return{image:!1,video:!1};let last4=out.trim().split(`
|
|
4139
4139
|
`).pop();try{return JSON.parse(last4)}catch{return{image:!1,video:!1}}}async function fetchTo(url2,ext){let tmp=join17(tmpdir6(),`eikon-gen-${Date.now()}${ext}`),res=await fetch(url2);if(!res.ok)throw Error(`download ${res.status}`);return await Bun.write(tmp,await res.arrayBuffer()),tmp}var generate=async(kind2,prompt,opts)=>{let r=spawn4(["-c",code(kind2,prompt,opts)]);if(r instanceof Error)return{err:r.message};let[out,err,exit]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);if(exit!==0)return{err:(err||out).trim().split(`
|
|
4140
4140
|
`).slice(-3).join(" ")||`python exited ${exit}`};let last4=out.trim().split(`
|
|
4141
4141
|
`).pop();if(!last4)return{err:"no output"};let j2;try{j2=JSON.parse(last4)}catch{return{err:`unparseable: ${last4.slice(0,200)}`}}if(j2.success===!1||j2.error)return{err:String(j2.error??"provider error")};let ref=j2.image??j2.video;if(!ref)return{err:"provider returned no asset"};if(ref.startsWith("/")||ref.startsWith("file://"))return{path:ref.replace(/^file:\/\//,"")};if(/^https?:\/\//.test(ref))return fetchTo(ref,kind2==="image"?".png":".mp4").then((p)=>({path:p})).catch((e)=>({err:`download: ${e instanceof Error?e.message:e}`}));return{err:`unrecognized asset ref: ${ref.slice(0,80)}`}},impl=generate,probeImpl=probe2,current=()=>impl,setImpl=(fn)=>{impl=fn??generate},setProbe=(fn)=>{probeImpl=fn??probe2},probeCached=()=>probeImpl();var import_react113=__toESM(require_react_production(),1);var ORDER5=["name","from"],FROMS=[{id:"blank",label:"blank",hint:"author in Studio"},{id:"file",label:"local file",hint:"png / jpg / webp / gif / mp4"},{id:"install",label:"inspect/install",hint:"catalog name \xB7 github.com/u/r/name \xB7 local dir"}],INSTALL_HINT="catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir";function openNewEikon(dialog,opts={}){return new Promise((resolve4)=>{let chained=!1;dialog.replace($jsx(Form4,{initial:opts.initial,dialog,onChain:()=>{chained=!0},done:(r)=>{chained=!0,dialog.clear(),resolve4(r)}}),()=>{if(!chained)resolve4(null)})})}var Form4=(props)=>{let theme=useTheme().theme,[name,setName]=import_react113.useState(props.initial??""),[from2,setFrom]=import_react113.useState("blank"),[field,setField]=import_react113.useState("name"),slug3=name?exports_eikon_knobs.slug(name):"",ok=slug3.length>0,submit3=async()=>{if(!ok)return;if(from2==="blank")return props.done({name:slug3,from:"blank"});if(props.onChain(),from2==="file"){let file2=await openTextPrompt(props.dialog,{title:"Source file",label:"absolute or ~ path (png / jpg / webp / gif / mp4)"});return props.done(file2?{name:slug3,from:"file",file:file2}:null)}let src3=await openTextPrompt(props.dialog,{title:"Inspect eikon source",label:INSTALL_HINT});if(!src3)return props.done(null);try{let info2=await exports_eikon.inspectSource(src3),ok2=await openConfirm(props.dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use the Library after install to select it."].join(`
|
|
4142
4142
|
`),yes:"install",no:"cancel"});return props.done(ok2?{name:slug3,from:"install",src:src3}:null)}catch(e){return await openConfirm(props.dialog,{title:"Inspect failed",danger:!0,body:e instanceof Error?e.message:String(e),yes:"ok",no:"cancel"}),props.done(null)}};useKeyboard((key3)=>{if(key3.name==="escape")return props.done(null);if(key3.name==="tab"){let i=ORDER5.indexOf(field);return setField(ORDER5[(i+(key3.shift?-1:1)+ORDER5.length)%ORDER5.length])}if(key3.name==="return")return void submit3();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[A-Za-z0-9 _-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(key3.name==="up"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.max(0,i-1)].id)}if(key3.name==="down"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.min(FROMS.length-1,i+1)].id)}});let bg2=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New eikon"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("name"),children:[$jsx("box",{width:9,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:slug3?` \u2192 ${slug3}`:" type a name"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:bg2("from"),children:$jsx("text",{fg:theme.textMuted,children:"From (\u2191\u2193)"})}),FROMS.map((f)=>{let on=f.id===from2,fg2=on?theme.accent:theme.text;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("from"),children:[$jsx("box",{width:2,children:$jsx("text",{fg:fg2,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:fg2,children:f.label})}),$jsx("text",{fg:theme.textMuted,children:f.hint})]},f.id)}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:ok?"Enter create \xB7 Tab next field \xB7 Esc cancel":"type a name"})})]})};extend({slider:SliderRenderable});var PANES=["knobs","preview","strip"],HELP_H=4,COL={flexDirection:"column"},mb2=(n)=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,HEAD2=[{id:"open",kind:"select",label:"eikon"},{id:"rasterizer",kind:"select",label:"rasterizer"},{id:"source",kind:"prompt",label:"source"},{id:"-1",kind:"divider",label:""},{id:"fetch",kind:"action",label:"download source",show:(_s,status)=>status.downloadable},{id:"knobsfor",kind:"action",label:"tune",show:(_s,status)=>!!status.path},{id:"reset",kind:"action",label:"reset",show:(_s,status)=>!!status.path},{id:"revert",kind:"action",label:"revert",show:(s)=>s.dirty},{id:"-2",kind:"divider",label:"",show:(_s,status)=>!!status.path},{id:"h-input",kind:"header",label:"input",show:(_s,status)=>!!status.path},{id:"contrast",kind:"tone",label:"contrast",show:(_s,status)=>!!status.path,knob:{kind:"slider",min:0.25,max:4,step:0.05,default:1,hint:"Spread pixel values around their mean. \xD71 = source as-is; higher sharpens, lower flattens. Applied to the image before rasterizing."}},{id:"invert",kind:"tone",label:"invert",show:(_s,status)=>!!status.path,knob:{kind:"toggle",default:!0,hint:"Swap light\u2194dark in the source pixels. On for a light subject on a dark terminal background \u2014 turn off if the subject is darker than its surround."}},{id:"flip",kind:"tone",label:"flip",show:(_s,status)=>!!status.path,knob:{kind:"cycle",options:["none","h","v","hv"],default:"none",hint:"Mirror the source horizontally, vertically, or both before rasterizing."}},{id:"-3",kind:"divider",label:"",show:(_s,status)=>!!status.path}],HELP2={open:"Which eikon you're editing. Enter to switch, create a new one, or install from elsewhere.",rasterizer:"The engine that turns your source image/video into text art. Each rasterizer exposes its own look-and-feel settings below the divider.",source:"Pick, generate, or clear source.",fetch:"Download published source for local editing.",knobsfor:"\u2190\u2192 toggles whether the settings below apply to every state or just the one selected in the strip.",reset:"Restore every setting below to this rasterizer's defaults and drop per-state overrides.",submit:"Submit this local eikon after backend preflight.",revert:"Throw away unsaved edits and reload this eikon from disk."},FLIPS=["none","h","v","hv"];function helpOf(row3){if(!row3)return"";if(row3.id==="source")return $jsx($Fragment,{children:$jsx("span",{children:HELP2.source})});let head=HELP2[row3.id];if(head)return head;if(!row3.knob)return"";if(row3.knob.hint)return row3.knob.hint;if(row3.knob.kind==="cycle")return`\u2190\u2192 or Enter cycles: ${row3.knob.options.join(" \xB7 ")}.`;if(row3.knob.kind==="toggle")return"Space or Enter toggles on/off.";return`\u2190\u2192 or drag adjusts (${row3.knob.min}\u2013${row3.knob.max}); scroll while selected also works.`}function buildRows(r,s,status){let dyn=status.path?Object.entries(r.knobs).map(([id,def2])=>({id,kind:"knob",label:def2.label??id,knob:def2})):[],head=HEAD2.filter((h2)=>h2.show?h2.show(s,status):!0);return dyn.length?[...head,{id:"h-r",kind:"header",label:r.name},...dyn]:head}var MINI_W=12;function Mini(props){let theme=useTheme().theme,d2=props.dims??{w:1,h:1},ar=d2.w/d2.h,bw=ar>=1?MINI_W:Math.max(4,Math.round(MINI_W*ar)),bh=ar>=1?Math.max(4,Math.round(MINI_W/ar)):MINI_W,short2=Math.min(bw,bh),cw=Math.max(1,short2*props.sp.zoom),cx=(bw-cw)*props.sp.ox,cy=(bh-cw)*props.sp.oy,on=(x2,y2)=>x2>=cx&&x2<cx+cw&&y2>=cy&&y2<cy+cw,cell=(x2,ty)=>{let up=on(x2,ty*2),dn=on(x2,ty*2+1);return up&&dn?"\u2588":up?"\u2580":dn?"\u2584":"\xB7"};return $jsx("box",{flexDirection:"column",flexShrink:0,backgroundColor:theme.backgroundElement,children:Array.from({length:Math.ceil(bh/2)},(_2,ty)=>$jsx("text",{fg:theme.textMuted,children:Array.from({length:bw},(_3,x2)=>cell(x2,ty)).join("")},ty))})}var SP_ROWS=["pan x","pan y","zoom","fps"];function PanBars(props){let theme=useTheme().theme,z2=props.sp.zoom,slack=1-z2,on=(i)=>props.focused&&props.sel===i,fg2=(i)=>on(i)?theme.accent:theme.textMuted,wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(k2,-1);if(d2==="down"||d2==="right")props.onWheel(k2,1)},drag=import_react115.useRef(null),grab=(k2,at)=>{drag.current={at,v:props.sp[k2],k:k2}},scrub=(at,L2)=>{let d2=drag.current;if(!d2||slack<=0)return;props.onSet(d2.k,Math.max(0,Math.min(1,+(d2.v+(at-d2.at)/(slack*L2)).toFixed(3))))},drop=()=>{drag.current=null},tw=Math.max(1,Math.round(z2*W2)),tl=Math.min(W2-tw,Math.round(props.sp.ox*slack*W2)),hbar=" ".repeat(tl)+"\u2588".repeat(tw)+" ".repeat(W2-tl-tw),vh=H*2,th=Math.max(1,z2*vh),ty=props.sp.oy*slack*vh,vbar=Array.from({length:H},(_2,y2)=>{let up=y2*2>=ty&&y2*2<ty+th,dn=y2*2+1>=ty&&y2*2+1<ty+th;return up&&dn?"\u2588\u2588":up?"\u2580\u2580":dn?"\u2584\u2584":" "});return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.children,$jsx("box",{width:W2,height:1,backgroundColor:theme.border,onMouseMove:()=>props.onHover(0),onMouseScroll:wheel("ox"),onMouseDown:(e)=>grab("ox",e.x),onMouseDrag:(e)=>scrub(e.x,W2),onMouseUp:drop,onMouseDragEnd:drop,children:$jsx("text",{fg:fg2(0),children:hbar})})]}),$jsx("box",{flexDirection:"column",width:2,height:H,backgroundColor:theme.border,onMouseMove:()=>props.onHover(1),onMouseScroll:wheel("oy"),onMouseDown:(e)=>grab("oy",e.y),onMouseDrag:(e)=>scrub(e.y,H),onMouseUp:drop,onMouseDragEnd:drop,children:vbar.map((g,y2)=>$jsx("text",{fg:fg2(1),children:g},y2))})]})}function SpatialBar(props){let theme=useTheme().theme,rows3=[{label:"zoom",k:"zoom",min:0.1,max:1,v:props.sp.zoom,i:2},{label:"fps",k:"fps",min:4,max:30,v:props.fps,i:3}],wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up")props.onWheel(k2,-1);if(d2==="down")props.onWheel(k2,1)};return $jsxs("box",{flexDirection:"row",marginTop:1,flexShrink:0,children:[$jsx("box",{flexDirection:"column",gap:1,flexShrink:0,children:rows3.map((d2)=>{let on=props.focused&&d2.i===props.sel;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onHover(d2.i),onMouseScroll:wheel(d2.k),children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:d2.label})}),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:d2.min,max:d2.max,value:d2.v,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>props.onSet(d2.k,d2.k==="fps"?Math.round(v2):+v2.toFixed(3))})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:` ${d2.k==="fps"?d2.v.toFixed(0):d2.v.toFixed(2)}`})})]},d2.label)})}),$jsx("box",{width:2}),$jsx(Mini,{sp:props.sp,dims:props.dims})]})}var PreviewPane=import_react115.memo((props)=>{let theme=useTheme().theme,[tick3,setTick]=import_react115.useState(0),n=props.frames.length,fps=props.live?props.s?.fps??FPS0:props.baked?.states.get(props.s?.state??"idle")?.fps??FPS0;import_react115.useEffect(()=>setTick((value2)=>value2%n),[props.frames,n]),import_react115.useEffect(()=>{if(!props.play||!props.focused||n<=1||props.busy)return;let id=setInterval(()=>setTick((value2)=>value2+1),1000/Math.max(1,fps));return()=>clearInterval(id)},[props.play,props.focused,n,props.busy,fps]);let title=props.s?`Preview \u2014 ${props.s.state}${props.s.per[props.s.state]?" (forked)":""}`+(n>1?` \xB7 ${props.play?"\u25B6":"\u23F8"} ${tick3%n+1}/${n}`:"")+(props.live?"":props.baked?" \xB7 (baked)":""):"Preview",frame=props.frames[tick3%n]??BLANK3,body=$jsxs("box",{position:"relative",flexDirection:"column",width:W2,height:H,flexShrink:0,backgroundColor:theme.background,onMouseScroll:props.onScroll,onMouseDown:()=>props.setPlay((value2)=>!value2),children:[frame.map((line4,i)=>$jsx("text",{fg:props.error?theme.textMuted:theme.hermAvatar,children:line4},i)),props.busy&&props.frames[0]===BLANK3?$jsx("box",{position:"absolute",left:0,top:H>>1,width:W2,justifyContent:"center",children:$jsx(Spinner,{color:theme.textMuted,label:"decoding\u2026"})}):null]});return $jsxs(TabShell,{title:props.spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:props.error,focus:props.pane==="preview",children:[!props.live&&props.baked?$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"Baked \u2014 download or attach source to edit."})}):null,props.spatialOk&&props.live&&props.s?$jsxs($Fragment,{children:[$jsx(PanBars,{sp:props.s.spatial,sel:props.sel,focused:props.pane==="preview",onHover:(i)=>{props.onPane("preview"),props.onSel(i)},onSet:props.onSet,onWheel:props.onWheel,children:body}),$jsx(SpatialBar,{sp:props.s.spatial,fps:props.s.fps,dims:props.s.dims,sel:props.sel,focused:props.pane==="preview",onHover:(i)=>{props.onPane("preview"),props.onSel(i)},onSet:props.onSet,onWheel:props.onWheel})]}):body]})});function valueOf(s,r,row3,theme,status,peek5,busy2){if(row3.id==="open")return`${s.name} \u25B8`;if(row3.id==="rasterizer"){let a=r.available();if(a===!0)return`${r.name} \u25B8`;return $jsxs($Fragment,{children:[$jsx("span",{children:`${r.name} \u25B8`}),$jsx("span",{fg:theme.warning,children:` \u26A0 ${a}`})]})}if(row3.id==="source"){if(!status?.path){if(status?.kind==="downloadable")return"Download source";if(status?.kind==="baked")return"Baked only";return"Missing source"}let d2=s.dims,sz=status.size===void 0?"?":mb2(status.size);return d2?`${basename11(status.path)} \xB7 ${d2.w}\xD7${d2.h} \xB7 ${sz}`:`${basename11(status.path)} \xB7 ${sz}`}if(row3.id==="knobsfor")return`\u25C2 ${!!s.per[s.state]?`${s.state} only`:"all states"} \u25B8`;if(row3.id==="reset")return"\u25B8 defaults";if(row3.id==="revert")return"\u25B8 reload from disk";if(row3.kind==="tone"){if(row3.id==="contrast")return`\xD7${s.tone.contrast.toFixed(2)}`;if(row3.id==="invert")return s.tone.invert?"\u25CF on":"\u25CB off";if(row3.id==="flip")return`\u25C2 ${s.tone.flip} \u25B8`}if(row3.id==="fetch")return busy2?"downloading\u2026":peek5?`\u25B8 ${peek5.n} files \xB7 ${mb2(peek5.bytes)}`:"\u25B8 local editable source";if(row3.kind==="knob"&&row3.knob){let k2=exports_eikon_knobs.eff(s,s.state)[row3.id]??row3.knob.default;if(row3.knob.kind==="cycle")return`\u25C2 ${String(k2)} \u25B8`;if(row3.knob.kind==="toggle")return k2?"\u25CF on":"\u25CB off";if(row3.knob.kind==="slider")return Number(k2).toFixed(2)}return""}function KnobRow(props){let theme=useTheme().theme,{row:row3,on,dim:dim2}=props,slider=row3.knob?.kind==="slider"?row3.knob:void 0,sval=!slider?0:row3.kind==="tone"?props.s.tone.contrast:Number(exports_eikon_knobs.eff(props.s,props.s.state)[row3.id]??slider.default),pushed=import_react115.useRef(sval);pushed.current=sval;let slide=(v2)=>{if(v2!==pushed.current)props.onSlide?.(v2)};if(row3.kind==="divider")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(24)})});if(row3.kind==="header")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.textMuted,children:$jsx("u",{children:row3.label})})});let scroll=(e)=>{if(!on||!slider||!props.onWheel)return;e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(-1);if(d2==="down"||d2==="right")props.onWheel(1)};return $jsxs("box",{id:props.id,height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onClick,onMouseScroll:scroll,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:dim2?theme.textMuted:on?theme.text:theme.textMuted,children:row3.label})}),slider?$jsxs($Fragment,{children:[$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:slider.min,max:slider.max,value:sval,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:slide})}),$jsx("box",{width:1})]}):null,$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:props.busy&&row3.id==="fetch"?$jsx(Spinner,{color:theme.accent,label:"downloading\u2026"}):$jsx("text",{fg:dim2?theme.textMuted:theme.text,children:valueOf(props.s,props.r,row3,theme,props.status,props.peek,props.busy)})})]})}function Strip(props){let theme=useTheme().theme,glyph=useSpinnerGlyph(props.pending.size>0);return $jsx("box",{flexDirection:"row",gap:1,children:STATES2.map((st)=>{let on=props.s.state===st,own=!!props.s.per[st],status=props.stats.get(st),mark2=status.kind==="missing"?"missing":status.kind==="downloadable"?"download":status.role===st?"own src":own?"forked":"",f=props.frames.get(st),gen=props.pending.has(st),empty=!f&&!gen;return $jsxs("box",{flexDirection:"column",alignItems:"center",onMouseDown:()=>{if(props.onPick(st),empty)props.onEmpty?.(st)},children:[$jsx("box",{border:!0,borderStyle:"rounded",borderColor:on&&props.focused?theme.primary:on?theme.accent:theme.border,width:18,height:10,overflow:"hidden",alignItems:"center",justifyContent:"center",children:gen?$jsx("text",{fg:theme.accent,children:`${glyph} gen`}):f?f.map((ln,i)=>$jsx("text",{fg:on?theme.text:theme.textMuted,children:ln},i)):$jsx("text",{fg:theme.textMuted,children:"+"})}),$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.accent:theme.textMuted,children:st})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:mark2})})]},st)})})}var BLANK3=Array.from({length:H},()=>" ".repeat(W2)),genCaps=null,probeGen=()=>{if(genCaps)return genCaps;let p=exports_eikon_gen.probeCached();return p.catch(()=>{genCaps=null}),genCaps=p};var EikonStudio=import_react115.memo((props)=>{let theme=useTheme().theme,keys=useKeys(),dialog=useDialog(),gw=useGateway(),toast=useToast(),wide=useTerminalDimensions().width>=120,ksb=import_react115.useRef(null),outer=import_react115.useRef(null);import_react115.useSyncExternalStore(exports_eikon.onRegistry,()=>exports_eikon.rasterizers().length);let[s,setS]=import_react115.useState(null),[pane,setPane]=import_react115.useState("knobs"),[sel,setSel]=import_react115.useState(0),[spSel,setSpSel]=import_react115.useState(0),selRef=import_react115.useRef(0);selRef.current=sel;let spRef=import_react115.useRef(0);spRef.current=spSel;let sRef=import_react115.useRef(null);sRef.current=s;let[frames,setFrames]=import_react115.useState([BLANK3]),[play,setPlay]=import_react115.useState(!0),[busy2,setBusy]=import_react115.useState(!1),[fetching,setFetching]=import_react115.useState(!1),[peek5,setPeek]=import_react115.useState(void 0),[thumbs,setThumbs]=import_react115.useState(new Map),[err,setErr]=import_react115.useState(null),[saving,setSaving]=import_react115.useState(!1),[pending3,setPending]=import_react115.useState(new Set),[genOk,setGenOk]=import_react115.useState(null),stampRef=import_react115.useRef(""),rev2=import_react115.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),r=import_react115.useMemo(()=>exports_eikon.pick(s?.rasterizer??get2("eikonRasterizer")),[s?.rasterizer]),spatialOk=caps3.ffmpeg,open3=import_react115.useCallback((name)=>{resetCache(),stampRef.current=exports_eikon.sourceStamp(name);let seed=exports_eikon.readStudio(name),ra=exports_eikon.pick(seed?.rasterizer??get2("eikonRasterizer")),next2=exports_eikon_knobs.fresh(name,ra,seed),src4=exports_eikon.findSource(name,"idle");next2.dims=src4?exports_eikon.probe(src4)??null:null;for(let st of STATES2){let p=exports_eikon.findSource(name,st);if(p)prewarm(p,next2.fps)}setS(next2),selRow.current=void 0,setSel(0),setPane("knobs"),setErr(null),setFrames([BLANK3])},[]),tried=import_react115.useRef(!1);import_react115.useEffect(()=>{if(tried.current)return;if(tried.current=!0,props.name)return open3(props.name||exports_eikon_knobs.slug("new"));let n=get2("eikon");if(n)open3(n)},[open3,props.name]);let dialogRef=import_react115.useRef(dialog);dialogRef.current=dialog,import_react115.useEffect(()=>{if(props.name===void 0)return;let next2=props.name||exports_eikon_knobs.slug("new"),cur=sRef.current;if(cur?.name===next2)return;if(!cur?.dirty)return open3(next2);let dead=!1;return openConfirm(dialogRef.current,{title:"Discard unsaved edits?",danger:!0,body:`Switch to '${next2}' and drop in-memory changes to '${cur.name}'.`}).then((ok)=>{if(!dead&&ok)open3(next2)}),()=>{dead=!0}},[props.name,open3]),import_react115.useEffect(()=>{let dead=!1;return probeGen().then((c)=>{if(!dead)setGenOk(c)}).catch(()=>{}),()=>{dead=!0}},[]);let stats=import_react115.useMemo(()=>{if(!s)return new Map;return new Map(STATES2.map((st)=>[st,exports_eikon.sourceStatus(s.name,st,{sources:s.sources})]))},[s?.name,s?.sources,rev2]),status=s?stats.get(s.state):void 0,src3=status?.path,live=!!src3,baked2=import_react115.useMemo(()=>{if(live||!s)return;let p=exports_eikon.baked(s.name);if(!p)return;try{return exports_eikon.parseEikonFile(p)}catch{return}},[live,s?.name]),url2=status?.sourceUrl;import_react115.useEffect(()=>{if(setPeek(void 0),!url2||!status?.downloadable)return;let dead=!1;return exports_eikon.peekSource(url2).then((x2)=>{if(!dead)setPeek(x2)}),()=>{dead=!0}},[url2,status?.downloadable]),import_react115.useEffect(()=>{if(!s)return;let stamp2=exports_eikon.sourceStamp(s.name);if(!stampRef.current){stampRef.current=stamp2;return}if(stamp2===stampRef.current)return;if(stampRef.current=stamp2,s.dirty){toast.show({variant:"info",message:"Source changed on disk",duration:3000});return}open3(s.name)},[rev2,s?.name,s?.dirty,open3,toast]);let rows3=import_react115.useMemo(()=>s&&status?buildRows(r,s,status):[],[r,s,status]),navRows=import_react115.useMemo(()=>rows3.map((x2,i)=>({...x2,i})).filter((x2)=>x2.kind!=="divider"&&x2.kind!=="header"),[rows3]),selRow=import_react115.useRef(void 0),rid2=(x2)=>`${x2.kind}:${x2.id}`,setSelBy=import_react115.useCallback((arg)=>{setSel((prev)=>{let next2=typeof arg==="function"?arg(prev):arg,row3=navRows[next2];return selRow.current=row3?rid2(row3):void 0,next2})},[navRows]),prevRows=import_react115.useRef(navRows);import_react115.useEffect(()=>{if(prevRows.current===navRows)return;prevRows.current=navRows;let id=selRow.current;if(!id)return;let ni=navRows.findIndex((x2)=>rid2(x2)===id);if(ni>=0&&ni!==selRef.current)setSel(ni)},[navRows]);let kScroll=(ni)=>{let row3=navRows[ni];if(row3)ksb.current?.scrollChildIntoView(`knob-${row3.kind}-${row3.id}`)};import_react115.useEffect(()=>{if(!s)return;if(!src3){let clip=baked2?.states.get(s.state);setFrames(clip?.frames.length?clip.frames:[BLANK3]),setErr(null),setBusy(!1);return}let ctrl=new AbortController;return setBusy(!0),cached2(r,src3,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,s.state),ctrl.signal).then((out)=>{if(ctrl.signal.aborted)return;if(setBusy(!1),"err"in out){setErr(out.err);return}setErr(null),setFrames(out.frames)}),()=>ctrl.abort()},[s?.spatial,s?.tone,s?.base,s?.per,s?.state,s?.fps,s?.rasterizer,src3,r,baked2]),import_react115.useEffect(()=>{if(!s)return;let dead=!1,t2=setTimeout(()=>{if(dead)return;let jobs=STATES2.map((st)=>{let sp=stats.get(st)?.path;if(!sp){let f=baked2?.states.get(st)?.frames[0];return Promise.resolve([st,f?thumb(f):void 0])}return cached2(r,sp,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,st)).then((res)=>[st,"err"in res?void 0:thumb(res.frames[0])])});Promise.all(jobs).then((done)=>{if(dead)return;setThumbs(new Map(done))})},400);return()=>{dead=!0,clearTimeout(t2)}},[frames,s?.per,s?.sources,s?.name,s?.fps,r,baked2,stats]);let mutate=(fn)=>setS((p)=>p?fn(p):p),setSpatial=(sp)=>mutate((p)=>({...p,spatial:{...p.spatial,...sp},dirty:!0})),setBar=(k2,v2)=>k2==="fps"?mutate((p)=>({...p,fps:Math.round(v2),dirty:!0})):setSpatial({[k2]:v2}),stepBar=(k2,d2)=>{let cur=sRef.current;if(!cur)return;if(k2==="fps")return setBar("fps",Math.max(4,Math.min(30,cur.fps+d2*2)));if(k2==="zoom")return setSpatial({zoom:Math.max(0.1,Math.min(1,+(cur.spatial.zoom+d2*0.03).toFixed(3)))});return setSpatial({[k2]:Math.max(0,Math.min(1,+(cur.spatial[k2]+d2*0.03).toFixed(3)))})},doSave=import_react115.useCallback(async()=>{if(!s)return!1;if(!s.dirty)return toast.show({variant:"info",message:"Nothing to save"}),!0;if(!live)return toast.show({variant:"warning",message:"No source \u2014 download or attach before saving"}),!1;setSaving(!0);try{let f=await exports_eikon.save({...s,dirty:!1});return mutate((p)=>({...p,dirty:!1})),toast.show({variant:"success",message:`Saved \u2192 ${basename11(f)}`}),!0}catch(e){return toast.error(e instanceof Error?e:Error(String(e))),!1}finally{setSaving(!1)}},[s,live,toast]),doSaveUse=import_react115.useCallback(async()=>{if(!s)return;if(!await doSave())return;exports_eikon.useInstalled(s.name),toast.show({variant:"success",message:`Avatar \u2192 ${s.name}`})},[doSave,s,toast]),doSelectRasterizer=()=>{let opts=exports_eikon.rasterizers().map((x2)=>{let a=x2.available();return{title:x2.name,value:x2.name,description:Object.keys(x2.knobs).join(" \xB7 "),hint:a===!0?void 0:a}});dialog.replace($jsx(DialogSelect,{title:"Rasterizer",filterable:!1,current:r.name,options:opts,onSelect:(o)=>{dialog.clear();let next2=exports_eikon.rasterizer(o.value);if(!next2)return;let a=next2.available();if(a!==!0)return toast.show({variant:"warning",message:`${o.value}: ${a}`});set("eikonRasterizer",o.value),mutate((p)=>exports_eikon_knobs.swap(p,next2))}}),()=>{})},runGenerate=async(st,kind2)=>{if(!s)return;let seed=stats.get("idle")?.path;setPending((prev)=>{let n=new Set(prev);return n.add(st),n});let out=await openGenerate(dialog,exports_eikon_gen.current(),{state:st,kind:kind2,seed,lastPrompt:s.prompts?.[st]});if(!out){setPending((prev)=>{let n=new Set(prev);return n.delete(st),n});return}let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,out.path,role);mutate((p)=>({...p,sources:{...p.sources,[role]:f},prompts:{...p.prompts,[st]:out.prompt},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}finally{setPending((prev)=>{let n=new Set(prev);return n.delete(st),n})}},download=async()=>{if(!s||fetching)return;setFetching(!0),await exports_eikon.downloadSource(s.name).then((out)=>{if(toast.show({variant:"success",message:`Downloaded ${out.n} file(s) \xB7 ${mb2(out.bytes)}`}),sRef.current?.dirty)mutate((prev)=>({...prev,sources:{...out.sources,...prev.sources}}));else open3(s.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e)))).finally(()=>setFetching(!1))},doSource=(forSt)=>{if(!s)return;let st=forSt??s.state,info2=stats.get(st)??exports_eikon.sourceStatus(s.name,st,{sources:s.sources}),own=info2.role===st||st==="idle"&&info2.role==="base"||s.sources[st]!==void 0,loc=exports_eikon.localSources(s.name),opts=[...info2.downloadable?[{title:"Download source",value:"download"}]:[],...loc.map((x2)=>({title:x2.file,value:`pick:${x2.file}`,hint:x2.role??"source"})),...genOk?.image?[{title:"Generate image\u2026",value:"gen-image"}]:[],...genOk?.video?[{title:"Generate video\u2026",value:"gen-video"}]:[],{title:"Local file\u2026",value:"local"},...st!=="idle"&&own?[{title:"Same as base",value:"same"}]:[],...own?[{title:"Remove",value:"remove"}]:[]];dialog.replace($jsx(DialogSelect,{title:`Source for '${st}'`,filterable:!1,options:opts,onSelect:async(o)=>{if(o.value==="download"){dialog.clear(),await download();return}if(o.value.startsWith("pick:")){dialog.clear();let file2=o.value.slice(5),role=st==="idle"&&loc.find((x2)=>x2.file===file2)?.role==="base"?"base":st;mutate((prev)=>({...prev,sources:{...prev.sources,[role]:file2},dirty:!0}));return}if(o.value==="local"){let p=await openPathPrompt(dialog,gw,{title:`Source for '${st}'`,label:"png/jpg/webp/gif/mp4/webm/mov \xB7 Tab completes",filter:/\.(png|jpe?g|webp|gif|mp4|webm|mov)$/i});if(!p)return;let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,p,role);mutate((prev)=>({...prev,sources:{...prev.sources,[role]:f},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}return}if(o.value==="gen-image")return void runGenerate(st,"image");if(o.value==="gen-video")return void runGenerate(st,"video");dialog.clear(),mutate((prev)=>({...prev,sources:{...prev.sources,[st==="idle"?"base":st]:null},dirty:!0}))}}),()=>{})},doPrompt=async(id)=>{if(!s)return;if(id==="source")return doSource()},switchTo=import_react115.useCallback(async(name)=>{let cur=sRef.current;if(cur?.name===name)return;if(cur?.dirty){if(!await openConfirm(dialog,{title:"Discard unsaved edits?",danger:!0,body:`Open '${name}' and drop in-memory changes to '${cur.name}'.`}))return}open3(name)},[dialog,open3]),apply=import_react115.useCallback(async(res)=>{if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),switchTo(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return switchTo(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[switchTo,toast]),doNew=import_react115.useCallback(async()=>{let res=await openNewEikon(dialog,{});await apply(res)},[dialog,apply]),eikonOptions=import_react115.useCallback(()=>{let installed=exports_eikon.list().map((e)=>({title:e.name,value:e.name,category:"installed",hint:e.hasSource?"\u25CF source":e.sourceUrl?"\u25CB source available":"\u2014"})),seen=new Set(installed.map((o)=>o.value)),bundled=listEikons([BUNDLED_EIKON_DIR,hermesPath("eikons")]).filter((e)=>e.path.startsWith(BUNDLED_EIKON_DIR)).map((e)=>{let slug3=e.meta.name.toLowerCase();return{title:e.meta.name,value:slug3,category:"bundled",hint:`${e.meta.width}\xD7${e.meta.height}`}}).filter((o)=>!seen.has(o.value)),raw2=exports_eikon.raw().filter((n)=>!seen.has(n)).map((n)=>({title:n,value:n,category:"installed",hint:"(unsaved)"}));return[...installed,...raw2,...bundled]},[]),doInstall=import_react115.useCallback(async()=>{let src4=await openTextPrompt(dialog,{title:"Inspect eikon source",label:"catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir"});if(!src4)return;let info2;try{info2=await exports_eikon.inspectSource(src4)}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}if(!await openConfirm(dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use Ctrl+U or Library after install to select it."].join(`
|
|
4143
|
-
`),yes:"install",no:"cancel"}))return;toast.show({variant:"info",message:`Installing from ${src4}\u2026`}),await exports_eikon.installPackage(src4).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,switchTo,toast]),doOpen=import_react115.useCallback(()=>{let cur=sRef.current,opts=[...eikonOptions(),{title:"+ New\u2026",value:"__new",category:""},{title:"+ Install\u2026",value:"__install",category:""}];dialog.replace($jsx(DialogSelect,{title:"Open eikon",current:cur?.name,options:opts,onSelect:(o)=>{if(dialog.clear(),o.value==="__new")return void doNew();if(o.value==="__install")return void doInstall();switchTo(o.value)}}),()=>{})},[dialog,eikonOptions,switchTo,doNew,doInstall]),doSubmit=import_react115.useCallback(async()=>{let cur=sRef.current;if(!cur)return;let path4=submitPath(cur.name);if(publishedInfo(path4)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}if(cur.dirty||!existsSync23(path4)){let pick2=await openSaveDiscard(dialog,{title:"Save before submit?",body:`'${cur.name}' has unsaved changes. Save to submit the current preview, discard to submit the last saved artifact, or keep editing.`});if(pick2==="save"){if(get2("eikon")===cur.name){if(!await openConfirm(dialog,{title:`Save active '${cur.name}' before submit?`,danger:!0,body:"Saving changes the active avatar's backing artifact. Submit itself will not change active selection.",yes:"save",no:"cancel"}))return}if(!await doSave())return}else if(pick2==="discard")open3(cur.name);else return}if(!existsSync23(path4)){toast.show({variant:"warning",message:"Save this eikon before submitting"});return}await openEikonSubmit(dialog,{name:cur.name,path:path4,submit:submit2})},[dialog,doSave,open3,toast]),doAction=async(id)=>{if(!s)return;if(id==="knobsfor")return mutate((p)=>p.per[p.state]?exports_eikon_knobs.unfork(p):exports_eikon_knobs.fork(p));if(id==="submit"){doSubmit();return}if(id==="revert"){discard();return}if(id==="reset"){if(await openConfirm(dialog,{title:"Reset settings?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!status?.downloadable||fetching)return;await download()}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Source\u2026",value:"source"},{title:s.per[s.state]?"Clear override (back to base)":"Tune this state only",value:"fork"}],onSelect:(o)=>{if(o.value==="source"){doSource();return}dialog.clear(),mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},setTone=(t2)=>mutate((p)=>({...p,tone:{...p.tone,...t2},dirty:!0})),stepRow=(row3,d2)=>{if(row3.kind==="tone"){if(row3.id==="contrast"){let def2=row3.knob,cur=sRef.current?.tone.contrast??1;return setTone({contrast:+Math.max(def2.min,Math.min(def2.max,cur+d2*def2.step)).toFixed(2)})}if(row3.id==="invert")return setTone({invert:!sRef.current?.tone.invert});if(row3.id==="flip"){let cur=sRef.current?.tone.flip??"none",i=FLIPS.indexOf(cur);return setTone({flip:FLIPS[(i+d2+FLIPS.length)%FLIPS.length]})}return}if(row3.kind!=="knob"||!row3.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row3.id,row3.knob,d2)))},act=(row3,via)=>{if(!row3||!sRef.current)return;if(row3.kind==="select"){if(row3.id==="open")return doOpen();return doSelectRasterizer()}if(row3.kind==="prompt")return void doPrompt(row3.id);if(row3.kind==="action"){if(via==="space"&&row3.id==="reset")return;return void doAction(row3.id)}if(row3.kind==="tone"||row3.kind==="knob"){if(row3.knob.kind==="slider")return;return stepRow(row3,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row3=navRows[selRef.current];if(!row3)return;if(row3.id==="knobsfor")return void doAction("knobsfor");stepRow(row3,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;let pick2=await openSaveDiscard(dialog,{title:"Unsaved edits",body:`'${cur.name}' has unsaved changes. Save them, discard them, or keep editing?`});if(pick2==="save"){if(await doSave())open3(cur.name);return!0}if(pick2==="discard")open3(cur.name);return!0},refresh=import_react115.useCallback(()=>{let cur=sRef.current;if(!cur)return;if(stampRef.current=exports_eikon.sourceStamp(cur.name),cur.dirty){toast.show({variant:"info",message:"Reload skipped: unsaved edits",duration:3000});return}open3(cur.name),toast.show({variant:"info",message:"Reloaded",duration:1000})},[open3,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(key3.eventType==="release")return;if(key3.name==="u"&&key3.ctrl&&sRef.current)return void doSaveUse();if(key3.name==="u"&&sRef.current)return void doSubmit();if(keys.match("eikon.save",key3)){if(!saving)doSave();return}if(key3.name==="escape")return void discard();if(key3.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key3.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key3.name==="return")return void doNew();return}if(pane==="knobs"){if(handleListKey(keys,key3,{count:navRows.length,setSel:setSelBy,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doNew(),onRefresh:refresh}))return;if(key3.name==="left")return adjust(-1);if(key3.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key3))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key3,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key3.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key3.name==="left"||key3.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key3.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key3.name))}return}if(key3.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key3.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key3.name==="return")return doStripMenu()});let onScroll=(e)=>{if(e.stopPropagation(),!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;let sign=d2==="up"?-1:1;if(e.modifiers.ctrl)return mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,sign),dirty:!0}));if(e.modifiers.shift)return mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,sign,0),dirty:!0}));mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,0,sign),dirty:!0}))},previewErr=err??(!s||src3||baked2?null:url2?"no source \u2014 Enter on 'download source'":"no source \u2014 Enter on 'source'"),hint=!s?[["Enter","new eikon"],["Shift+\u2192","library"]]:pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"edit"],[keys.print("list.refresh"),"reload"],[keys.print("list.new"),"new"],["u","submit"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","pan"],["Ctrl+wheel","zoom"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),preview2=$jsx(PreviewPane,{s,frames,play,setPlay,focused:Boolean(props.focused),busy:busy2,live,baked:baked2,spatialOk,error:previewErr,pane,sel:spSel,onPane:setPane,onSel:setSpSel,onSet:setBar,onWheel:stepBar,onScroll}),help=helpOf(navRows[sel]),panel=$jsx(TabShell,{title:s?`Settings \u2014 ${s.name}`:"Settings",focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create or pick one."})}):$jsxs($Fragment,{children:[$jsx("scrollbox",{id:"studio-knob-scroll",ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,onMouseScroll:(e)=>e.stopPropagation(),children:rows3.map((row3,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row3.kind==="knob"&&!src3;return $jsx(KnobRow,{id:`knob-${row3.kind}-${row3.id}`,row:row3,s,r,status,on,dim:dim2,peek:peek5,busy:row3.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSelBy(ni)},onClick:()=>{if(ni>=0)setSelBy(ni),setPane("knobs"),act(row3,"click")},onWheel:(d2)=>stepRow(row3,d2),onSlide:row3.knob?.kind!=="slider"?void 0:row3.kind==="tone"?(v2)=>setTone({contrast:+v2.toFixed(2)}):(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row3.id,row3.knob,v2)))},`${row3.kind}:${r.name}:${row3.id}`)})}),$jsx("box",{flexShrink:0,height:HELP_H,marginTop:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:help})})]})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:18,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,stats,pending:pending3,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))},onEmpty:(st)=>doSource(st)})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+HELP_H+1+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:saving?"\u25CF saving\u2026":s?.dirty?"\u25CF unsaved":void 0})]})});var import_react117=__toESM(require_react_production(),1);import{existsSync as existsSync24,readFileSync as readFileSync15}from"fs";import{basename as basename12,dirname as dirname12,join as join18}from"path";var EIKON_CARD=50,titleWidth=(title,rows3)=>Math.max(title.length,...rows3.map((r)=>r.name.length+4))+7,cardWidth=(lines3)=>Math.max(EIKON_CARD,...lines3.map((line4)=>line4.length+2)),EikonTitleList=(props)=>{let theme=useTheme().theme;return $jsx("box",{width:props.width,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:props.title,focus:props.focus,grow:1,children:$jsx("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:$jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"row",height:1,paddingRight:3,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,children:[r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})})]},r.key)})})})})})},EikonCardGrid=(props)=>{let theme=useTheme().theme;if(props.rows.length===0)return $jsx("box",{padding:1,children:props.empty??$jsx("text",{fg:theme.textMuted,children:"No eikons found."})});return $jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"row",flexWrap:"wrap",width:"100%",flexShrink:0,children:props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"column",height:r.lines.length+2,width:cardWidth(r.lines),flexShrink:0,paddingX:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{height:r.lines.length,overflow:"hidden",flexDirection:"column",children:r.lines.map((line4,j2)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:line4||" "})},j2))}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:[on?"\u25B8 ":" ",r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.author??"unknown"," \xB7 ",r.status]})})]},r.key)})})})};var PREVIEW2=54,EikonGallery=import_react117.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),rev2=import_react117.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),dims=useTerminalDimensions(),rows3=import_react117.useMemo(()=>{let user=hermesPath("eikons"),own=exports_eikon.list(),map=new Map(own.map((x2)=>[x2.name.toLowerCase(),x2])),meta=own.map((x2)=>({inst:x2,ids:ids2(x2.manifest,x2.name,x2.sourceUrl)}));return[...listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():dirname12(e.path)===user?basename12(e.path,".eikon"):basename12(dirname12(e.path)),man=manifest4(dirname12(e.path)),keys2=ids2(man,slug3),mine=meta.find((x2)=>x2.ids.some((k2)=>keys2.includes(k2)))?.inst??map.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,url:mine?.sourceUrl,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3),lifecycle:mine?.lifecycle,...man?{manifest:man}:{}}}).filter((r)=>!(r.bundled&&r.lifecycle)).reduce((map2,row3)=>{let prev=map2.get(row3.slug);if(!prev||dirname12(prev.path)===user&&dirname12(row3.path)!==user)map2.set(row3.slug,row3);return map2},new Map).values()]},[rev2]),active=usePref("eikon"),path4=import_react117.useMemo(()=>active?exports_eikon.baked(active):void 0,[active,rev2]),current2=(row3)=>path4===row3.path,[sel,setSel]=import_react117.useState(0),[pane,setPane]=import_react117.useState("list"),[act,setAct]=import_react117.useState(0),galleryFollow=useFollow("gal",(i)=>rows3[i]?.slug??i),gridFollow=useFollow("lib-grid",(i)=>rows3[i]?.slug??i);import_react117.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],parsed=import_react117.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]),activate=(row3=cur)=>{if(!row3)return;if(row3.bundled)set("eikon",row3.slug);else exports_eikon.useInstalled(row3.slug);toast.show({variant:"success",message:`Avatar \u2192 ${row3.name}`})},doNew=import_react117.useCallback(async()=>{let res=await openNewEikon(dialog,{});if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),props.onEdit?.(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return props.onEdit?.(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,toast,props]),updateLocal=import_react117.useCallback(async()=>{if(!cur||cur.bundled)return;try{let out=await exports_eikon.update(cur.slug);if("type"in out){if(!await openConfirm(dialog,{title:`Update active '${cur.name}'?`,danger:!0,body:`${out.message} The active avatar's backing package will change even though the selected name stays '${cur.slug}'.`,yes:"update active",no:"cancel"}))return;let done=await exports_eikon.update(cur.slug,{confirmActive:!0});if("type"in done)return toast.show({variant:"warning",message:done.message})}toast.show({variant:"success",message:`Updated ${cur.name}`})}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}},[cur,dialog,toast]),submitLocal=import_react117.useCallback(async()=>{if(!cur||cur.bundled)return;let path6=submitPath(cur.slug);if(publishedInfo(path6)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path6,submit:props.submit??submit2})},[cur,dialog,props.submit,toast]),del=async()=>{if(!cur||cur.bundled)return;let here=current2(cur),base3=dirname12(cur.path)===hermesPath("eikons")?`Removes legacy flat file ${basename12(cur.path)}.`:`Removes ${dirname12(cur.path)} and all its sources.`,body=here?`${base3} This is the active avatar; deleting it will clear the active avatar selection.`:base3;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body}))return;let removed=exports_eikon.remove(cur.slug,{confirmActive:here});if(removed)return toast.show({variant:"warning",message:removed.message});toast.show({variant:"info",message:`Deleted ${cur.name}`})},actions=import_react117.useMemo(()=>{if(!cur)return[];return[{key:"Enter",label:current2(cur)?"Use as active avatar (active)":"Use as active avatar",run:()=>activate()},...props.onEdit?[{key:"e",label:"Edit in Studio",run:()=>props.onEdit?.(cur.slug)}]:[],...!cur.bundled?[{key:"u",label:"Update local package",run:()=>void updateLocal()},{key:"s",label:"Share to catalog",run:()=>void submitLocal()},{key:"d",label:"Delete local eikon",run:()=>void del(),danger:!0}]:[]]},[cur,path4,props.onEdit,updateLocal,submitLocal]);import_react117.useEffect(()=>{if(act>=actions.length)setAct(Math.max(0,actions.length-1))},[act,actions.length]);let cards=import_react117.useMemo(()=>rows3.map((r)=>{let p=(()=>{try{return parseEikonFile(r.path)}catch{return}})(),lines3=p?.resolve("state.idle")?.frames[0]??p?.states.get("idle")?.frames[0]??["(no preview)"];return{key:r.path,name:r.name,active:current2(r),author:r.author,status:current2(r)?"active":r.bundled?"bundled/system":"installed",lines:lines3}}),[rows3,path4]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;let plain=!key3.shift&&!key3.ctrl&&!key3.meta;if(key3.name==="tab")return setPane((p)=>p==="list"?"actions":"list");if(pane==="actions"){if(key3.name==="escape"||plain&&key3.name==="left"){setPane("list");return}if(plain&&key3.name==="up"){setAct((i)=>Math.max(0,i-1));return}if(plain&&key3.name==="down"){setAct((i)=>Math.min(actions.length-1,i+1));return}if(keys.match("list.activate",key3)||keys.match("list.toggle",key3)){actions[act]?.run();return}return}if(handleListKey(keys,key3,{count:rows3.length,setSel,page:galleryFollow.opts.page,scrollTo:(n)=>galleryFollow.ref.current?.scrollChildIntoView(galleryFollow.id(n)),onActivate:()=>activate(),onDelete:()=>void del(),onNew:doNew,onRefresh:()=>{exports_eikon.notifyRevision(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}))return;if(key3.name==="u"&&cur&&!cur.bundled)return void updateLocal();if(key3.name==="s"&&cur&&!cur.bundled)return void submitLocal();if(key3.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)});let listW=Math.max(13,...rows3.map((r)=>r.name.length+4))+7,showGrid=dims.width-listW-PREVIEW2>=EIKON_CARD;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minHeight:0,children:[$jsx(EikonTitleList,{title:`Library (${rows3.length})`,rows:rows3.map((r)=>({key:r.path,name:r.name,active:current2(r)})),sel,focus:props.focused&&pane==="list",follow:galleryFollow,width:listW,onSel:setSel,onUse:(i)=>activate(rows3[i])}),showGrid?$jsx(TabShell,{title:"Grid",grow:1,children:$jsx(EikonCardGrid,{rows:cards,sel,follow:gridFollow,onSel:setSel,onUse:(i)=>activate(rows3[i])})}):null,$jsx("box",{width:PREVIEW2,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:1,children:$jsxs("box",{flexDirection:"column",flexGrow:1,padding:1,alignItems:"center",children:[$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})}),cur?$jsxs("box",{flexDirection:"column",width:48,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:cur.name})}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",cur.author??"\u2014"]}),$jsxs("text",{fg:theme.textMuted,children:["Status: ",current2(cur)?"active":cur.bundled?"bundled/system":"installed"]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Source: ",gallerySource(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Trust: ",galleryTrust(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Package: ",packageId(cur)]}),$jsx("text",{fg:theme.textMuted,children:sourceBadge(cur)}),$jsx("box",{height:1}),$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Actions"})}),actions.map((a,i)=>$jsx("box",{height:1,overflow:"hidden",paddingRight:1,backgroundColor:pane==="actions"&&i===act?theme.backgroundElement:void 0,onMouseDown:()=>{setPane("actions"),setAct(i),a.run()},children:$jsxs("text",{fg:a.danger?theme.error:theme.text,wrapMode:"none",children:[pane==="actions"&&i===act?"\u25B8 ":" ",a.label," [",a.key,"]"]})},a.label))]}):null]})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="list"?"actions":"library"],[keys.print("list.activate"),pane==="actions"?"run action":"use"],["\u2191\u2193",pane==="actions"?"action":"select"],[keys.print("list.new"),"new / install"],[keys.print("list.refresh"),"reload"],...cur&&props.onEdit?[["e","edit in Studio"]]:[]]})]})}),galleryTrust=(row3)=>{let t2=row3.lifecycle?.trust;if(t2==="verified")return"Verified";if(t2==="mismatch")return"Mismatch";if(t2==="unverified")return"Unverified";return row3.bundled?"Bundled":"Legacy local"},gallerySource=(row3)=>{let src3=row3.lifecycle?.source;if(src3)return src3.identity??src3.repo??src3.origin??src3.kind;if(row3.bundled)return"bundled/system";return"local"},packageId=(row3)=>typeof row3.manifest?.id==="string"?row3.manifest.id:row3.bundled?"bundled/system":"\u2014",manifest4=(dir2)=>{let file2=join18(dir2,"manifest.json");if(!existsSync24(file2))return;try{let raw2=JSON.parse(readFileSync15(file2,"utf8"));return raw2&&typeof raw2==="object"&&!Array.isArray(raw2)?raw2:void 0}catch{return}},sourceBadge=(row3)=>row3.hasSource?"\u25CF source":row3.url||row3.bundled?"\u25CB source available":"\u2014 no source",key3=(value2)=>{try{let url2=new URL(value2);if(url2.protocol==="http:"||url2.protocol==="https:"||url2.protocol==="file:")return url2.href.replace(/\/?$/,"/").toLowerCase()}catch{}return value2.toLowerCase()},ids2=(man,name,url2)=>{let origin2=man?.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:void 0;return[...new Set([typeof man?.id==="string"?man.id:void 0,typeof origin2?.sourceKey==="string"?origin2.sourceKey:void 0,typeof origin2?.identityKey==="string"?origin2.identityKey:void 0,typeof origin2?.packageUrl==="string"?origin2.packageUrl:void 0,typeof origin2?.source==="string"?origin2.source:void 0,url2,name].filter((x2)=>!!x2).map(key3))]};var import_react120=__toESM(require_react_production(),1);var import_react119=__toESM(require_react_production(),1);var fmt3=(n)=>n==null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(1)} KiB`:`${(n/1024/1024).toFixed(1)} MiB`,choices=(row3,sizes)=>{if(row3.installState==="incompatible"||row3.installState==="mismatch")return[{label:"Delist from Registry",value:"delist"}];if(!row3.installed)return[{label:"Eikon only",hint:fmt3(sizes?.eikon),value:"install"},{label:"Eikon + Source",hint:`${fmt3((sizes?.eikon??0)+(sizes?.source??0))} \xB7 Source files needed to edit Eikon in Studio`,value:"source"},{label:"Delist from Registry",value:"delist"}];return[...!row3.active?[{label:"Use",hint:"set as active avatar",value:"use"}]:[],...row3.sourceDownloadable?[{label:"Download Source",hint:"needed to edit in Studio",value:"download"}]:[],...row3.removable?[{label:"Uninstall",value:"delete"}]:[],{label:"Delist from Registry",value:"delist"}]},Action=(props)=>{let theme=useTheme().theme,opts=choices(props.row,props.sizes),[sel,setSel]=import_react119.useState(0),desc=opts.some((o)=>!!o.hint);return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.row.entry.name})}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.row.entry.description??"No description."}),$jsx("box",{height:1}),opts.length>0?$jsx("select",{focused:!0,width:62,height:Math.min(12,Math.max(1,opts.length*(desc?2:1))),options:opts.map((o)=>({name:o.label,description:o.hint??"",value:o.value})),selectedIndex:Math.min(sel,opts.length-1),showDescription:desc,showScrollIndicator:opts.length>6,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"},{name:"return",action:"select-current"}],onChange:(i)=>setSel(i),onSelect:(i)=>{let opt=opts[i];if(opt)props.onPick(opt.value)}}):$jsx("text",{fg:theme.textMuted,children:props.row.reason??"No available actions."}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"[\u2191\u2193] move [Space/Enter] confirm [Esc] cancel"})]})};function openEikonMarketplaceAction(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Action,{...opts,onPick:done}),()=>resolve4(null))})}init_perf();import{existsSync as existsSync25,readFileSync as readFileSync16,readdirSync as readdirSync9,writeFileSync as writeFileSync8}from"fs";import{createHash as createHash7}from"crypto";import{basename as basename13,dirname as dirname13,extname as extname3,join as join19}from"path";import{Buffer as Buffer6}from"buffer";var REPO2=process.env.EIKON_REPO??"liftaris/eikon",HOST="eikon.liftaris.dev",enc2=new TextEncoder;async function gh2(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?enc2.encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code2]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code2!==0)throw Error(err.trim()||out.trim()||`gh ${args[0]} failed`);return out.trim()}function json(text3){return JSON.parse(text3)}function clean4(value2){return value2.replace(/[^A-Za-z0-9_.-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function pkg(entry3){let parts2=entry3.id.includes("/")?entry3.id.split("/"):["liftaris",entry3.name];return{ns:parts2[0]||"liftaris",name:parts2[1]||entry3.name}}function dirs(entry3){let p=pkg(entry3);return[`eikons/${entry3.name}/`,`packages/${p.ns}/${p.name}/`]}function touches(entry3,path4){return dirs(entry3).some((dir2)=>path4.startsWith(dir2))}function official(entry3){try{return new URL(entry3.packageUrl).hostname===HOST&&[entry3.sourceKey,entry3.identityKey].some((key4)=>key4?.startsWith(`registry:${HOST}:`))}catch{return!1}}async function user(run){return run(["api","user","-q",".login"])}async function prs(entry3,repo2,run){let exact=(xs)=>xs.filter((pr)=>pr.title===`eikons: submit ${entry3.name}`&&pr.headRefName===`submit/${entry3.name}`),at=(pr)=>Number.isFinite(Date.parse(pr.mergedAt??""))?Date.parse(pr.mergedAt??""):0,sort=(xs)=>xs.toSorted((a,b2)=>at(a)-at(b2)||a.number-b2.number),first=exact(json(await run(["pr","list","-R",repo2,"--state","merged","--search",`"eikons: submit ${entry3.name}" in:title`,"--json","number,title,headRefName,url,mergedAt,author","--limit","100"])));if(first.length)return sort(first);return sort(exact(json(await run(["pr","list","-R",repo2,"--state","merged","--json","number,title,headRefName,url,mergedAt,author","--limit","100"]))))}async function files(repo2,pr,run){return(await run(["api","--paginate","-X","GET",`repos/${repo2}/pulls/${pr}/files`,"--jq",".[].filename"])).split(/\r?\n/).filter(Boolean).map((path4)=>({path:path4}))}async function found(entry3,repo2,run){for(let pr of await prs(entry3,repo2,run)){let title=pr.title===`eikons: submit ${entry3.name}`,head=pr.headRefName===`submit/${entry3.name}`;if(!title||!head)continue;if((await files(repo2,pr.number,run)).some((f)=>touches(entry3,f.path??f.filename??"")))return pr}return}async function info2(entry3,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2;if(!official(entry3))return{eligible:!1,reason:"Registry delist is only available for official Eikon catalog entries"};let login;try{login=await user(run)}catch(err){return{eligible:!1,reason:err instanceof Error?err.message:String(err)}}let pr=await found(entry3,repo2,run),author=pr?.author?.login;if(!pr||!author)return{eligible:!1,user:login,reason:"No merged GitHub submission found"};if(author!==login)return{eligible:!1,user:login,author,pr:pr.number,url:pr.url,reason:`Submitted by @${author}`};return{eligible:!0,user:login,author,pr:pr.number,url:pr.url}}async function exists(run,repo2,branch2,path4){try{let raw2=await run(["api","-X","GET",`repos/${repo2}/contents/${path4}`,"-f",`ref=${branch2}`]);return json(raw2).sha}catch{return}}async function put2(run,repo2,branch2,path4,text3,msg){let sha2=await exists(run,repo2,branch2,path4);await run(["api","-X","PUT",`repos/${repo2}/contents/${path4}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,content:Buffer6.from(text3).toString("base64"),...sha2?{sha:sha2}:{}}))}async function del(run,repo2,branch2,path4,sha2,msg){await run(["api","-X","DELETE",`repos/${repo2}/contents/${path4}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,sha:sha2}))}async function main(run,repo2){let sha2=await run(["api",`repos/${repo2}/git/ref/heads/main`,"-q",".object.sha"]),tree2=await run(["api",`repos/${repo2}/git/commits/${sha2}`,"-q",".tree.sha"]);return{sha:sha2,tree:tree2}}async function tree2(run,repo2,sha2){return json(await run(["api","-X","GET",`repos/${repo2}/git/trees/${sha2}`,"-f","recursive=1"])).tree??[]}async function index3(run,repo2){let raw2=json(await run(["api","-X","GET",`repos/${repo2}/contents/eikons/index.json`,"-f","ref=main"]));return Buffer6.from((raw2.content??"").replace(/\s/g,""),"base64").toString("utf8")}async function reset3(run,repo2,name,sha2){try{await run(["api","-X","POST",`repos/${repo2}/git/refs`,"-f",`ref=refs/heads/${name}`,"-f",`sha=${sha2}`])}catch{await run(["api","-X","PATCH",`repos/${repo2}/git/refs/heads/${name}`,"--input","-"],JSON.stringify({sha:sha2,force:!0}))}}async function pr(run,repo2,user2,branch2,name,body){try{return await run(["pr","create","-R",repo2,"-H",`${user2}:${branch2}`,"-B","main","-t",`eikons: delist ${name}`,"-b",body])}catch{let raw2=await run(["api","-X","GET",`repos/${repo2}/pulls`,"-f","state=open","-f",`head=${user2}:${branch2}`]),hit2=json(raw2)[0]?.url;if(hit2)return hit2;throw Error("GitHub PR creation failed")}}async function submit3(entry3,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2,own=await info2(entry3,{repo:repo2,run});if(!own.eligible||!own.user)throw Error(own.reason??"not authorized to delist this eikon");await run(["repo","fork",repo2,"--clone=false"]).catch(()=>"");let fork2=`${own.user}/${repo2.split("/")[1]}`,branch2=`delist/${clean4(entry3.name)}`,base3=await main(run,repo2);await reset3(run,fork2,branch2,base3.sha);let msg=`eikons: delist ${entry3.name}`,next2=json(await index3(run,repo2)).filter((e)=>e.name!==entry3.name&&e.id!==entry3.id);await put2(run,fork2,branch2,"eikons/index.json",`${JSON.stringify(next2,null,2)}
|
|
4143
|
+
`),yes:"install",no:"cancel"}))return;toast.show({variant:"info",message:`Installing from ${src4}\u2026`}),await exports_eikon.installPackage(src4).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,switchTo,toast]),doOpen=import_react115.useCallback(()=>{let cur=sRef.current,opts=[...eikonOptions(),{title:"+ New\u2026",value:"__new",category:""},{title:"+ Install\u2026",value:"__install",category:""}];dialog.replace($jsx(DialogSelect,{title:"Open eikon",current:cur?.name,options:opts,onSelect:(o)=>{if(dialog.clear(),o.value==="__new")return void doNew();if(o.value==="__install")return void doInstall();switchTo(o.value)}}),()=>{})},[dialog,eikonOptions,switchTo,doNew,doInstall]),doSubmit=import_react115.useCallback(async()=>{let cur=sRef.current;if(!cur)return;let path4=submitPath(cur.name);if(publishedInfo(path4)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}if(cur.dirty||!existsSync23(path4)){let pick2=await openSaveDiscard(dialog,{title:"Save before submit?",body:`'${cur.name}' has unsaved changes. Save to submit the current preview, discard to submit the last saved artifact, or keep editing.`});if(pick2==="save"){if(get2("eikon")===cur.name){if(!await openConfirm(dialog,{title:`Save active '${cur.name}' before submit?`,danger:!0,body:"Saving changes the active avatar's backing artifact. Submit itself will not change active selection.",yes:"save",no:"cancel"}))return}if(!await doSave())return}else if(pick2==="discard")open3(cur.name);else return}if(!existsSync23(path4)){toast.show({variant:"warning",message:"Save this eikon before submitting"});return}await openEikonSubmit(dialog,{name:cur.name,path:path4,submit:submit2})},[dialog,doSave,open3,toast]),doAction=async(id)=>{if(!s)return;if(id==="knobsfor")return mutate((p)=>p.per[p.state]?exports_eikon_knobs.unfork(p):exports_eikon_knobs.fork(p));if(id==="submit"){doSubmit();return}if(id==="revert"){discard();return}if(id==="reset"){if(await openConfirm(dialog,{title:"Reset settings?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!status?.downloadable||fetching)return;await download()}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Source\u2026",value:"source"},{title:s.per[s.state]?"Clear override (back to base)":"Tune this state only",value:"fork"}],onSelect:(o)=>{if(o.value==="source"){doSource();return}dialog.clear(),mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},setTone=(t2)=>mutate((p)=>({...p,tone:{...p.tone,...t2},dirty:!0})),stepRow=(row3,d2)=>{if(row3.kind==="tone"){if(row3.id==="contrast"){let def2=row3.knob,cur=sRef.current?.tone.contrast??1;return setTone({contrast:+Math.max(def2.min,Math.min(def2.max,cur+d2*def2.step)).toFixed(2)})}if(row3.id==="invert")return setTone({invert:!sRef.current?.tone.invert});if(row3.id==="flip"){let cur=sRef.current?.tone.flip??"none",i=FLIPS.indexOf(cur);return setTone({flip:FLIPS[(i+d2+FLIPS.length)%FLIPS.length]})}return}if(row3.kind!=="knob"||!row3.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row3.id,row3.knob,d2)))},act=(row3,via)=>{if(!row3||!sRef.current)return;if(row3.kind==="select"){if(row3.id==="open")return doOpen();return doSelectRasterizer()}if(row3.kind==="prompt")return void doPrompt(row3.id);if(row3.kind==="action"){if(via==="space"&&row3.id==="reset")return;return void doAction(row3.id)}if(row3.kind==="tone"||row3.kind==="knob"){if(row3.knob.kind==="slider")return;return stepRow(row3,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row3=navRows[selRef.current];if(!row3)return;if(row3.id==="knobsfor")return void doAction("knobsfor");stepRow(row3,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;let pick2=await openSaveDiscard(dialog,{title:"Unsaved edits",body:`'${cur.name}' has unsaved changes. Save them, discard them, or keep editing?`});if(pick2==="save"){if(await doSave())open3(cur.name);return!0}if(pick2==="discard")open3(cur.name);return!0},refresh=import_react115.useCallback(()=>{let cur=sRef.current;if(!cur)return;if(stampRef.current=exports_eikon.sourceStamp(cur.name),cur.dirty){toast.show({variant:"info",message:"Reload skipped: unsaved edits",duration:3000});return}open3(cur.name),toast.show({variant:"info",message:"Reloaded",duration:1000})},[open3,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(key3.eventType==="release")return;if(key3.name==="u"&&key3.ctrl&&sRef.current)return void doSaveUse();if(key3.name==="u"&&sRef.current)return void doSubmit();if(keys.match("eikon.save",key3)){if(!saving)doSave();return}if(key3.name==="escape")return void discard();if(key3.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key3.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key3.name==="return")return void doNew();return}if(pane==="knobs"){if(handleListKey(keys,key3,{count:navRows.length,setSel:setSelBy,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doNew(),onRefresh:refresh}))return;if(key3.name==="left")return adjust(-1);if(key3.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key3))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key3,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key3.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key3.name==="left"||key3.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key3.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key3.name))}return}if(key3.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key3.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key3.name==="return")return doStripMenu()});let onScroll=(e)=>{if(e.stopPropagation(),!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;let sign=d2==="up"?-1:1;if(e.modifiers.ctrl)return mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,sign),dirty:!0}));if(e.modifiers.shift)return mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,sign,0),dirty:!0}));mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,0,sign),dirty:!0}))},previewErr=err??(!s||src3||baked2?null:url2?"no source \u2014 Enter on 'download source'":"no source \u2014 Enter on 'source'"),hint=!s?[["Enter","new eikon"],["Shift+\u2192","library"]]:pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"edit"],[keys.print("list.refresh"),"reload"],[keys.print("list.new"),"new"],["u","submit"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","pan"],["Ctrl+wheel","zoom"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),preview2=$jsx(PreviewPane,{s,frames,play,setPlay,focused:Boolean(props.focused),busy:busy2,live,baked:baked2,spatialOk,error:previewErr,pane,sel:spSel,onPane:setPane,onSel:setSpSel,onSet:setBar,onWheel:stepBar,onScroll}),help=helpOf(navRows[sel]),panel=$jsx(TabShell,{title:s?`Settings \u2014 ${s.name}`:"Settings",focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create or pick one."})}):$jsxs($Fragment,{children:[$jsx("scrollbox",{id:"studio-knob-scroll",ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,onMouseScroll:(e)=>e.stopPropagation(),children:rows3.map((row3,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row3.kind==="knob"&&!src3;return $jsx(KnobRow,{id:`knob-${row3.kind}-${row3.id}`,row:row3,s,r,status,on,dim:dim2,peek:peek5,busy:row3.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSelBy(ni)},onClick:()=>{if(ni>=0)setSelBy(ni),setPane("knobs"),act(row3,"click")},onWheel:(d2)=>stepRow(row3,d2),onSlide:row3.knob?.kind!=="slider"?void 0:row3.kind==="tone"?(v2)=>setTone({contrast:+v2.toFixed(2)}):(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row3.id,row3.knob,v2)))},`${row3.kind}:${r.name}:${row3.id}`)})}),$jsx("box",{flexShrink:0,height:HELP_H,marginTop:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:help})})]})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:18,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,stats,pending:pending3,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))},onEmpty:(st)=>doSource(st)})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+HELP_H+1+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:saving?"\u25CF saving\u2026":s?.dirty?"\u25CF unsaved":void 0})]})});var import_react117=__toESM(require_react_production(),1);import{existsSync as existsSync24,readFileSync as readFileSync15}from"fs";import{basename as basename12,dirname as dirname12,join as join18}from"path";var EIKON_CARD=50,titleWidth=(title,rows3)=>Math.max(title.length,...rows3.map((r)=>r.name.length+4))+7,cardWidth=(lines3)=>Math.max(EIKON_CARD,...lines3.map((line4)=>line4.length+2)),EikonTitleList=(props)=>{let theme=useTheme().theme;return $jsx("box",{width:props.width,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:props.title,focus:props.focus,grow:1,children:$jsx("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:$jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"row",height:1,paddingRight:3,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,children:[r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})})]},r.key)})})})})})},EikonCardGrid=(props)=>{let theme=useTheme().theme;if(props.rows.length===0)return $jsx("box",{padding:1,children:props.empty??$jsx("text",{fg:theme.textMuted,children:"No eikons found."})});return $jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"row",flexWrap:"wrap",width:"100%",flexShrink:0,children:props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"column",height:r.lines.length+2,width:cardWidth(r.lines),flexShrink:0,paddingX:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{height:r.lines.length,overflow:"hidden",flexDirection:"column",children:r.lines.map((line4,j2)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:line4||" "})},j2))}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:[on?"\u25B8 ":" ",r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.author??"unknown"," \xB7 ",r.status]})})]},r.key)})})})};var PREVIEW2=54,EikonGallery=import_react117.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),rev2=import_react117.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),dims=useTerminalDimensions(),rows3=import_react117.useMemo(()=>{let user=hermesPath("eikons"),own=exports_eikon.list(),map=new Map(own.map((x2)=>[x2.name.toLowerCase(),x2])),meta2=own.map((x2)=>({inst:x2,ids:ids2(x2.manifest,x2.name,x2.sourceUrl)}));return[...listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():dirname12(e.path)===user?basename12(e.path,".eikon"):basename12(dirname12(e.path)),man=manifest4(dirname12(e.path)),keys2=ids2(man,slug3),mine=meta2.find((x2)=>x2.ids.some((k2)=>keys2.includes(k2)))?.inst??map.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,url:mine?.sourceUrl,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3),lifecycle:mine?.lifecycle,...man?{manifest:man}:{}}}).filter((r)=>!(r.bundled&&r.lifecycle)).reduce((map2,row3)=>{let prev=map2.get(row3.slug);if(!prev||dirname12(prev.path)===user&&dirname12(row3.path)!==user)map2.set(row3.slug,row3);return map2},new Map).values()]},[rev2]),active=usePref("eikon"),path4=import_react117.useMemo(()=>active?exports_eikon.baked(active):void 0,[active,rev2]),current2=(row3)=>path4===row3.path,[sel,setSel]=import_react117.useState(0),[pane,setPane]=import_react117.useState("list"),[act,setAct]=import_react117.useState(0),galleryFollow=useFollow("gal",(i)=>rows3[i]?.slug??i),gridFollow=useFollow("lib-grid",(i)=>rows3[i]?.slug??i);import_react117.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],parsed=import_react117.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]),activate=(row3=cur)=>{if(!row3)return;if(row3.bundled)set("eikon",row3.slug);else exports_eikon.useInstalled(row3.slug);toast.show({variant:"success",message:`Avatar \u2192 ${row3.name}`})},doNew=import_react117.useCallback(async()=>{let res=await openNewEikon(dialog,{});if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),props.onEdit?.(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return props.onEdit?.(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,toast,props]),updateLocal=import_react117.useCallback(async()=>{if(!cur||cur.bundled)return;try{let out=await exports_eikon.update(cur.slug);if("type"in out){if(!await openConfirm(dialog,{title:`Update active '${cur.name}'?`,danger:!0,body:`${out.message} The active avatar's backing package will change even though the selected name stays '${cur.slug}'.`,yes:"update active",no:"cancel"}))return;let done=await exports_eikon.update(cur.slug,{confirmActive:!0});if("type"in done)return toast.show({variant:"warning",message:done.message})}toast.show({variant:"success",message:`Updated ${cur.name}`})}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}},[cur,dialog,toast]),submitLocal=import_react117.useCallback(async()=>{if(!cur||cur.bundled)return;let path6=submitPath(cur.slug);if(publishedInfo(path6)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path6,submit:props.submit??submit2})},[cur,dialog,props.submit,toast]),del=async()=>{if(!cur||cur.bundled)return;let here=current2(cur),base3=dirname12(cur.path)===hermesPath("eikons")?`Removes legacy flat file ${basename12(cur.path)}.`:`Removes ${dirname12(cur.path)} and all its sources.`,body=here?`${base3} This is the active avatar; deleting it will clear the active avatar selection.`:base3;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body}))return;let removed=exports_eikon.remove(cur.slug,{confirmActive:here});if(removed)return toast.show({variant:"warning",message:removed.message});toast.show({variant:"info",message:`Deleted ${cur.name}`})},actions=import_react117.useMemo(()=>{if(!cur)return[];return[{key:"Enter",label:current2(cur)?"Use as active avatar (active)":"Use as active avatar",run:()=>activate()},...props.onEdit?[{key:"e",label:"Edit in Studio",run:()=>props.onEdit?.(cur.slug)}]:[],...!cur.bundled?[{key:"u",label:"Update local package",run:()=>void updateLocal()},{key:"s",label:"Share to catalog",run:()=>void submitLocal()},{key:"d",label:"Delete local eikon",run:()=>void del(),danger:!0}]:[]]},[cur,path4,props.onEdit,updateLocal,submitLocal]);import_react117.useEffect(()=>{if(act>=actions.length)setAct(Math.max(0,actions.length-1))},[act,actions.length]);let cards=import_react117.useMemo(()=>rows3.map((r)=>{let p=(()=>{try{return parseEikonFile(r.path)}catch{return}})(),lines3=p?.resolve("state.idle")?.frames[0]??p?.states.get("idle")?.frames[0]??["(no preview)"];return{key:r.path,name:r.name,active:current2(r),author:r.author,status:current2(r)?"active":r.bundled?"bundled/system":"installed",lines:lines3}}),[rows3,path4]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;let plain=!key3.shift&&!key3.ctrl&&!key3.meta;if(key3.name==="tab")return setPane((p)=>p==="list"?"actions":"list");if(pane==="actions"){if(key3.name==="escape"||plain&&key3.name==="left"){setPane("list");return}if(plain&&key3.name==="up"){setAct((i)=>Math.max(0,i-1));return}if(plain&&key3.name==="down"){setAct((i)=>Math.min(actions.length-1,i+1));return}if(keys.match("list.activate",key3)||keys.match("list.toggle",key3)){actions[act]?.run();return}return}if(handleListKey(keys,key3,{count:rows3.length,setSel,page:galleryFollow.opts.page,scrollTo:(n)=>galleryFollow.ref.current?.scrollChildIntoView(galleryFollow.id(n)),onActivate:()=>activate(),onDelete:()=>void del(),onNew:doNew,onRefresh:()=>{exports_eikon.notifyRevision(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}))return;if(key3.name==="u"&&cur&&!cur.bundled)return void updateLocal();if(key3.name==="s"&&cur&&!cur.bundled)return void submitLocal();if(key3.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)});let listW=Math.max(13,...rows3.map((r)=>r.name.length+4))+7,showGrid=dims.width-listW-PREVIEW2>=EIKON_CARD;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minHeight:0,children:[$jsx(EikonTitleList,{title:`Library (${rows3.length})`,rows:rows3.map((r)=>({key:r.path,name:r.name,active:current2(r)})),sel,focus:props.focused&&pane==="list",follow:galleryFollow,width:listW,onSel:setSel,onUse:(i)=>activate(rows3[i])}),showGrid?$jsx(TabShell,{title:"Grid",grow:1,children:$jsx(EikonCardGrid,{rows:cards,sel,follow:gridFollow,onSel:setSel,onUse:(i)=>activate(rows3[i])})}):null,$jsx("box",{width:PREVIEW2,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:1,children:$jsxs("box",{flexDirection:"column",flexGrow:1,padding:1,alignItems:"center",children:[$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})}),cur?$jsxs("box",{flexDirection:"column",width:48,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:cur.name})}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",cur.author??"\u2014"]}),$jsxs("text",{fg:theme.textMuted,children:["Status: ",current2(cur)?"active":cur.bundled?"bundled/system":"installed"]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Source: ",gallerySource(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Trust: ",galleryTrust(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Package: ",packageId(cur)]}),$jsx("text",{fg:theme.textMuted,children:sourceBadge(cur)}),$jsx("box",{height:1}),$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Actions"})}),actions.map((a,i)=>$jsx("box",{height:1,overflow:"hidden",paddingRight:1,backgroundColor:pane==="actions"&&i===act?theme.backgroundElement:void 0,onMouseDown:()=>{setPane("actions"),setAct(i),a.run()},children:$jsxs("text",{fg:a.danger?theme.error:theme.text,wrapMode:"none",children:[pane==="actions"&&i===act?"\u25B8 ":" ",a.label," [",a.key,"]"]})},a.label))]}):null]})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="list"?"actions":"library"],[keys.print("list.activate"),pane==="actions"?"run action":"use"],["\u2191\u2193",pane==="actions"?"action":"select"],[keys.print("list.new"),"new / install"],[keys.print("list.refresh"),"reload"],...cur&&props.onEdit?[["e","edit in Studio"]]:[]]})]})}),galleryTrust=(row3)=>{let t2=row3.lifecycle?.trust;if(t2==="verified")return"Verified";if(t2==="mismatch")return"Mismatch";if(t2==="unverified")return"Unverified";return row3.bundled?"Bundled":"Legacy local"},gallerySource=(row3)=>{let src3=row3.lifecycle?.source;if(src3)return src3.identity??src3.repo??src3.origin??src3.kind;if(row3.bundled)return"bundled/system";return"local"},packageId=(row3)=>typeof row3.manifest?.id==="string"?row3.manifest.id:row3.bundled?"bundled/system":"\u2014",manifest4=(dir2)=>{let file2=join18(dir2,"manifest.json");if(!existsSync24(file2))return;try{let raw2=JSON.parse(readFileSync15(file2,"utf8"));return raw2&&typeof raw2==="object"&&!Array.isArray(raw2)?raw2:void 0}catch{return}},sourceBadge=(row3)=>row3.hasSource?"\u25CF source":row3.url||row3.bundled?"\u25CB source available":"\u2014 no source",key3=(value2)=>{try{let url2=new URL(value2);if(url2.protocol==="http:"||url2.protocol==="https:"||url2.protocol==="file:")return url2.href.replace(/\/?$/,"/").toLowerCase()}catch{}return value2.toLowerCase()},ids2=(man,name,url2)=>{let origin2=man?.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:void 0;return[...new Set([typeof man?.id==="string"?man.id:void 0,typeof origin2?.sourceKey==="string"?origin2.sourceKey:void 0,typeof origin2?.identityKey==="string"?origin2.identityKey:void 0,typeof origin2?.packageUrl==="string"?origin2.packageUrl:void 0,typeof origin2?.source==="string"?origin2.source:void 0,url2,name].filter((x2)=>!!x2).map(key3))]};var import_react120=__toESM(require_react_production(),1);var import_react119=__toESM(require_react_production(),1);var fmt3=(n)=>n==null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(1)} KiB`:`${(n/1024/1024).toFixed(1)} MiB`,choices=(row3,sizes)=>{if(row3.installState==="incompatible"||row3.installState==="mismatch")return[{label:"Delist from Registry",value:"delist"}];if(!row3.installed)return[{label:"Eikon only",hint:fmt3(sizes?.eikon),value:"install"},{label:"Eikon + Source",hint:`${fmt3((sizes?.eikon??0)+(sizes?.source??0))} \xB7 Source files needed to edit Eikon in Studio`,value:"source"},{label:"Delist from Registry",value:"delist"}];return[...!row3.active?[{label:"Use",hint:"set as active avatar",value:"use"}]:[],...row3.sourceDownloadable?[{label:"Download Source",hint:"needed to edit in Studio",value:"download"}]:[],...row3.removable?[{label:"Uninstall",value:"delete"}]:[],{label:"Delist from Registry",value:"delist"}]},Action=(props)=>{let theme=useTheme().theme,opts=choices(props.row,props.sizes),[sel,setSel]=import_react119.useState(0),desc=opts.some((o)=>!!o.hint);return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.row.entry.name})}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.row.entry.description??"No description."}),$jsx("box",{height:1}),opts.length>0?$jsx("select",{focused:!0,width:62,height:Math.min(12,Math.max(1,opts.length*(desc?2:1))),options:opts.map((o)=>({name:o.label,description:o.hint??"",value:o.value})),selectedIndex:Math.min(sel,opts.length-1),showDescription:desc,showScrollIndicator:opts.length>6,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"},{name:"return",action:"select-current"}],onChange:(i)=>setSel(i),onSelect:(i)=>{let opt=opts[i];if(opt)props.onPick(opt.value)}}):$jsx("text",{fg:theme.textMuted,children:props.row.reason??"No available actions."}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"[\u2191\u2193] move [Space/Enter] confirm [Esc] cancel"})]})};function openEikonMarketplaceAction(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Action,{...opts,onPick:done}),()=>resolve4(null))})}init_perf();import{existsSync as existsSync25,readFileSync as readFileSync16,readdirSync as readdirSync9,writeFileSync as writeFileSync8}from"fs";import{createHash as createHash7}from"crypto";import{basename as basename13,dirname as dirname13,extname as extname3,join as join19}from"path";import{Buffer as Buffer6}from"buffer";var REPO2=process.env.EIKON_REPO??"liftaris/eikon",HOST="eikon.liftaris.dev",enc2=new TextEncoder;async function gh2(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?enc2.encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code2]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code2!==0)throw Error(err.trim()||out.trim()||`gh ${args[0]} failed`);return out.trim()}function json(text3){return JSON.parse(text3)}function clean4(value2){return value2.replace(/[^A-Za-z0-9_.-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function pkg(entry3){let parts2=entry3.id.includes("/")?entry3.id.split("/"):["liftaris",entry3.name];return{ns:parts2[0]||"liftaris",name:parts2[1]||entry3.name}}function dirs(entry3){let p=pkg(entry3);return[`eikons/${entry3.name}/`,`packages/${p.ns}/${p.name}/`]}function touches(entry3,path4){return dirs(entry3).some((dir2)=>path4.startsWith(dir2))}function official(entry3){try{return new URL(entry3.packageUrl).hostname===HOST&&[entry3.sourceKey,entry3.identityKey].some((key4)=>key4?.startsWith(`registry:${HOST}:`))}catch{return!1}}async function user(run){return run(["api","user","-q",".login"])}async function prs(entry3,repo2,run){let exact=(xs)=>xs.filter((pr)=>pr.title===`eikons: submit ${entry3.name}`&&pr.headRefName===`submit/${entry3.name}`),at=(pr)=>Number.isFinite(Date.parse(pr.mergedAt??""))?Date.parse(pr.mergedAt??""):0,sort=(xs)=>xs.toSorted((a,b2)=>at(a)-at(b2)||a.number-b2.number),first=exact(json(await run(["pr","list","-R",repo2,"--state","merged","--search",`"eikons: submit ${entry3.name}" in:title`,"--json","number,title,headRefName,url,mergedAt,author","--limit","100"])));if(first.length)return sort(first);return sort(exact(json(await run(["pr","list","-R",repo2,"--state","merged","--json","number,title,headRefName,url,mergedAt,author","--limit","100"]))))}async function files(repo2,pr,run){return(await run(["api","--paginate","-X","GET",`repos/${repo2}/pulls/${pr}/files`,"--jq",".[].filename"])).split(/\r?\n/).filter(Boolean).map((path4)=>({path:path4}))}async function found(entry3,repo2,run){for(let pr of await prs(entry3,repo2,run)){let title=pr.title===`eikons: submit ${entry3.name}`,head=pr.headRefName===`submit/${entry3.name}`;if(!title||!head)continue;if((await files(repo2,pr.number,run)).some((f)=>touches(entry3,f.path??f.filename??"")))return pr}return}async function info2(entry3,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2;if(!official(entry3))return{eligible:!1,reason:"Registry delist is only available for official Eikon catalog entries"};let login;try{login=await user(run)}catch(err){return{eligible:!1,reason:err instanceof Error?err.message:String(err)}}let pr=await found(entry3,repo2,run),author=pr?.author?.login;if(!pr||!author)return{eligible:!1,user:login,reason:"No merged GitHub submission found"};if(author!==login)return{eligible:!1,user:login,author,pr:pr.number,url:pr.url,reason:`Submitted by @${author}`};return{eligible:!0,user:login,author,pr:pr.number,url:pr.url}}async function exists(run,repo2,branch2,path4){try{let raw2=await run(["api","-X","GET",`repos/${repo2}/contents/${path4}`,"-f",`ref=${branch2}`]);return json(raw2).sha}catch{return}}async function put2(run,repo2,branch2,path4,text3,msg){let sha2=await exists(run,repo2,branch2,path4);await run(["api","-X","PUT",`repos/${repo2}/contents/${path4}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,content:Buffer6.from(text3).toString("base64"),...sha2?{sha:sha2}:{}}))}async function del(run,repo2,branch2,path4,sha2,msg){await run(["api","-X","DELETE",`repos/${repo2}/contents/${path4}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,sha:sha2}))}async function main(run,repo2){let sha2=await run(["api",`repos/${repo2}/git/ref/heads/main`,"-q",".object.sha"]),tree2=await run(["api",`repos/${repo2}/git/commits/${sha2}`,"-q",".tree.sha"]);return{sha:sha2,tree:tree2}}async function tree2(run,repo2,sha2){return json(await run(["api","-X","GET",`repos/${repo2}/git/trees/${sha2}`,"-f","recursive=1"])).tree??[]}async function index3(run,repo2){let raw2=json(await run(["api","-X","GET",`repos/${repo2}/contents/eikons/index.json`,"-f","ref=main"]));return Buffer6.from((raw2.content??"").replace(/\s/g,""),"base64").toString("utf8")}async function reset3(run,repo2,name,sha2){try{await run(["api","-X","POST",`repos/${repo2}/git/refs`,"-f",`ref=refs/heads/${name}`,"-f",`sha=${sha2}`])}catch{await run(["api","-X","PATCH",`repos/${repo2}/git/refs/heads/${name}`,"--input","-"],JSON.stringify({sha:sha2,force:!0}))}}async function pr(run,repo2,user2,branch2,name,body){try{return await run(["pr","create","-R",repo2,"-H",`${user2}:${branch2}`,"-B","main","-t",`eikons: delist ${name}`,"-b",body])}catch{let raw2=await run(["api","-X","GET",`repos/${repo2}/pulls`,"-f","state=open","-f",`head=${user2}:${branch2}`]),hit2=json(raw2)[0]?.url;if(hit2)return hit2;throw Error("GitHub PR creation failed")}}async function submit3(entry3,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2,own=await info2(entry3,{repo:repo2,run});if(!own.eligible||!own.user)throw Error(own.reason??"not authorized to delist this eikon");await run(["repo","fork",repo2,"--clone=false"]).catch(()=>"");let fork2=`${own.user}/${repo2.split("/")[1]}`,branch2=`delist/${clean4(entry3.name)}`,base3=await main(run,repo2);await reset3(run,fork2,branch2,base3.sha);let msg=`eikons: delist ${entry3.name}`,next2=json(await index3(run,repo2)).filter((e)=>e.name!==entry3.name&&e.id!==entry3.id);await put2(run,fork2,branch2,"eikons/index.json",`${JSON.stringify(next2,null,2)}
|
|
4144
4144
|
`,msg);for(let item of await tree2(run,repo2,base3.tree)){if(!item.path||item.type!=="blob"||!item.sha||!touches(entry3,item.path))continue;let sha2=await exists(run,fork2,branch2,item.path)??item.sha;await del(run,fork2,branch2,item.path,sha2,msg)}return{url:await pr(run,repo2,own.user,branch2,entry3.name,`Requests delisting \`${entry3.name}\` from the Eikon registry.`),info:own}}var DEFAULT_TIMEOUT=5000,DEFAULT_CACHE_LIMIT=24,OFFICIAL_CATALOG="https://eikon.liftaris.dev/eikons",dec=new TextDecoder;function hash2(data2){return`sha256:${createHash7("sha256").update(data2).digest("hex")}`}function keyIdentity(s){try{let u3=new URL(s);if(u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")return u3.href.replace(/\/?$/,"/")}catch{}return s}function manifestBaseKey(s){try{let u3=new URL(s);if((u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")&&u3.pathname.endsWith("/manifest.json"))return new URL(".",u3).href}catch{}return}function registryKey(man,source2){if(man?.kind!=="eikon.package"||typeof man.id!=="string")return;let sourceKey=man.origin?.sourceKey??man.origin?.identityKey;if(sourceKey)return keyIdentity(sourceKey);try{let host=source2?new URL(source2).host:void 0;if(!host)return;return`registry:${host}:${man.id}${typeof man.version==="string"&&man.version?`@${man.version}`:""}`}catch{return}}function entryKeys(entry3){return[...new Set([entry3.identityKey,entry3.sourceKey].filter(Boolean).map(keyIdentity))]}function keysFor(inst){let keys=new Set,man=inst.manifest,origin2=typeof man?.origin?.source==="string"?man.origin.source:void 0,head=exports_eikon.header(inst.file),src3=typeof head?.source_url==="string"?head.source_url:inst.sourceUrl,registry2=registryKey(man,origin2);if(registry2)keys.add(registry2);if(origin2){keys.add(keyIdentity(origin2));let base3=manifestBaseKey(origin2);if(base3)keys.add(keyIdentity(base3))}if(src3){keys.add(keyIdentity(src3));let base3=manifestBaseKey(src3);if(base3)keys.add(keyIdentity(base3))}return[...keys]}function read(path4){try{let man=JSON.parse(readFileSync16(path4,"utf8"));return obj(man)?man:void 0}catch{return}}function chosen(active,name){return active===name||active==="default"&&name==="nous"}function media(dir2){return existsSync25(dir2)&&readdirSync9(dir2).length>0}function text3(value2){return typeof value2==="string"&&value2?value2:void 0}function life(name,man){let origin2=obj(man.origin)?man.origin:{},display3=obj(man.display)?man.display:{},src3=text3(origin2.source),identity2=text3(origin2.identityKey)??text3(origin2.sourceKey)??text3(origin2.packageUrl)??text3(origin2.repo)??src3,title=text3(display3.title)??text3(man.title),author=text3(display3.author)??text3(man.author);return{name,...title?{title}:{},...author?{author}:{},...text3(man.version)?{version:text3(man.version)}:{},source:{kind:text3(origin2.kind)??"default-catalog",...identity2?{identity:identity2}:{},...src3?{origin:src3}:{},...text3(origin2.repo)?{repo:text3(origin2.repo)}:{},...text3(origin2.selector)?{selector:text3(origin2.selector)}:{},...text3(origin2.catalogRoot)?{catalogRoot:text3(origin2.catalogRoot)}:{},...text3(origin2.sha)?{sha:text3(origin2.sha)}:{},...text3(origin2.packageUrl)?{packageUrl:text3(origin2.packageUrl)}:{}},trust:text3(origin2.trust)??"verified",active:chosen(get2("eikon"),name),removable:!1,updateable:Boolean(src3??text3(origin2.packageUrl)),updateAvailable:!1,dirty:!1,...text3(man.poster)?{poster:text3(man.poster)}:{},...obj(man.compatibility)?{compatibility:man.compatibility}:{},...text3(origin2.at)?{installedAt:text3(origin2.at)}:{}}}function bundled(xs){let names=new Set(xs.map((x2)=>x2.name.toLowerCase()));return listEikons([BUNDLED_EIKON_DIR]).flatMap((e)=>{let man=read(join19(dirname13(e.path),"manifest.json"));if(man?.kind!=="eikon.package")return[];let name=text3(man.name)??e.meta.name.toLowerCase();if(names.has(name.toLowerCase()))return[];let inst={name,file:e.path,source:exports_eikon.sourceDir(name),hasSource:media(exports_eikon.sourceDir(name)),sourceUrl:text3(man.origin?.source)??text3(man.origin?.packageUrl),manifest:man,lifecycle:life(name,man)};return[{...inst,manifest:man,identityKeys:keysFor(inst)}]})}function cacheKey(entry3){return[entry3.identityKey||entry3.sourceKey||entry3.id,entry3.runtimeUrl,entry3.trust?.runtimeDigest,entry3.trust?.runtimeSize].filter(Boolean).join("|")}function blob(url2){return/\/blobs\/sha256\/[^/?#]+/.test(url2)}function artifact(entry3){return entry3}function obj(value2){return!!value2&&typeof value2==="object"&&!Array.isArray(value2)}function rawManifest(entry3){let raw2=entry3.raw;return obj(raw2.manifest)?raw2.manifest:void 0}function role(file2){if(file2.role==="source.base")return"base";if(file2.role?.startsWith("source."))return file2.role.slice(7);if(!file2.path)return;return basename13(file2.path,extname3(file2.path)).toLowerCase()||"base"}function sourceEntries2(man,strict=!1){if(!man)return[];try{let xs=entries(man).map(([r,rel2])=>[r,rel2]);if(xs.length)return xs;return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}catch(err){if(strict)throw err}return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}function sourceDescriptors3(man){return sourceEntries2(man).length>0}function sourceAvailable2(entry3,inst){return sourceDescriptors3(inst?.manifest)||sourceDescriptors3(rawManifest(entry3))}function trust(entry3){return entry3.trust}function boundTrust(entry3,raw2){let t2=trust(entry3),man=t2.manifestDigest,run=t2.runtimeDigest;if(!man&&!run)return"unverified";if(man&&hash2(raw2)!==man)throw Error(`catalog trust mismatch: manifest digest for ${entry3.name}`);let pkg2=JSON.parse(dec.decode(raw2)),rel2=pkg2.entrypoints?.default,got=rel2?pkg2.files?.find((f)=>f.path===rel2)?.digest:void 0;if(run&&got!==run)throw Error(`catalog trust mismatch: runtime digest for ${entry3.name}`);return man&&run?"verified":"unverified"}function spec2(man,rel2){return man.files?.find((f)=>f.path===rel2)}async function sourceBytes(man,base3,rel2,opts){let file2=spec2(man,rel2);if(!file2?.digest||typeof file2.size!=="number")throw Error(`source descriptor missing digest or size: ${rel2}`);let raw2=await downloadBytes(new URL(rel2,base3).href,opts);if(raw2.length!==file2.size)throw Error(`source size mismatch: ${rel2}`);if(hash2(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}function target(input){return typeof input==="string"?input:input instanceof URL?input.href:input.url}function verifiedCatalogTrust(entry3){let t2=trust(entry3);return typeof t2.manifestDigest==="string"&&t2.manifestDigest.length>0&&typeof t2.runtimeDigest==="string"&&t2.runtimeDigest.length>0}function installed(){let xs=exports_eikon.list().map((inst)=>({...inst,manifest:inst.manifest,identityKeys:keysFor(inst)}));return[...xs,...bundled(xs)]}function match2(entry3,xs){let keys=entryKeys(entry3),exact=xs.find((x2)=>x2.identityKeys.some((k2)=>keys.includes(k2)));if(exact)return{inst:exact,legacy:!1};let named=xs.find((x2)=>x2.name===entry3.name&&x2.identityKeys.length===0);if(named)return{inst:named,legacy:!0};return}function row3(entry3,xs){let usable=match2(entry3,xs),active=usable?chosen(get2("eikon"),usable.inst.name):!1,installed2=Boolean(usable),conflict=!usable&&chosen(get2("eikon"),entry3.name),blocked=entry3.compatibility?.available===!1,mismatch=usable?.inst.lifecycle.trust==="mismatch",installState=mismatch?"mismatch":blocked?"incompatible":active?"active":conflict?"active-name-conflict":!usable?"available":usable.legacy?"legacy-name-match":"installed",lifecycle2=usable?.inst.lifecycle??{name:entry3.name,title:entry3.title,author:entry3.author,version:entry3.version,source:{kind:"default-catalog",identity:entry3.sourceKey,packageUrl:entry3.packageUrl},trust:verifiedCatalogTrust(entry3)?"verified":"unverified",active:!1,removable:!1,updateable:!1,updateAvailable:!1,dirty:!1,...entry3.poster?{poster:entry3.poster}:{},compatibility:entry3.compatibility},available2=sourceAvailable2(entry3,usable?.inst);return{entry:entry3,installed:installed2,active,installState,...usable?.inst.file?{installedPath:usable.inst.file,installedName:usable.inst.name}:{},...usable?.inst.manifest?{installedManifest:usable.inst.manifest}:{},lifecycle:lifecycle2,trust:lifecycle2.trust,updateable:lifecycle2.updateable,updateAvailable:lifecycle2.updateAvailable,removable:lifecycle2.removable,sourceIdentity:lifecycle2.source.identity,sourcePresent:usable?.inst.hasSource??!1,sourceAvailable:available2,sourceDownloadable:Boolean(usable&&!usable.inst.hasSource&&available2),reason:blocked?entry3.compatibility?.reason??"incompatible":mismatch?"trust mismatch":conflict?"install would replace the active avatar backing package":void 0,action:active?"active":installed2?"use":"install"}}function sizes(man){let files2=Array.isArray(man.files)?man.files:[],eikon=files2.filter((f)=>f.role==="runtime"||f.path===man.entrypoints?.default).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0),source2=files2.filter((f)=>typeof f.role==="string"&&f.role.startsWith("source")).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0);return{...eikon>0?{eikon}:{},...source2>0?{source:source2}:{}}}function abortErr(){return new DOMException("aborted","AbortError")}class MarketplaceService{catalog;fetcher;timeoutMs;previewCacheLimit;concurrency;allowPrivate;official;delistRepo;delistRun;activeLoads=0;queue=[];cache=new Map;inFlight=new Map;constructor(catalog3,opts={}){this.catalog=catalog3,this.fetcher=opts.fetcher??fetch,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT,this.previewCacheLimit=opts.previewCacheLimit??DEFAULT_CACHE_LIMIT,this.concurrency=Math.max(1,Math.floor(opts.concurrency??4)),this.allowPrivate=opts.allowPrivate===!0,this.official=keyIdentity(publicCatalogUrl(opts.catalog??OFFICIAL_CATALOG,void 0,opts))===keyIdentity(OFFICIAL_CATALOG),this.delistRepo=opts.delistRepo,this.delistRun=opts.delistRun}rows(query2=""){let entries2=searchCatalog(this.catalog.entries,query2),xs=installed();return entries2.map((e)=>row3(e,xs))}entry(id){let key4=keyIdentity(id);return this.catalog.entries.find((e)=>keyIdentity(e.identityKey)===key4||keyIdentity(e.sourceKey)===key4||e.id===id||e.name===id)}dl(signal,fetcher=this.fetcher){return{allowPrivate:this.allowPrivate,fetcher:(input,init)=>fetcher(input,signal?{...init,signal}:init)}}runtime(entry3,signal){return async(input)=>{let url2=target(input),bound=keyIdentity(url2)===keyIdentity(entry3.runtimeUrl)&&(!!entry3.trust?.runtimeDigest||blob(url2)),raw2=await downloadBytes(url2,{...this.dl(signal),rejectContentEncoding:bound}),buf=raw2.buffer.slice(raw2.byteOffset,raw2.byteOffset+raw2.byteLength);return new Response(buf,{headers:{"content-length":String(raw2.length)}})}}cached(url2,raw2){let key4=keyIdentity(url2);return async(input,init)=>{if(keyIdentity(target(input))===key4)return new Response(raw2.slice(),{headers:{"content-length":String(raw2.length)}});return this.fetcher(input,init)}}async preview(id,opts={}){if(opts.signal?.aborted)throw abortErr();let entry3=this.entry(id);if(!entry3)throw Error(`marketplace: unknown eikon "${id}"`);let key4=cacheKey(entry3),hit2=this.cache.get(key4);if(hit2!==void 0)return hit2;let active=this.inFlight.get(key4);if(active)return active;let p=this.enqueue(()=>this.loadPreview(entry3,opts)).finally(()=>this.inFlight.delete(key4));return this.inFlight.set(key4,p),p}async packageSizes(id){let entry3=this.entry(id);if(!entry3)throw Error(`marketplace: unknown eikon "${id}"`);return sizes(JSON.parse(dec.decode(await downloadBytes(entry3.packageUrl,this.dl()))))}async delistInfo(id){let entry3=this.entry(id);if(!entry3)throw Error(`marketplace: unknown eikon "${id}"`);if(!this.official)return{eligible:!1,reason:"Registry delist is only available from the official Eikon catalog"};return info2(entry3,{repo:this.delistRepo,run:this.delistRun})}async delist(id){let entry3=this.entry(id);if(!entry3)throw Error(`marketplace: unknown eikon "${id}"`);if(!this.official)throw Error("Registry delist is only available from the official Eikon catalog");return submit3(entry3,{repo:this.delistRepo,run:this.delistRun})}async install(id,opts={}){let entry3=this.entry(id);if(!entry3)throw Error(`marketplace: unknown eikon "${id}"`);if(entry3.compatibility?.available===!1)throw Error(entry3.compatibility.reason??"eikon is incompatible");if(!match2(entry3,installed())&&chosen(get2("eikon"),entry3.name)&&!opts.confirmActive)throw Error(`Installing '${entry3.name}' will replace the active avatar's backing package. Pass confirmActive to install it.`);let raw2=await downloadBytes(entry3.packageUrl,this.dl()),state3=boundTrust(entry3,raw2),out=await exports_eikon.fetchSource(entry3.packageUrl,{name:entry3.name,media:opts.media===!0,downloader:this.dl(void 0,this.cached(entry3.packageUrl,raw2))}),ef=exports_eikon.file(out.name);if(!existsSync25(ef)){let art=await loadRuntimeArtifact(entry3,this.runtime(entry3),{allowPrivate:this.allowPrivate});await Bun.write(ef,art.bytes),exports_eikon.notifyRevision()}let mf=join19(exports_eikon.dir(out.name),"manifest.json"),man=JSON.parse(readFileSync16(mf,"utf8")),origin2=man.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:{};return writeFileSync8(mf,JSON.stringify({...man,origin:{...origin2,sourceKey:entry3.sourceKey,identityKey:entry3.identityKey,packageUrl:entry3.packageUrl,trust:state3}},null,2)+`
|
|
4145
4145
|
`),out}async downloadSource(id){let entry3=this.entry(id);if(!entry3)throw Error(`marketplace: unknown eikon "${id}"`);let usable=match2(entry3,installed());if(!usable)throw Error(`marketplace: "${entry3.name}" is not installed`);if(!sourceAvailable2(entry3,usable.inst))throw Error(`marketplace: no source media published for "${entry3.name}"`);let raw2=await downloadBytes(entry3.packageUrl,this.dl());boundTrust(entry3,raw2);let man=JSON.parse(dec.decode(raw2)),xs=sourceEntries2(man,!0);if(xs.length===0)throw Error(`marketplace: no source media published for "${entry3.name}"`);let base3=new URL(".",entry3.packageUrl).href,dir2=exports_eikon.ensure(usable.inst.name).source,pairs=await Promise.all(xs.map(async([r,rel2])=>{let data2=await sourceBytes(man,base3,rel2,this.dl());return[r,exports_eikon.sourceName(man,r,rel2),data2]})),sources={};return await Promise.all(pairs.map(async([r,fname,data2])=>{await Bun.write(join19(dir2,fname),data2),sources[r]=fname})),exports_eikon.attachSources(usable.inst.name,sources),{name:usable.inst.name,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}enqueue(run){return new Promise((resolve4,reject)=>{this.queue.push({run,resolve:resolve4,reject}),this.pump()})}pump(){if(this.activeLoads>=this.concurrency)return;let job=this.queue.shift();if(!job)return;this.activeLoads+=1,job.run().then(job.resolve,job.reject).finally(()=>{this.activeLoads-=1,this.pump()})}async loadPreview(entry3,opts){let ctl=new AbortController,timeout2=setTimeout(()=>ctl.abort(),opts.timeoutMs??this.timeoutMs),off=()=>ctl.abort();opts.signal?.addEventListener("abort",off,{once:!0});try{let item=artifact(entry3),text4=(await loadRuntimeArtifact(item,this.runtime(item,ctl.signal),{signal:ctl.signal,allowPrivate:this.allowPrivate})).text;this.cache.set(cacheKey(entry3),text4);while(this.cache.size>this.previewCacheLimit)this.cache.delete(this.cache.keys().next().value);return text4}finally{clearTimeout(timeout2),opts.signal?.removeEventListener("abort",off)}}}async function load4(opts={}){let query2=opts.query??"";try{if(opts.catalog)publicCatalogUrl(opts.catalog,void 0,opts);let cat=await loadCatalog(opts.catalog,opts.fetcher??fetch,opts),service=new MarketplaceService(cat,opts),rows3=service.rows(query2);return{status:rows3.length>0?"ready":"empty",query:query2,rows:rows3,selected:rows3[0],service}}catch(err){return{status:"error",query:query2,rows:[],error:err instanceof Error?err.message:String(err)}}}var NO_MARKET={status:"empty",query:"",rows:[]},DETAIL=54;function localCatalog(raw2){if(!raw2)return!1;try{let url2=new URL(raw2),host=url2.hostname.toLowerCase().replace(/^\[|\]$/g,"");return url2.protocol==="file:"||host==="localhost"||host==="127.0.0.1"||host==="0.0.0.0"||host==="::1"||host.endsWith(".localhost")}catch{return!1}}var filterRows=(rows3,query2)=>{let q5=query2.trim().toLowerCase();if(!q5)return rows3;return rows3.filter((r)=>[r.entry.name,r.entry.author,r.entry.description,r.entry.id].some((x2)=>typeof x2==="string"&&x2.toLowerCase().includes(q5)))},EikonMarketplace=import_react120.memo((props)=>{let toast=useToast(),dialog=useDialog(),keys=useKeys(),theme=useTheme().theme,rev2=import_react120.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),[sel,setSel]=import_react120.useState(0),[searching,setSearching]=import_react120.useState(!1),[query2,setQuery]=import_react120.useState(""),[state3,setState2]=import_react120.useState(NO_MARKET),[loading,setLoading]=import_react120.useState(!1),[installing,setInstalling]=import_react120.useState(!1),[acting,setActing]=import_react120.useState(!1),[previewState,setPreviewState]=import_react120.useState("idle"),[preview2,setPreview]=import_react120.useState(void 0),[pane,setPane]=import_react120.useState("grid"),previewSeq=import_react120.useRef(0),loadSeq=import_react120.useRef(0),actingRef=import_react120.useRef(!1),follow=useFollow("market",(i)=>state3.rows[i]?.entry.identityKey??i),listFollow=useFollow("market-list",(i)=>state3.rows[i]?.entry.identityKey??i),dims=useTerminalDimensions();import_react120.useEffect(()=>{if(sel>=state3.rows.length)setSel(Math.max(0,state3.rows.length-1))},[state3.rows.length,sel]);let selected=state3.rows[sel];import_react120.useEffect(()=>{if(!selected||!state3.service){setPreview(void 0);return}let id=++previewSeq.current,key4=selected.entry.identityKey;count("market:preview:load"),state3.service.preview(key4).then((text4)=>{if(previewSeq.current!==id)return;let e=parseEikon(text4),st=e.states.has(previewState)?previewState:"idle";setPreview({eikon:e,state:st,states:[...e.states.keys()]}),count("market:preview:ready")}).catch(()=>{if(previewSeq.current!==id)return;setPreview(void 0),count("market:preview:error")})},[selected,state3.service,previewState]),import_react120.useEffect(()=>()=>{previewSeq.current++,setPreview(void 0)},[]);let loadMarket=import_react120.useCallback((q5=query2)=>{let id=++loadSeq.current;setLoading(!0);let end=mark("market:list:load"),catalog3=process.env.EIKON_URL;load4({catalog:catalog3,allowPrivate:localCatalog(catalog3),query:q5}).then((next2)=>{if(loadSeq.current!==id)return;count("market:list:rows",next2.rows.length);let rows3=next2.service?filterRows(next2.service.rows(""),q5):filterRows(next2.rows,q5);setState2({...next2,status:rows3.length>0?"ready":"empty",rows:rows3,selected:rows3[0]}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))}).finally(()=>{if(end(),loadSeq.current===id)setLoading(!1)})},[query2]),refreshMarket=import_react120.useCallback((svc,q5=query2)=>{let rows3=filterRows(svc.rows(""),q5);setState2({status:rows3.length>0?"ready":"empty",query:q5,rows:rows3,selected:rows3[0],service:svc}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))},[query2]);import_react120.useEffect(()=>{loadMarket(query2)},[query2,rev2,loadMarket]);let cycle3=import_react120.useCallback((by)=>{let states=preview2?.states,cur=preview2?.state;if(!states?.length||!cur)return;let at=Math.max(0,states.indexOf(cur));setPreviewState(states[(at+by+states.length)%states.length])},[preview2]),removeSelected=import_react120.useCallback(async(idx)=>{let row4=state3.rows[idx??sel],svc=state3.service,name=row4?.installedName??row4?.entry.name;if(!row4||!svc||!name||!row4.removable)return toast.show({variant:"warning",message:"This eikon is not removable"});let active=row4.active;if(!await openConfirm(dialog,{title:`Remove '${name}'?`,danger:!0,body:active?`Remove the local package for '${name}'. This is the active avatar; removal will clear the active avatar selection.`:`Remove the local package for '${name}'. This does not change the active avatar.`,yes:"remove",no:"cancel"}))return;let out=exports_eikon.remove(name,{confirmActive:active});if(out)return toast.show({variant:"warning",message:out.message});toast.show({variant:"info",message:`Removed '${name}'`}),refreshMarket(svc,query2)},[dialog,query2,refreshMarket,sel,state3.rows,state3.service,toast]),delistSelected=import_react120.useCallback(async(row4,svc)=>{let own;try{own=await svc.delistInfo(row4.entry.identityKey)}catch(err){toast.show({variant:"error",title:"Delist check failed",message:err instanceof Error?err.message:String(err),duration:6000});return}if(!own.eligible){toast.show({variant:"warning",title:"Delist unavailable",message:own.reason??"Only the original GitHub submitter can delist this eikon",duration:6000});return}if(!await openConfirm(dialog,{title:`Delist '${row4.entry.name}'?`,danger:!0,body:`This will open a GitHub delist request in liftaris/eikon for '${row4.entry.name}'. The registry will remove it automatically after authorship is verified.`,yes:"delist",no:"cancel"}))return;try{let out=await svc.delist(row4.entry.identityKey);toast.show({variant:"success",title:"Delist requested",message:`${row4.entry.name} will be removed automatically once GitHub verifies the request. ${out.url}`,duration:8000})}catch(err){toast.show({variant:"error",title:"Delist failed",message:err instanceof Error?err.message:String(err),duration:6000})}},[dialog,toast]),primary=import_react120.useCallback((idx)=>{let row4=state3.rows[idx??sel],svc=state3.service;if(!row4||!svc||actingRef.current||acting)return;(async()=>{actingRef.current=!0,setActing(!0);try{let sizes2=!row4.installed?await svc.packageSizes(row4.entry.identityKey).catch(()=>{return}):void 0,pick2=await openEikonMarketplaceAction(dialog,{row:row4,sizes:sizes2});if(!pick2)return;if(pick2==="use"){let name=row4.installedName??row4.entry.name;exports_eikon.useInstalled(name),toast.show({variant:"success",message:`Avatar \u2192 ${name}`}),refreshMarket(svc,query2);return}if(pick2==="delete")return removeSelected(idx);if(pick2==="delist")return delistSelected(row4,svc);setInstalling(!0);try{if(!(row4.installState==="active-name-conflict"?await openConfirm(dialog,{title:`Replace active '${row4.entry.name}'?`,danger:!0,body:`Installing this catalog package will replace the active avatar's backing package for '${row4.entry.name}' because another package with the same installed name is active.`,yes:"replace active",no:"cancel"}):!0))return;let out=pick2==="download"?await svc.downloadSource(row4.entry.identityKey):await svc.install(row4.entry.identityKey,{media:pick2==="source",confirmActive:row4.installState==="active-name-conflict"});toast.show({variant:"success",message:pick2==="download"?`Downloaded source for '${out.name}'`:`Installed '${out.name}' (${out.n} files)`}),refreshMarket(svc,query2)}catch(err){toast.show({variant:"error",title:pick2==="download"?"Source download failed":"Install failed",message:err instanceof Error?err.message:String(err),duration:6000}),refreshMarket(svc,query2)}finally{setInstalling(!1)}}finally{actingRef.current=!1,setActing(!1)}})()},[dialog,state3.rows,state3.service,sel,acting,toast,refreshMarket,query2,removeSelected,delistSelected]);useKeyboard((key4)=>{if(!props.focused||dialog.open())return;if(searching){if(key4.name==="escape"||key4.name==="esc"){setSearching(!1);return}if(key4.name==="backspace"){setQuery((q5)=>q5.slice(0,-1)),setSel(0);return}let seq=typeof key4.sequence==="string"?key4.sequence:"",ch=key4.raw&&key4.raw.length===1?key4.raw:seq.length===1?seq:key4.name.length===1&&!key4.ctrl&&!key4.meta?key4.name:"";if(ch>=" "){setQuery((q5)=>q5+ch),setSel(0);return}return}let plain=!key4.shift&&!key4.ctrl&&!key4.meta;if(key4.name==="tab")return setPane((p)=>p==="grid"?"detail":"grid");if(pane==="detail"){if(key4.name==="escape"||plain&&key4.name==="left"){setPane("grid");return}if(plain&&key4.name==="right"){cycle3(1);return}if(keys.match("list.activate",key4)){primary();return}if(keys.match("list.toggle",key4)){cycle3(1);return}if(keys.match("list.search",key4)){setPane("grid"),setSearching(!0);return}if(keys.match("list.refresh",key4)){loadMarket(query2);return}return}let move=(by)=>setSel((p)=>{let n=Math.max(0,Math.min(state3.rows.length-1,p+by));return follow.opts.scrollTo?.(n),listFollow.opts.scrollTo?.(n),n});if(plain&&key4.name==="left"){move(-1);return}if(plain&&key4.name==="right"){move(1);return}if(plain&&key4.name==="up"){move(-1);return}if(plain&&key4.name==="down"){move(1);return}if(handleListKey(keys,key4,{count:state3.rows.length,setSel,page:listFollow.opts.page,scrollTo:(n)=>{follow.opts.scrollTo?.(n),listFollow.opts.scrollTo?.(n)},onActivate:primary,onToggle:()=>cycle3(1),onSearch:()=>setSearching(!0),onRefresh:()=>loadMarket(query2),onDelete:()=>void removeSelected()}))return}),count("market:render");let titles=state3.rows.map((r)=>({key:r.entry.identityKey,name:r.entry.name,active:r.active})),cards=state3.rows.map((r)=>({key:r.entry.identityKey,name:r.entry.name,active:r.active,author:r.entry.author,status:stateLabel(r,!0),lines:posterLines(r.entry.poster)})),listW=titleWidth(`Catalog (${state3.rows.length})`,titles),showGrid=dims.width-listW-DETAIL>=EIKON_CARD;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(EikonTitleList,{title:`Catalog (${state3.rows.length})${searching?` Search: ${query2}`:""}`,rows:titles,sel,focus:props.focused&&pane==="grid",follow:listFollow,width:listW,onSel:setSel,onUse:primary}),showGrid?$jsx(TabShell,{title:"Posters",grow:1,children:state3.error?$jsx("box",{padding:1,children:$jsxs("text",{fg:theme.error,wrapMode:"word",children:["Catalog unavailable: ",state3.error]})}):loading&&state3.rows.length===0?$jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:"Loading shared eikons\u2026"})}):$jsx(EikonCardGrid,{rows:cards,sel,follow,empty:$jsx("text",{fg:theme.textMuted,children:"No catalog eikons match. Press / to change search."}),onSel:setSel,onUse:primary})}):null,$jsx("box",{width:DETAIL,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:selected?`Details \u2014 ${selected.entry.name}`:"Details",focus:props.focused&&pane==="detail",grow:1,children:$jsx(MarketplaceDetail,{row:selected,loading,installing,onUse:()=>primary(),onFocus:()=>setPane("detail"),onState:setPreviewState,preview:preview2})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="grid"?"details":"catalog"],[keys.print("list.activate"),"actions"],[pane==="detail"?"\u2192/Space":"\u2191\u2193\u2190\u2192/Pg",pane==="detail"?"state":"select"],[keys.print("list.search"),searching?"typing search":"search"],[keys.print("list.refresh"),"reload"],["d","delete in modal"],["Space","preview"]]})]})}),posterLines=(poster2)=>{let lines3=poster2?poster2.split(`
|
|
4146
4146
|
`):[];return lines3.length?lines3:["(no poster)"]},MarketplaceDetail=(props)=>{let theme=useTheme().theme,r=props.row;if(!r)return $jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:props.loading?"Loading shared eikons\u2026":"No catalog entry selected."})});let previewState=props.preview?.state??"idle",states=props.preview?.states??[previewState];return $jsxs("box",{flexDirection:"column",padding:1,onMouseDown:props.onFocus,children:[props.preview?$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:$jsx(AnimatedAvatar,{state:props.preview.state,eikon:props.preview.eikon},`${r.entry.identityKey}:${props.preview.state}`)}):null,$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:$jsxs("strong",{children:[r.active?"\u25CF ":"",r.entry.name]})})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.entry.author??"unknown"]})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:r.entry.description??"No description."})}),$jsx("box",{flexDirection:"row",flexWrap:"wrap",flexShrink:0,children:states.map((s,i)=>$jsx(FilterChip,{label:s,state:s===previewState?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.textMuted,onMouseDown:()=>props.onState(s)},s))}),$jsx(DetailRow2,{label:"Status",value:stateLabel(r),block:!0}),$jsx(DetailRow2,{label:"Trust",value:trustLabel(r),block:!0}),$jsx(DetailRow2,{label:"Source",value:sourceText(r),block:!0}),$jsx(DetailRow2,{label:"Compat",value:compatText(r)}),$jsx(DetailRow2,{label:"Digest",value:digest2(r)??"unknown",block:!0})]})},DetailRow2=(props)=>{let theme=useTheme().theme;if(props.block)return $jsx("box",{flexDirection:"column",minHeight:props.label==="Status"?2:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:[props.label,": ",props.value]})});return $jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[props.label,": ",props.value]})})},shortDigest=(value2)=>{if(!value2)return;let[algo,hash3]=value2.includes(":")?value2.split(":",2):[void 0,value2];if(!hash3||hash3.length<=16)return value2;return algo?`${algo}:${hash3.slice(0,12)}\u2026`:`${hash3.slice(0,12)}\u2026`},digest2=(row4)=>{let t2=row4.entry.trust;return shortDigest(t2.manifestDigest??t2.runtimeDigest??t2.digest)},trustLabel=(row4)=>{let t2=row4.trust==="mismatch"?"Mismatch":row4.trust==="verified"?"Verified":row4.trust==="unverified"?"Unverified":"Trust unknown";return row4.reason&&row4.trust==="mismatch"?`${t2}: ${row4.reason}`:t2},sourceText=(row4)=>row4.sourceIdentity??row4.lifecycle.source.packageUrl??row4.entry.sourceKey??row4.entry.packageUrl,compatText=(row4)=>row4.installState==="incompatible"?`Blocked: ${row4.reason??"requires newer Herm/eikon"}`:row4.installState==="active-name-conflict"?`Requires confirmation: ${row4.reason}`:"Compatible",stateLabel=(row4,short2=!1)=>{let base3=row4.installState==="active-name-conflict"?"active name conflict":row4.active?"active":row4.installed?"installed":"not installed";if(short2)return base3;let src3=row4.sourcePresent?" \xB7 source present":row4.sourceDownloadable?" \xB7 source downloadable":row4.sourceAvailable?" \xB7 source available":"",rm2=row4.removable?" \xB7 removable":row4.installed?" \xB7 not removable":"";return`${base3}${src3}${rm2}`};var EikonGroup=import_react122.memo((props)=>{let labels=SUB_TABS[EIKON_TAB],[target2,setTarget]=import_react122.useState(void 0);import_react122.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let edit2=import_react122.useCallback((name)=>{setTarget(name),props.setSub(2)},[props]),hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:[$jsx(Pane4,{visible:props.sub===0,children:$jsx(EikonGallery,{focused:!!props.focused&&props.sub===0,onEdit:edit2})}),$jsx(Pane4,{visible:props.sub===1,children:$jsx(EikonMarketplace,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane4,{visible:props.sub===2,children:$jsx(EikonStudio,{focused:!!props.focused&&props.sub===2,name:target2})})]})]})}),Pane4=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react123=__toESM(require_react_production(),1);var FRAME={cw:16,ch:8,tw:20,tv:8},TL=["\u2800\u2880\u28E4\u2824\u2884\u28C0\u2804\u2880\u28E0\u28E4\u28C4\u2864\u2844\u2840\u2800\u2800","\u2800\u28DC\u2841\u28A9\u28C8\u2842\u2880\u28CB\u28ED\u2809\u2808\u2888\u28EE\u28FB\u2851\u28F6","\u2800\u28B8\u2856\u28BF\u280F\u28E4\u28F6\u28FD\u28EB\u28B6\u28E2\u284C\u2839\u28E7\u284F\u283B","\u2800\u2808\u2864\u2892\u28E6\u28BB\u28FF\u28FF\u28FF\u28BF\u28C5\u2847\u28C6\u2849\u2802\u2880","\u2801\u28B8\u284F\u2818\u280B\u289E\u28B3\u28FF\u28FF\u28DF\u284D\u284D\u28E4\u2805\u2800\u28A8","\u2800\u2824\u28AF\u28C6\u28C0\u2819\u28A6\u28FF\u284B\u2880\u28DC\u2807\u28C1\u28D2\u28CA\u28C9","\u2800\u2880\u28F7\u28DD\u28FB\u28F6\u28F6\u2884\u280D\u2818\u2841\u2847\u28E7\u28E0\u28E4\u2862","\u2800\u2800\u2818\u288E\u28BF\u28EF\u2803\u2801\u2864\u28DA\u287C\u2800\u284F\u28F9\u28FF\u2869"],TR=["\u2800\u2800\u2880\u28A0\u28A0\u28E0\u28E4\u28C0\u2840\u2820\u28C0\u2860\u2824\u28E4\u28C0\u2800","\u28F6\u288A\u28DF\u28F5\u2841\u2801\u2809\u28ED\u28D9\u2800\u2890\u28C2\u284D\u2888\u28E3\u2800","\u281F\u28B9\u28FC\u280F\u28A1\u28D4\u28B6\u28DD\u28EF\u28F6\u28E4\u2839\u287F\u28B2\u2847\u2800","\u2840\u2801\u2889\u28F0\u28B8\u28E8\u287F\u28FF\u28FF\u28FF\u285F\u28F4\u2852\u28A4\u2801\u2800","\u2845\u2804\u2828\u28E4\u28A9\u28A9\u28FB\u28FF\u28FF\u285E\u2873\u2819\u2803\u28B9\u2847\u2800","\u28C9\u28D1\u28D2\u28C8\u2838\u28E3\u2840\u2899\u28FF\u2874\u280B\u28C0\u28F0\u287D\u2824\u2880","\u2884\u28E4\u28C4\u28F8\u28B8\u2888\u2803\u2829\u2860\u28F6\u28F6\u28DF\u28EB\u28FE\u2802\u2800","\u288D\u28FF\u289F\u28B9\u2800\u28A7\u28D2\u28A4\u2801\u2808\u28FD\u287F\u2871\u2807\u2800\u2800"],BL=["\u2800\u2800\u28C0\u28FF\u28FF\u285F\u2801\u2800\u283B\u28AC\u28F3\u2800\u28C7\u28F2\u28DF\u28BF","\u2800\u2890\u287A\u28DB\u286F\u28ED\u2837\u280C\u2882\u2880\u2842\u2847\u284F\u2819\u281B\u2827","\u2800\u2816\u287C\u2809\u2809\u28A0\u28F0\u2825\u28AD\u2818\u28DB\u28C4\u288B\u28C9\u28C9\u2859","\u2800\u28B8\u284C\u2880\u28E0\u28F5\u28FF\u28FF\u28FF\u28FF\u28E8\u2803\u2837\u2802\u2810\u288D","\u2800\u2800\u283B\u281D\u283F\u28F4\u28FF\u28FF\u287F\u28FF\u28DF\u28CB\u284F\u2841\u2804\u2818","\u2800\u28B8\u28F0\u28F6\u28C4\u283B\u283F\u28FF\u28F9\u2830\u281F\u2882\u28A0\u285F\u28C6\u28F4","\u2800\u28AA\u2849\u2838\u28FB\u2807\u2800\u285D\u28DB\u2880\u2840\u28D8\u285F\u2877\u28EB\u286F","\u2800\u2819\u283B\u282A\u281C\u2813\u2802\u2808\u281B\u2813\u281B\u2819\u281A\u2808\u2801\u2800"],BR2=["\u287F\u28FB\u28D6\u28F8\u2800\u28DE\u2861\u281F\u2880\u2804\u28BB\u28FF\u28FF\u28C0\u2800\u2800","\u2836\u281B\u280B\u28B9\u28B8\u2890\u2840\u2850\u2821\u283E\u28ED\u28BD\u28DB\u2897\u2842\u2800","\u288B\u28C9\u28C9\u2859\u28E0\u28DB\u2803\u286D\u282C\u28C6\u2844\u2809\u2829\u28A7\u2832\u2800","\u2869\u2802\u2810\u283E\u2818\u28C5\u28FF\u28FF\u28FF\u28FF\u28EE\u28C4\u2840\u28B1\u2847\u2800","\u2803\u2880\u2888\u28B3\u28D9\u28FB\u28FF\u28DF\u28FF\u28FF\u28E6\u283F\u282B\u281F\u2800\u2800","\u28E6\u28F0\u28BB\u2844\u2850\u283B\u2803\u28CF\u28FF\u283F\u281F\u28E0\u28F6\u28C6\u2847\u2800","\u28BD\u28DD\u28AF\u28BB\u28C3\u2880\u2840\u28DB\u28E9\u2800\u2838\u28DF\u2807\u2889\u2855\u2800","\u2801\u2800\u2801\u2813\u280B\u281B\u281A\u281B\u2801\u2810\u281A\u2823\u2807\u281F\u280B\u2800"],T2=["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2844\u28E2\u28F4\u28F6\u2836\u2816\u2832\u28CC\u2818\u2809\u2822\u285B\u28A1\u2834\u2832\u2836\u28F0\u2896\u28B4\u28E4","\u28FE\u28E5\u283F\u2800\u28E0\u28B0\u283F\u28BE\u2850\u283E\u283F\u2887\u2873\u28FF\u28D7\u2804\u2800\u2823\u28D1\u28F5","\u28BE\u285F\u2804\u2810\u28AD\u28CD\u2896\u2844\u2828\u28BB\u28EB\u283D\u287C\u287F\u28BD\u28A5\u2842\u2804\u283B\u287D","\u2813\u287B\u28B6\u28C4\u2848\u2818\u282D\u281A\u280D\u28BB\u2849\u280B\u280B\u282D\u2803\u2803\u2861\u28F6\u28DF\u28BE","\u2801\u2804\u2809\u2809\u281A\u2824\u2824\u282C\u281F\u2830\u2827\u280A\u282F\u2834\u2824\u2813\u281B\u2809\u2810\u2822","\u28DB\u28DB\u285F\u28DB\u285B\u28DB\u28DB\u289B\u28DB\u28DB\u285B\u28DB\u28DB\u289B\u28FB\u28FB\u28DF\u281B\u28FB\u28BB","\u28CA\u28C9\u28C9\u28DB\u28CB\u28D9\u28CB\u28FC\u28F7\u28E5\u28EF\u28FA\u28CB\u28F5\u28F7\u28ED\u28D9\u28D1\u28FB\u28FD"],B2=["\u28FF\u28BF\u28FF\u28FF\u28BF\u28FF\u287F\u287F\u28FF\u28FF\u283F\u28FF\u28BF\u287F\u28FF\u28FF\u287F\u28FF\u287F\u28BF","\u28C3\u28DB\u28C8\u28D3\u28DA\u28DA\u28C3\u28D9\u28DB\u28C9\u28DB\u28DB\u28C1\u28DB\u28D9\u28D9\u28CB\u28D8\u28C9\u28D9","\u2820\u2884\u2884\u28C0\u2864\u28E4\u2810\u28E0\u2884\u28A0\u2844\u2864\u28C4\u2800\u2864\u2884\u28C0\u2840\u2880\u2880","\u28F1\u282C\u282B\u2811\u2881\u28E0\u28A0\u286B\u28E1\u28E0\u28E4\u28C9\u2885\u2884\u28C4\u2809\u283B\u2850\u28A5\u28CC","\u2894\u28C8\u2800\u28B0\u2841\u28B6\u28FF\u28FF\u28DF\u28FF\u28C3\u285B\u2815\u280D\u28E6\u28C3\u2844\u2802\u28F9\u2862","\u287F\u288F\u2884\u2800\u2803\u28EB\u28FF\u289C\u28A9\u28F6\u28E6\u2809\u2876\u28FE\u2856\u281B\u2800\u28E0\u285B\u287F","\u283C\u28BE\u283F\u28F5\u28D6\u28D8\u2834\u2803\u2808\u2886\u2880\u2800\u2873\u2824\u28C2\u28F2\u28FE\u282F\u281A\u280F","\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u280B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800"],L2=["\u2800\u2800\u2890\u289F\u28FE\u283F\u282E\u2836\u2877\u28EA\u283E\u2802\u2857\u28AD\u28BF\u28B9","\u2800\u2800\u28E8\u2855\u2809\u2861\u2824\u28C1\u284C\u282A\u28A7\u2801\u2847\u28F0\u28FF\u28BC","\u2800\u2800\u2839\u2843\u28BE\u28D5\u28F7\u2866\u28D3\u2840\u2849\u2846\u284F\u28F6\u2863\u28FB","\u2800\u28B0\u2876\u28AC\u28ED\u285C\u28FF\u28FF\u28EF\u2888\u2893\u2801\u284F\u28DA\u287E\u28FF","\u2800\u2818\u285B\u288A\u28D9\u2823\u2887\u28AF\u28FF\u2828\u286D\u2841\u2867\u28BC\u28F2\u28FF","\u2800\u2800\u28B1\u2849\u28BF\u2847\u2824\u28DD\u2844\u2800\u2841\u2801\u284F\u28F6\u2896\u28BF","\u2800\u2800\u28B0\u28E7\u2840\u2813\u2813\u2809\u2881\u28F4\u284D\u2800\u2847\u283A\u283D\u28BA","\u2800\u2800\u2828\u283A\u28FD\u28F7\u28E6\u2874\u285A\u2803\u2880\u2800\u2847\u287E\u28FF\u28B9"],R=["\u284F\u287F\u286D\u28BA\u2880\u2837\u289D\u28BE\u2836\u2835\u283F\u28F7\u287B\u2842\u2800\u2800","\u2867\u28FF\u28C6\u28B8\u2800\u287C\u2815\u28A1\u28C0\u2824\u288C\u2809\u28AA\u28C5\u2801\u2800","\u28DF\u289C\u28F6\u28B9\u28B0\u2889\u2880\u28DA\u28B4\u28FE\u28EA\u2877\u2898\u280F\u2800\u2800","\u28FF\u28B7\u285B\u28B9\u2808\u285A\u2841\u28FD\u28FF\u28FF\u28A3\u28ED\u2865\u28B6\u2846\u2800","\u28FF\u28D6\u2867\u28BC\u2888\u28AD\u2805\u28FF\u287D\u2878\u2858\u28CB\u2851\u289B\u2803\u2800","\u287F\u2872\u28F6\u28B9\u2808\u2888\u2800\u28A0\u28EB\u2824\u28B8\u287F\u2889\u2846\u2800\u2800","\u2857\u282F\u2817\u28B8\u2800\u28A9\u28E6\u2848\u2809\u281A\u281A\u2880\u28FC\u2846\u2800\u2800","\u284F\u28FF\u28AF\u28B8\u2800\u2880\u2818\u2893\u28A6\u28B6\u28FE\u28EF\u2817\u2805\u2800\u2800"];function frame(w2,h2){let{cw,ch,tw,tv}=FRAME,mw=w2-2*cw,mh=h2-2*ch,inner={x:cw,y:ch,w:Math.max(0,mw),h:Math.max(0,mh)};if(mw<4||mh<2)return{lines:[],inner};let repH=(p,span2)=>p.map((l2)=>l2.repeat(Math.ceil(span2/tw)).slice(0,span2)),repV=(p,span2)=>Array.from({length:span2},(_2,i)=>p[i%tv]),t2=repH(T2,mw),b2=repH(B2,mw),l=repV(L2,mh),r=repV(R,mh),mid2=" ".repeat(mw),out=[];for(let i=0;i<ch;i++)out.push(TL[i]+t2[i]+TR[i]);for(let i=0;i<mh;i++)out.push(l[i]+mid2+r[i]);for(let i=0;i<ch;i++)out.push(BL[i]+b2[i]+BR2[i]);return{lines:out,inner}}import{readFileSync as readFileSync17}from"fs";import{join as join20}from"path";var FALLBACK=["`@file:path/to/file.py` injects file contents directly into your message.","`/title <name>` names the session \u2014 resume it later from the Sessions tab.","Ctrl+G opens $EDITOR seeded with the composer contents.","Ctrl+Z suspends to the shell; `fg` resumes.","Pasting 5+ lines collapses to a `[Pasted #N \u2026]` placeholder.","Click a user message in the transcript to rewind to that point."],HL=/(\/[a-z][\w-]*|@[\w:./-]+|(?:Ctrl|Alt|Shift)\+\S+|`[^`]+`|"[^"]+")/g;function splitTip(tip2){let out=[],i=0;for(let m2 of tip2.matchAll(HL)){let j2=m2.index;if(j2>i)out.push({t:tip2.slice(i,j2),hl:!1});out.push({t:m2[0].replace(/^`|`$/g,""),hl:!0}),i=j2+m2[0].length}if(i<tip2.length)out.push({t:tip2.slice(i),hl:!1});return out}var cache5=null;function loadTips(){if(cache5)return cache5;try{let body=readFileSync17(join20(hermesAgentRoot(),"hermes_cli","tips.py"),"utf8").split(/^TIPS\s*=\s*\[/m)[1]?.split(/^\]/m)[0]??"",tips=[];for(let line4 of body.split(`
|
|
4147
|
-
`)){let m2=line4.match(/^\s+"((?:[^"\\]|\\.)*)",?\s*$/);if(m2)tips.push(m2[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"))}cache5=tips.length>10?tips:FALLBACK}catch{cache5=FALLBACK}return cache5}function randomTip(prev){let t2=loadTips();if(t2.length<2)return t2[0]??"";let pick2=t2[Math.floor(Math.random()*t2.length)];while(pick2===prev)pick2=t2[Math.floor(Math.random()*t2.length)];return pick2}import{readFileSync as readFileSync18,existsSync as existsSync26}from"fs";import{dirname as dirname14,join as join21}from"path";var pkgVersion=(d2,up=4)=>{let p=join21(d2,"package.json");if(existsSync26(p))return JSON.parse(readFileSync18(p,"utf8")).version;return up>0?pkgVersion(dirname14(d2),up-1):"0.0.0"},VERSION=pkgVersion(import.meta.dirname);function parseLaunch(argv){let splash=!0;for(let i=0;i<argv.length;i++){let a=argv[i];if(a==="--no-splash"){splash=!1;continue}if(a==="-c"||a==="--continue")
|
|
4147
|
+
`)){let m2=line4.match(/^\s+"((?:[^"\\]|\\.)*)",?\s*$/);if(m2)tips.push(m2[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"))}cache5=tips.length>10?tips:FALLBACK}catch{cache5=FALLBACK}return cache5}function randomTip(prev){let t2=loadTips();if(t2.length<2)return t2[0]??"";let pick2=t2[Math.floor(Math.random()*t2.length)];while(pick2===prev)pick2=t2[Math.floor(Math.random()*t2.length)];return pick2}import{readFileSync as readFileSync18,existsSync as existsSync26}from"fs";import{dirname as dirname14,join as join21}from"path";var pkgVersion=(d2,up=4)=>{let p=join21(d2,"package.json");if(existsSync26(p))return JSON.parse(readFileSync18(p,"utf8")).version;return up>0?pkgVersion(dirname14(d2),up-1):"0.0.0"},VERSION=pkgVersion(import.meta.dirname);function parseLaunch(argv){let splash=!0,mode="new",profile,sid2;for(let i=0;i<argv.length;i++){let a=argv[i];if(a==="--no-splash"){splash=!1;continue}if(a==="--profile"){let next2=argv[i+1];if(!next2||next2.startsWith("-"))throw Error("--profile requires a name");profile=next2,i++;continue}if(a==="-c"||a==="--continue"){mode="resume";continue}if(a==="--resume"){let next2=argv[i+1];if(mode="resume",next2&&!next2.startsWith("-"))sid2=next2,i++}}if(mode==="resume")return{mode,...profile?{profile}:{},...sid2?{sid:sid2}:{},splash};return{mode,...profile?{profile}:{},splash}}var HELP3=`herm \u2014 OpenTUI client for hermes-agent
|
|
4148
4148
|
|
|
4149
4149
|
Usage:
|
|
4150
4150
|
herm start a fresh session
|
|
4151
4151
|
herm -c, --continue resume the last real TUI session
|
|
4152
4152
|
herm --resume [id] resume last (or the given) session
|
|
4153
|
+
herm --profile <name> start once with a profile; do not change the default
|
|
4153
4154
|
herm --no-splash skip the launch splash
|
|
4154
4155
|
herm -v, --version print version
|
|
4155
4156
|
herm -h, --help show this help
|
|
@@ -4235,4 +4236,4 @@ Run 'herm eikon use ${out.name}' to activate.`)}if(cmd==="search"||cmd==="browse
|
|
|
4235
4236
|
trust: ${out.trust}`)}if(cmd==="list"){let rows3=deps.list().map((e)=>({name:e.name,file:e.file,hasSource:e.hasSource,sourceUrl:e.sourceUrl,lifecycle:e.lifecycle})),active=deps.getActive()??null;if(p.json)return emit(io2,JSON.stringify({ok:!0,active,eikons:rows3}));return emit(io2,rows3.length?rows3.map((e)=>`${e.name}${e.name===active?" *":""}`).join(`
|
|
4236
4237
|
`):"No installed eikons")}if(cmd==="use"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon use <name>",p.json);if(!deps.has(name)&&!deps.baked(name))return emitError(io2,`No installed or bundled eikon named '${name}'`,p.json);if(deps.setActive(name),p.json)return emit(io2,JSON.stringify({ok:!0,active:name}));return emit(io2,`Avatar \u2192 ${name}`)}if(cmd==="remove"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon remove <name>",p.json);if(!deps.has(name))return emitError(io2,`No installed eikon named '${name}'`,p.json);let wasActive=deps.getActive()===name,result=deps.remove(name,{confirmActive:p.activeOk});if(result?.type==="active-consequence")return emitError(io2,activeMessage(result),p.json,{consequence:"active",action:result.action,name:result.name});if(p.json)return emit(io2,JSON.stringify({ok:!0,name,removed:!0,activeCleared:wasActive}));return emit(io2,`Removed '${name}'${wasActive?" and cleared active avatar":""}`)}if(cmd==="update"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon update <name>",p.json);let out=await deps.update(name,{confirmActive:p.activeOk});if(isActiveConsequence(out))return emitError(io2,activeMessage(out),p.json,{consequence:"active",action:out.action,name:out.name});let active=deps.getActive()??null;if(p.json)return emit(io2,JSON.stringify({ok:!0,name:out.name,n:out.n,bytes:out.bytes,active}));return emit(io2,`Updated '${out.name}' (${out.n} files)`)}return emitError(io2,`unknown eikon command '${cmd}'`,p.json)}catch(e){return emitError(io2,e instanceof Error?e.message:String(e),p.json)}}init_perf();var exports_bundled_skills={};__export(exports_bundled_skills,{sync:()=>sync,skills:()=>exports_bundled_skills});import{existsSync as existsSync32,mkdirSync as mkdirSync10,readdirSync as readdirSync11,cpSync as cpSync2}from"fs";import{dirname as dirname15,join as join28}from"path";var locate4=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join28(d2,"assets/skills");if(existsSync32(p))return p;let up=dirname15(d2);if(up===d2)break;d2=up}return};function has2(root3,n){if(existsSync32(join28(root3,n,"SKILL.md")))return!0;if(!existsSync32(root3))return!1;return readdirSync11(root3,{withFileTypes:!0}).some((e)=>e.isDirectory()&&existsSync32(join28(root3,e.name,n,"SKILL.md")))}function sync(){let src3=locate4();if(!src3)return[];let root3=hermesPath("skills"),dst=join28(root3,"creative"),out=[];for(let e of readdirSync11(src3,{withFileTypes:!0})){if(!e.isDirectory())continue;if(has2(root3,e.name))continue;mkdirSync10(dst,{recursive:!0}),cpSync2(join28(src3,e.name),join28(dst,e.name),{recursive:!0}),out.push(e.name)}return out}var exports_bundled_plugins={};__export(exports_bundled_plugins,{sync:()=>sync2,plugins:()=>exports_bundled_plugins});import{cpSync as cpSync3,existsSync as existsSync33,mkdirSync as mkdirSync11,readFileSync as readFileSync23,readdirSync as readdirSync12,writeFileSync as writeFileSync12}from"fs";import{dirname as dirname16,join as join29}from"path";var locate5=()=>{let dir2=import.meta.dir;for(let i=0;i<5;i++){let path4=join29(dir2,"assets/plugins");if(existsSync33(path4))return path4;let up=dirname16(dir2);if(up===dir2)break;dir2=up}return},obj2=(v2)=>v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:{},arr3=(v2)=>Array.isArray(v2)?v2.map(String):[];function ours(dir2){let path4=join29(dir2,"plugin.yaml");if(!existsSync33(path4))return!1;let raw2=readFileSync23(path4,"utf8");return raw2.includes("name: eikon")&&raw2.includes("eikon_install")}function enable(name){let path4=hermesPath("config.yaml"),raw2=existsSync33(path4)?readFileSync23(path4,"utf8"):"",doc=$parseDocument(raw2||`{}
|
|
4237
4238
|
`),js=doc.toJS();if(!js||typeof js!=="object"||Array.isArray(js))doc.contents=doc.createNode({});let cfg=obj2(doc.toJS()),plug=obj2(cfg.plugins);if(arr3(plug.disabled).includes(name)||arr3(plug.enabled).includes(name))return!1;return doc.setIn(["plugins","enabled"],[...arr3(plug.enabled),name]),mkdirSync11(dirname16(path4),{recursive:!0}),writeFileSync12(path4,String(doc),"utf8"),!0}function sync2(){let src3=locate5();if(!src3)return[];let root3=hermesPath("plugins"),out=[];for(let e of readdirSync12(src3,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let dst=join29(root3,e.name),fresh2=!existsSync33(dst);if(fresh2)mkdirSync11(root3,{recursive:!0}),cpSync3(join29(src3,e.name),dst,{recursive:!0}),out.push(e.name);if(fresh2||ours(dst))enable(e.name)}catch{}}return out}import{writeSync as writeSync2}from"fs";var TERMINAL_MODE_RESET="\x1B[0'z\x1B[0'{\x1B[?2029l\x1B[?1016l\x1B[?1015l\x1B[?1006l\x1B[?1005l\x1B[?1003l\x1B[?1002l\x1B[?1001l\x1B[?1000l\x1B[?9l\x1B[?1004l\x1B[?2004l\x1B[?1049l\x1B[<u\x1B[>4;0m\x1B[0m\x1B[?25h";function resetTerminalModes(stream=process.stdout){if(!stream.isTTY)return!1;let fd=typeof stream.fd==="number"?stream.fd:stream===process.stdout?1:void 0;if(fd!==void 0)try{return writeSync2(fd,TERMINAL_MODE_RESET),!0}catch{}try{return stream.write(TERMINAL_MODE_RESET),!0}catch{return!1}}var wired=!1;function installExitResetHooks(){if(wired)return;wired=!0,process.on("exit",()=>{resetTerminalModes()});let codes={SIGHUP:129,SIGINT:130,SIGTERM:143};for(let sig of["SIGINT","SIGTERM","SIGHUP"])process.on(sig,()=>{resetTerminalModes(),process.exit(codes[sig])});process.on("uncaughtException",(err)=>{resetTerminalModes(),console.error(err),process.exit(1)}),process.on("unhandledRejection",(reason)=>{resetTerminalModes(),console.error(reason),process.exit(1)})}var cfg={columns:{fallback:80,max:500},rows:{fallback:24,max:200}};function sanitizeTerminalDimension(value2,dim2){if(typeof value2!=="number")return cfg[dim2].fallback;if(!Number.isFinite(value2))return cfg[dim2].fallback;let n=Math.floor(value2);if(n<2)return cfg[dim2].fallback;return Math.min(n,cfg[dim2].max)}function findDescriptor(stream,dim2){let cur=stream;while(cur){let desc=Object.getOwnPropertyDescriptor(cur,dim2);if(desc)return desc;cur=Object.getPrototypeOf(cur)}return}function patchDimension(stream,dim2){let desc=findDescriptor(stream,dim2);if(desc&&desc.configurable===!1)return!1;let raw2=desc&&"value"in desc?desc.value:void 0,read4=desc?.get,write=desc?.set;try{return Object.defineProperty(stream,dim2,{configurable:!0,enumerable:desc?.enumerable??!0,get(){let value2=read4?read4.call(stream):raw2;return sanitizeTerminalDimension(value2,dim2)},set(value2){if(write){write.call(stream,value2);return}raw2=value2}}),!0}catch{return!1}}function clampStdoutDimensions(stream=process.stdout){if(!stream||typeof stream!=="object")return!1;let columns=patchDimension(stream,"columns"),rows3=patchDimension(stream,"rows");return columns||rows3}boot("import-graph",Bun.nanoseconds()/1e6);var argv=Bun.argv.slice(2);if(argv[0]==="eikon"&&argv[1]==="install")exports_bundled_plugins.sync();var eikonCliExit=await handleEikonCli(argv);if(eikonCliExit!==null)process.exit(eikonCliExit);if(argv.includes("--help")||argv.includes("-h"))process.stdout.write(HELP3),process.exit(0);if(argv.includes("--version")||argv.includes("-v"))process.stdout.write(VERSION+`
|
|
4238
|
-
`),process.exit(0);var launch=parseLaunch(argv)
|
|
4239
|
+
`),process.exit(0);var launch=parseLaunch(argv);if(launch.profile){let home4=resolveProfileHome(launch.profile);if(!home4)throw Error(`profile not found: ${launch.profile}`);rehome(home4)}var main2=async()=>{resetTerminalModes(),installExitResetHooks(),clampStdoutDimensions(),mem("pre-renderer");let prefs=load2(),end=mark("renderer-init"),renderer=await createCliRenderer({exitOnCtrlC:!1,useMouse:prefs.mouse??!0,targetFps:prefs.targetFps??30,gatherStats:!1});renderer.setMaxListeners(64),end();let bump3=()=>renderer.capabilities?.kitty_keyboard||process.stdout.isTTY&&process.stdout.write("\x1B[>4;2m");bump3(),renderer.on("focus",bump3),mem("post-renderer"),await prime(prefs.theme??DEFAULT_THEME);let root3=createRoot(renderer),endRender=mark("first-render");root3.render($jsx(App,{initialTheme:prefs.theme,launch})),endRender(),boot("first-render",Bun.nanoseconds()/1e6),warmup(),warm(),exports_bundled_skills.sync(),exports_bundled_plugins.sync(),mem("post-first-render"),monitor(15000),start()};main2().catch(console.error);
|