herm-tui 1.11.0-dev.3 → 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 +4 -3
- 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
|
|
|
@@ -4144,12 +4144,13 @@ high contrast, light subject on dark, black background`,BINDS=[{name:"return",ac
|
|
|
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);
|