herm-tui 1.8.2-dev.3 → 1.8.2-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.
Files changed (2) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -4086,7 +4086,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
4086
4086
  `),add=lines2.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines2.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add,del}})}var DiffTabs=import_react37.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react37.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react37.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react38=__toESM(require_react_production(),1);function digit(name){let n=parseInt(name,10);return Number.isFinite(n)?n:null}var Frame=(p)=>{let theme=useTheme().theme;return $jsx("box",{flexDirection:"column",border:["left"],borderColor:p.tint,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,marginBottom:1,children:p.children})},Pill=(p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,paddingX:1,backgroundColor:p.on?theme.primary:void 0,onMouseDown:p.onPick,children:$jsxs("text",{children:[$jsxs("span",{fg:p.on?theme.background:theme.textMuted,children:[p.hot," "]}),$jsx("span",{fg:p.on?theme.background:theme.text,children:p.label})]})})},CHOICES=["once","session","always","deny"],LABELS={once:"Allow once",session:"Allow this session",always:"Always allow",deny:"Deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),[steering,setSteering]=import_react38.useState(!1),[custom,setCustom]=import_react38.useState(""),[note,setNote]=import_react38.useState(""),done=import_react38.useRef(!1),send=(c)=>{if(done.current)return;done.current=!0,gw.request("approval.respond",{choice:c}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text2)=>{let body=text2.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react38.useImperativeHandle(ref,()=>({masked:steering,feed:(key2)=>{if(steering){if(key2.name==="escape")return setSteering(!1),!0;return!1}if(key2.name==="s")return setSteering(!0),setNote(""),!0;if(key2.name==="left"||key2.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key2.name==="right"||key2.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key2.name==="return")return send(CHOICES[sel]),!0;if(key2.name==="escape")return send("deny"),!0;let n=digit(key2.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react38.useState(0),[typing,setTyping]=import_react38.useState(choices.length===0),[custom,setCustom]=import_react38.useState(""),done=import_react38.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react38.useImperativeHandle(ref,()=>({masked:typing,feed:(key2)=>{if(typing){if(key2.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key2.name==="escape")return send(""),!0;if(key2.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key2.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key2.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key2.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react38.useState(""),done=import_react38.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react38.useImperativeHandle(ref,()=>({masked:!0,feed:(key2)=>{if(key2.name==="escape")return go(""),!0;return!1}}),[]),$jsx(Frame,{tint:theme.warning,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})}),$jsx("text",{fg:theme.text,children:p.note}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value,onInput:setValue,onSubmit:()=>go(value),focused:!0,flexGrow:1,textColor:theme.backgroundElement,cursorColor:theme.accent,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{position:"absolute",left:2,top:0,height:1,children:$jsx("text",{fg:theme.text,bg:theme.backgroundElement,children:"\u2022".repeat(value.length)})})]}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync8,statSync as statSync2}from"fs";function parseChafaLine(line){let out=[],fg2=null,bg2=null,reverse2=!1,i=0,N2=line.length;while(i<N2){if(line.charCodeAt(i)===27&&line.charCodeAt(i+1)===91){let end=line.indexOf("m",i+2);if(end<0){i=N2;break}let params=line.slice(i+2,end).split(";").map((x2)=>parseInt(x2,10)||0),p=0;while(p<params.length){let n=params[p];if(n===0){fg2=null,bg2=null,reverse2=!1,p++;continue}if(n===7){reverse2=!0,p++;continue}if(n===27){reverse2=!1,p++;continue}if(n===38&&params[p+1]===2){fg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===48&&params[p+1]===2){bg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===39){fg2=null,p++;continue}if(n===49){bg2=null,p++;continue}p++}i=end+1;continue}let cp=line.codePointAt(i),ch=String.fromCodePoint(cp);i+=ch.length;let efg=reverse2?bg2:fg2,ebg=reverse2?fg2:bg2;out.push({ch,fg:efg,bg:ebg})}return out}function parseChafa(text2){return text2.split(`
4087
4087
  `).filter((s)=>s.length>0).map(parseChafaLine)}function hex(c){if(!c)return;return`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`}var CHAFA_PATHS=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa","/home/linuxbrew/.linuxbrew/bin/chafa"],cachedBin=void 0;function chafaBin(){if(cachedBin!==void 0)return cachedBin;for(let p of CHAFA_PATHS)if(existsSync8(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync8(full)?full:null}var CACHE=new Map,CACHE_CAP=50;function cacheGet(k2){let v2=CACHE.get(k2);if(!v2)return;return CACHE.delete(k2),CACHE.set(k2,v2),v2}function cachePut(k2,v2){if(CACHE.size>=CACHE_CAP)CACHE.delete(CACHE.keys().next().value);CACHE.set(k2,v2)}function renderChafa(path7,width,height){let bin=chafaBin();if(!bin)return{err:"chafa not installed"};let full=resolveImage(path7);if(!full)return{err:`not found: ${path7}`};let mtime=0;try{mtime=statSync2(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key2=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key2);if(cached2)return{rows:cached2};let r=spawnSync(bin,[`--size=${width}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8",timeout:5000});if(r.error)return{err:r.error.message};if(r.status!==0)return{err:(r.stderr||`chafa exit ${r.status}`).trim()};let rows2=parseChafa(r.stdout);return cachePut(key2,rows2),{rows:rows2}}var basename6=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react39.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react39.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react39.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row2,i)=>$jsx("text",{children:row2.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,onMouseDown:(e)=>{e.stopPropagation(),openFile(path7)},children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.accent,children:"\u25C9 "}),$jsx("span",{fg:theme.text,children:basename6(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react40=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react40.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react40.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react40.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsx("box",{flexDirection:"column",marginBottom:1,backgroundColor:hover?theme.backgroundElement:void 0,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:$jsx(Gutter2,{color:theme.primary,side:"left",children:$jsx("box",{minHeight:1,flexDirection:"column",children:message.parts.map((p,i)=>{let seg=segs[i];if(!seg)return null;let k2=p.key??i;return seg.map((s,j2)=>{if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang},`${k2}-c${j2}`);return $jsx("text",{fg:theme.text,wrapMode:"word",children:s.md},`${k2}-${j2}`)})})})})})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsx("box",{flexDirection:"column",marginBottom:1,backgroundColor:hover?theme.backgroundElement:void 0,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:$jsxs(Gutter2,{color:err?theme.error:theme.accent,side:"right",children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]})})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant",firstUser=messages.findIndex((m2)=>m2.role==="user");return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsxs("box",{flexDirection:"column",children:[msg.role==="user"&&i>firstUser?$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"\u2500\u2500\u2500"})}):null,$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})]},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react61=__toESM(require_react_production(),1);var import_react53=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync9}from"fs";import{homedir as homedir4}from"os";import{join as join8}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join8(homedir4(),".hermes"),entry=()=>{let js=join8(import.meta.dirname,"db.worker.js");return new URL(existsSync9(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn=()=>{if(state.w)return state.w;let w2=new Worker(entry());return w2.onmessage=(e)=>{let r=e.data;state.pending.get(r.id)?.(r),state.pending.delete(r.id)},w2.onerror=(ev)=>{let err=`io worker: ${ev.message}`;for(let res of state.pending.values())res({id:-1,ok:!1,err});state.pending.clear()},state.w=w2},call=(fn,args)=>{if(INLINE)return state.inline??=Promise.resolve().then(() => (init_fns(),exports_fns)).then((m2)=>m2.FNS),state.inline.then((f)=>f[fn](...args));return new Promise((resolve4,reject)=>{let id=++state.seq;state.pending.set(id,(r)=>r.ok?resolve4(r.v):reject(Error(r.err))),spawn().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react45=__toESM(require_react_production(),1);var Ctx5=import_react45.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react45.useState([]),gate=import_react45.useRef(!1),gen=import_react45.useRef(0),prev=import_react45.useRef(null),refocus=import_react45.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react45.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react45.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react45.useCallback(()=>gate.current,[]),onError=import_react45.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key2)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key2))clear()});let value=import_react45.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react45.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react45.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react47=__toESM(require_react_production(),1);var HintBar=import_react47.memo((props)=>{let theme=useTheme().theme,text2=props.pairs?props.pairs.map((p)=>`[${p[0]}] ${p[1]}`).join(" ")+(props.suffix?` \xB7 ${props.suffix}`:""):props.raw??"";return $jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text2})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight: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:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react48=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text2=p.children,box=import_react48.useRef(null),node=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react48.useState(!1);import_react48.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text2.length>w2),!animate){tn.scrollX=0;return}let id,period=text2.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text2.length<=cur){tn.scrollX=0;return}tn.scrollX=(tn.scrollX+1)%period},p.speed??180)},p.hold??600);return()=>{if(clearTimeout(hold),id)clearInterval(id);if(node.current)node.current.scrollX=0}},[animate,text2,p.speed,p.hold]);let body=wraps?text2+GAP+text2:text2;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,children:body})})})},GAP=" ";var import_react49=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react49.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key2)=>{if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.onConfirm();if(keys.match("dialog.deny",key2))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.name==="s")return props.onPick("save");if(key2.name==="d")return props.onPick("discard");if(key2.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react51=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react51.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.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 confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost=(c)=>c==null?"\u2014":`$${c.toFixed(2)}`,clock=(d2)=>d2.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:h12()}),stamp=(ts)=>{let d2=new Date(ts*1000);return d2.toDateString()===new Date().toDateString()?clock(d2):d2.toLocaleDateString(void 0,{month:"short",day:"numeric"})},rel=(ts)=>{let s=Math.floor(Date.now()/1000-ts);if(s<60)return"just now";if(s<3600)return`${Math.floor(s/60)}m ago`;if(s<86400)return`${Math.floor(s/3600)}h ago`;return`${Math.floor(s/86400)}d ago`},ago=(ts)=>abs()?stamp(ts):rel(ts),until=(ts)=>{if(abs())return ts<=Date.now()/1000?"due":stamp(ts);let s=Math.floor(ts-Date.now()/1000);if(s<=0)return"due";if(s<60)return`in ${s}s`;if(s<3600)return`in ${Math.floor(s/60)}m`;if(s<86400)return`in ${Math.floor(s/3600)}h`;return`in ${Math.floor(s/86400)}d`},when=(ts)=>{let d2=new Date(ts*1000);return`${d2.toLocaleDateString()} ${clock(d2)}`},span=(start,end)=>{let s=Math.round(end-start);if(s<0)return"\u2014";if(s>=3600)return`${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m`;if(s>=60)return`${Math.floor(s/60)}m`;return`${s}s`},dur2=(s)=>s>=3600?`${Math.floor(s/3600)}h${Math.floor(s%3600/60)}m`:s>=60?`${Math.floor(s/60)}m${Math.floor(s%60)}s`:`${Math.floor(s)}s`;var import_react52=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync11,statSync as statSync3}from"fs";import{dirname as dirname4,basename as basename7}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync as openSync2,readSync as readSync2,closeSync as closeSync2,readdirSync as readdirSync4,readFileSync as readFileSync3,existsSync as existsSync10}from"fs";import{homedir as homedir5}from"os";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,$YAMLError=errors.YAMLError,$YAMLParseError=errors.YAMLParseError,$YAMLWarning=errors.YAMLWarning,$Alias=Alias.Alias,$isAlias=identity.isAlias,$isCollection=identity.isCollection,$isDocument=identity.isDocument,$isMap=identity.isMap,$isNode=identity.isNode,$isPair=identity.isPair,$isScalar=identity.isScalar,$isSeq=identity.isSeq,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,$parse=publicApi.parse,$parseAllDocuments=publicApi.parseAllDocuments,$parseDocument=publicApi.parseDocument,$stringify=publicApi.stringify,$visit=visit.visit,$visitAsync=visit.visitAsync;init_sessions_db();var HOME3=process.env.HOME||homedir5(),home={path:process.env.HERMES_HOME||`${HOME3}/.hermes`},setHome2=(h2)=>{home.path=h2},hermesPath=(relative2)=>`${home.path}/${relative2}`,managedSystem=async()=>{let env2=(process.env.HERMES_MANAGED??"").trim();if(env2){let norm=env2.toLowerCase();if(norm==="1"||norm==="true"||norm==="yes"||norm==="on")return"NixOS";return{homebrew:"Homebrew",nix:"NixOS",nixos:"NixOS"}[norm]??env2}return await Bun.file(hermesPath(".managed")).exists()?"NixOS":null},makeSource=(relative2,label)=>({file:hermesPath(relative2),relative:relative2,label:label??relative2.split("/").pop()??relative2});function readSkillFrontmatter(source){try{let fd=openSync2(source.file,"r"),buf=Buffer.alloc(2048),n=readSync2(fd,buf,0,2048,0);closeSync2(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
4088
4088
  ---`,3);if(end<0)return{description:"",tags:[]};let fm=$parse(head.slice(3,end)),tags=Array.isArray(fm.tags)?fm.tags.map(String):[];return{description:String(fm.description??""),tags}}catch{return{description:"",tags:[]}}}async function readSkillUsage(){try{let f=Bun.file(hermesPath("skills/.usage.json"));if(!await f.exists())return{};let raw=await f.json(),out={};for(let[k2,v2]of Object.entries(raw??{}))out[k2]={use_count:Number(v2.use_count??0),view_count:Number(v2.view_count??0),patch_count:Number(v2.patch_count??0),last_used_at:v2.last_used_at??null,last_viewed_at:v2.last_viewed_at??null,last_patched_at:v2.last_patched_at??null,created_at:v2.created_at??null,archived_at:v2.archived_at??null,state:v2.state??"active",pinned:Boolean(v2.pinned)};return out}catch{return{}}}async function readCuratorState(){try{let f=Bun.file(hermesPath("skills/.curator_state"));if(!await f.exists())return null;let raw=await f.json();return{last_run_at:raw.last_run_at??null,last_run_duration_seconds:raw.last_run_duration_seconds??null,last_run_summary:raw.last_run_summary??null,paused:Boolean(raw.paused),run_count:Number(raw.run_count??0)}}catch{return null}}async function readLatestCuratorReport(){try{let base2=hermesPath("logs/curator"),entries2=readdirSync4(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory());if(entries2.length===0)return null;entries2.sort((a,b2)=>b2.name.localeCompare(a.name));let runId=entries2[0].name,rel2=`logs/curator/${runId}/REPORT.md`,source=makeSource(rel2),body=await Bun.file(source.file).text();return{source,content:body.trim(),runId}}catch{return null}}function listCuratorRuns(){try{let base2=hermesPath("logs/curator");return readdirSync4(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory()).sort((a,b2)=>b2.name.localeCompare(a.name)).flatMap((e)=>{try{let fd=openSync2(`${base2}/${e.name}/run.json`,"r"),buf=Buffer.alloc(8192),n=readSync2(fd,buf);closeSync2(fd);let j2=JSON.parse(buf.toString("utf8",0,n)),c=j2.counts??{};return[{id:e.name,at:Date.parse(j2.started_at??"")/1000||0,archived:c.archived_this_run??0,consolidated:c.consolidated_this_run??0,added:c.added_this_run??0,before:c.before??0,after:c.after??0}]}catch{return[]}})}catch{return[]}}async function readCuratorReport(id){try{return(await Bun.file(hermesPath(`logs/curator/${id}/REPORT.md`)).text()).trim()}catch{return""}}function indexCuratorLineage(){let out=new Map,push2=(name,ev)=>{let a=out.get(name)??[];a.push(ev),out.set(name,a)};try{let base2=hermesPath("logs/curator");for(let e of readdirSync4(base2,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let j2=JSON.parse(readFileSync3(`${base2}/${e.name}/run.json`,"utf8")),at=Date.parse(j2.started_at??"")/1000||0,run=e.name,into=new Map;for(let c of j2.consolidated??[])push2(c.name,{kind:"merged",run,at,into:c.into,reason:c.reason}),into.set(c.into,[...into.get(c.into)??[],c.name]);for(let[tgt,srcs]of into)push2(tgt,{kind:"absorbed",run,at,sources:srcs});for(let t2 of j2.state_transitions??[])push2(t2.name,{kind:"transition",run,at,from:t2.from,to:t2.to});for(let p of j2.pruned??[])push2(p.name,{kind:"pruned",run,at,reason:p.reason});for(let n of j2.added??[])push2(n,{kind:"added",run,at})}catch{}}}catch{}for(let a of out.values())a.sort((x2,y2)=>y2.at-x2.at);return out}function readChangelog(){try{let source=makeSource("herm/changelog.md"),fd=openSync2(source.file,"r"),buf=Buffer.alloc(4096),n=readSync2(fd,buf);closeSync2(fd);let body=buf.toString("utf8",0,n).trim(),line=body.split(`
4089
- `).find((l)=>/^[-*\u00B7]/.test(l.trim()));return{source,headline:line?.replace(/^[-*\u00B7]\s*/,"").trim()??"",body}}catch{return null}}async function readConfig(){try{let text2=await Bun.file(hermesPath("config.yaml")).text(),raw=$parse(text2);return{source:makeSource("config.yaml","config.yaml"),model:{default:raw?.model?.default??"unknown",provider:raw?.model?.provider??"auto",base_url:raw?.model?.base_url??""},agent:{max_turns:raw?.agent?.max_turns??60,reasoning_effort:raw?.agent?.reasoning_effort??"medium"},compression:{enabled:raw?.compression?.enabled??!0,threshold:raw?.compression?.threshold??0.5,target_ratio:raw?.compression?.target_ratio??0.2,protect_last_n:raw?.compression?.protect_last_n??20,summary_model:raw?.compression?.summary_model??""},memory:{memory_enabled:raw?.memory?.memory_enabled??!0,user_profile_enabled:raw?.memory?.user_profile_enabled??!0,memory_char_limit:raw?.memory?.memory_char_limit??2200,user_char_limit:raw?.memory?.user_char_limit??1375,provider:raw?.memory?.provider??"",nudge_interval:raw?.memory?.nudge_interval??10,flush_min_turns:raw?.memory?.flush_min_turns??6},display:{personality:raw?.display?.personality??"default",skin:raw?.display?.skin??"default",show_cost:raw?.display?.show_cost??!1},curator:{enabled:raw?.curator?.enabled??!0,interval_hours:raw?.curator?.interval_hours??168,stale_after_days:raw?.curator?.stale_after_days??30,archive_after_days:raw?.curator?.archive_after_days??90},approvals:{destructive_slash_confirm:raw?.approvals?.destructive_slash_confirm??!0},gateway:{platforms:{api_server:raw?.gateway?.platforms?.api_server??void 0}}}}catch{return null}}async function readMemoryFile(filename,charLimit){try{let relative2=`memories/${filename}`,content=await Bun.file(hermesPath(relative2)).text(),entryCount=content.split("\xA7").filter((s)=>s.trim()).length;return{source:makeSource(relative2,filename),content,charCount:content.length,charLimit,usagePercent:charLimit>0?Math.round(content.length/charLimit*100):0,entryCount}}catch{return null}}async function readLiveSessions(){try{let file=Bun.file(hermesPath("sessions/sessions.json"));if(!await file.exists())return{};let text2=await file.text();return JSON.parse(text2)}catch{return{}}}var MEMORY_CFG_FILES={mem0:["mem0.json"],honcho:["honcho.json"],hindsight:["hindsight/config.json"],supermemory:["supermemory.json"],holographic:["holographic.db"]};function discoverMemoryProviders(){let names=new Set(["builtin"]);try{for(let e of readdirSync4(hermesPath("hermes-agent/plugins/memory"),{withFileTypes:!0}))if(e.isDirectory()&&!e.name.startsWith("_"))names.add(e.name)}catch{}return[...names]}async function readMemoryProviders(activeProvider){let out=[];for(let name of discoverMemoryProviders()){if(name==="builtin"){out.push({name,active:!0,config:{}});continue}let cfg={};for(let f of MEMORY_CFG_FILES[name]??[])try{let file=Bun.file(hermesPath(f));if(f.endsWith(".json")){let raw=await file.json();for(let[k2,v2]of Object.entries(raw))if(typeof v2==="string"||typeof v2==="number"||typeof v2==="boolean"){let lower=k2.toLowerCase();if(lower.includes("key")||lower.includes("token")||lower.includes("secret"))cfg[k2]=typeof v2==="string"?`${v2.slice(0,4)}...`:v2;else cfg[k2]=v2}}else{let st=await file.stat();if(st)cfg.db_size=`${Math.round(st.size/1024)}KB`}}catch{}out.push({name,active:name===activeProvider,config:cfg})}return out}async function readSoul(){try{let text2=await Bun.file(hermesPath("SOUL.md")).text();return{source:makeSource("SOUL.md"),charCount:text2.length,tokenEstimate:count2(text2),content:text2}}catch{return null}}async function readToolsFromLatestSession(){try{let dir=hermesPath("sessions");if(!existsSync10(dir))return null;let glob=new Bun.Glob("session_*.json"),latestPath="",latestTime=0;for await(let path7 of glob.scan({cwd:dir})){let stat2=await Bun.file(hermesPath(`sessions/${path7}`)).stat();if(stat2&&stat2.mtimeMs>latestTime)latestTime=stat2.mtimeMs,latestPath=path7}if(!latestPath)return null;let relative2=`sessions/${latestPath}`,tools=((await Bun.file(hermesPath(relative2)).json()).tools||[]).map((t2)=>({name:t2?.function?.name??"unknown",descriptionLength:(t2?.function?.description??"").length,paramsLength:JSON.stringify(t2?.function?.parameters??{}).length}));return{source:makeSource(relative2,latestPath),tools}}catch{return null}}async function readCronOutput(jobId,tailLines=40){let dir=hermesPath(`cron/output/${jobId}`),entries2;try{entries2=await readdir2(dir)}catch{return null}let md=entries2.filter((f)=>f.endsWith(".md")).sort().reverse();if(md.length===0)return null;let path7=`${dir}/${md[0]}`,full=await Bun.file(path7).text(),lines2=full.trimEnd().split(`
4089
+ `).find((l)=>/^[-*\u00B7]/.test(l.trim()));return{source,headline:line?.replace(/^[-*\u00B7]\s*/,"").trim()??"",body}}catch{return null}}async function readConfig(){try{let text2=await Bun.file(hermesPath("config.yaml")).text(),raw=$parse(text2);return{source:makeSource("config.yaml","config.yaml"),model:{default:raw?.model?.default??"unknown",provider:raw?.model?.provider??"auto",base_url:raw?.model?.base_url??"",context_length:raw?.model?.context_length??0},agent:{max_turns:raw?.agent?.max_turns??60,reasoning_effort:raw?.agent?.reasoning_effort??"medium"},compression:{enabled:raw?.compression?.enabled??!0,threshold:raw?.compression?.threshold??0.5,target_ratio:raw?.compression?.target_ratio??0.2,protect_last_n:raw?.compression?.protect_last_n??20,summary_model:raw?.compression?.summary_model??""},memory:{memory_enabled:raw?.memory?.memory_enabled??!0,user_profile_enabled:raw?.memory?.user_profile_enabled??!0,memory_char_limit:raw?.memory?.memory_char_limit??2200,user_char_limit:raw?.memory?.user_char_limit??1375,provider:raw?.memory?.provider??"",nudge_interval:raw?.memory?.nudge_interval??10,flush_min_turns:raw?.memory?.flush_min_turns??6},display:{personality:raw?.display?.personality??"default",skin:raw?.display?.skin??"default",show_cost:raw?.display?.show_cost??!1},curator:{enabled:raw?.curator?.enabled??!0,interval_hours:raw?.curator?.interval_hours??168,stale_after_days:raw?.curator?.stale_after_days??30,archive_after_days:raw?.curator?.archive_after_days??90},approvals:{destructive_slash_confirm:raw?.approvals?.destructive_slash_confirm??!0},gateway:{platforms:{api_server:raw?.gateway?.platforms?.api_server??void 0}}}}catch{return null}}async function readMemoryFile(filename,charLimit){try{let relative2=`memories/${filename}`,content=await Bun.file(hermesPath(relative2)).text(),entryCount=content.split("\xA7").filter((s)=>s.trim()).length;return{source:makeSource(relative2,filename),content,charCount:content.length,charLimit,usagePercent:charLimit>0?Math.round(content.length/charLimit*100):0,entryCount}}catch{return null}}async function readLiveSessions(){try{let file=Bun.file(hermesPath("sessions/sessions.json"));if(!await file.exists())return{};let text2=await file.text();return JSON.parse(text2)}catch{return{}}}var MEMORY_CFG_FILES={mem0:["mem0.json"],honcho:["honcho.json"],hindsight:["hindsight/config.json"],supermemory:["supermemory.json"],holographic:["holographic.db"]};function discoverMemoryProviders(){let names=new Set(["builtin"]);try{for(let e of readdirSync4(hermesPath("hermes-agent/plugins/memory"),{withFileTypes:!0}))if(e.isDirectory()&&!e.name.startsWith("_"))names.add(e.name)}catch{}return[...names]}async function readMemoryProviders(activeProvider){let out=[];for(let name of discoverMemoryProviders()){if(name==="builtin"){out.push({name,active:!0,config:{}});continue}let cfg={};for(let f of MEMORY_CFG_FILES[name]??[])try{let file=Bun.file(hermesPath(f));if(f.endsWith(".json")){let raw=await file.json();for(let[k2,v2]of Object.entries(raw))if(typeof v2==="string"||typeof v2==="number"||typeof v2==="boolean"){let lower=k2.toLowerCase();if(lower.includes("key")||lower.includes("token")||lower.includes("secret"))cfg[k2]=typeof v2==="string"?`${v2.slice(0,4)}...`:v2;else cfg[k2]=v2}}else{let st=await file.stat();if(st)cfg.db_size=`${Math.round(st.size/1024)}KB`}}catch{}out.push({name,active:name===activeProvider,config:cfg})}return out}async function readSoul(){try{let text2=await Bun.file(hermesPath("SOUL.md")).text();return{source:makeSource("SOUL.md"),charCount:text2.length,tokenEstimate:count2(text2),content:text2}}catch{return null}}async function readToolsFromLatestSession(){try{let dir=hermesPath("sessions");if(!existsSync10(dir))return null;let glob=new Bun.Glob("session_*.json"),latestPath="",latestTime=0;for await(let path7 of glob.scan({cwd:dir})){let stat2=await Bun.file(hermesPath(`sessions/${path7}`)).stat();if(stat2&&stat2.mtimeMs>latestTime)latestTime=stat2.mtimeMs,latestPath=path7}if(!latestPath)return null;let relative2=`sessions/${latestPath}`,tools=((await Bun.file(hermesPath(relative2)).json()).tools||[]).map((t2)=>({name:t2?.function?.name??"unknown",descriptionLength:(t2?.function?.description??"").length,paramsLength:JSON.stringify(t2?.function?.parameters??{}).length}));return{source:makeSource(relative2,latestPath),tools}}catch{return null}}async function readCronOutput(jobId,tailLines=40){let dir=hermesPath(`cron/output/${jobId}`),entries2;try{entries2=await readdir2(dir)}catch{return null}let md=entries2.filter((f)=>f.endsWith(".md")).sort().reverse();if(md.length===0)return null;let path7=`${dir}/${md[0]}`,full=await Bun.file(path7).text(),lines2=full.trimEnd().split(`
4090
4090
  `),text2=lines2.length>tailLines?`\u2026(${lines2.length-tailLines} earlier lines)
4091
4091
  `+lines2.slice(-tailLines).join(`
4092
4092
  `):full.trimEnd();return{at:(await stat(path7)).mtime,path:path7,text:text2}}var ENV_PATH=hermesPath(".env");async function readEnvFile(){try{let text2=await Bun.file(ENV_PATH).text(),vars={};for(let line of text2.split(`
@@ -4105,7 +4105,7 @@ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid)
4105
4105
  `,skE);while(end<text2.length&&end>=0){let nl=text2.indexOf(`
4106
4106
  `,end+1);if(nl<0){end=text2.length;break}let line2=text2.slice(end+1,nl).trim();if(line2.startsWith("#"))break;if(line2===""){if(text2.slice(nl+1,text2.indexOf(`
4107
4107
  `,nl+1)).trim().startsWith("#")){end=nl;break}}end=nl}mark2(skH,end+1,"skills","Skills Catalog",makeSource("skills","skills/"))}let proj=text2.indexOf("# Project Context");if(proj>=0){let conv2=text2.indexOf("Conversation started:");mark2(proj,conv2>proj?conv2:text2.length,"project","Project Context",makeSource("AGENTS.md"))}let conv=text2.indexOf("Conversation started:");if(conv>=0)mark2(conv,text2.length,"meta","Session Metadata");let start=-1;for(let i=0;i<=text2.length;i++)if(i<text2.length&&!used[i]){if(start<0)start=i}else if(start>=0){let slice=text2.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)=>text2.indexOf(a.text)-text2.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=Math.min(opts.conversationTokens,opts.inputTokens||opts.conversationTokens);result.push({id:"conversation",label:"Conversation",tokens:ct,percent:pct(ct)})}let taken=result.reduce((s,g)=>s+g.tokens,0),free=Math.max(0,opts.contextLength-taken);return result.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),result}function drill(group){if(!group.children||group.children.length===0)return[];let total=group.tokens;return group.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_react55=__toESM(require_react_production(),1);var FileLink=import_react55.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react55.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"],SLOT=Object.fromEntries(SLOTS2.map((id,i)=>[id,i])),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_react56.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_react56.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_react56.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line2 of sec.text.split(`
4108
- `)){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_react56.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_react56.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_react56.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?.tools)return null;let tools=Object.entries(info.tools).flatMap(([group,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group.length})));if(tools.length===0)return null;return{source:makeSource("state.db","session.info"),tools}},Context=import_react56.memo(({messages=NO_MESSAGES,info,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"),recentSessions=useHome("recentSessions"),liveSessions=useHome("liveSessions"),[wire,setWire]=import_react56.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react56.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react56.useState(null),[selected,setSelected]=import_react56.useState(null),[drilled,setDrilled]=import_react56.useState(null);import_react56.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 session=recentSessions?.[0],ctxLen=info?.context_max??DEFAULT_CTX,lastPrompt=(session?Object.values(liveSessions??{}).find((ls)=>ls.session_id===session.id):void 0)?.last_prompt_tokens??0,fill=wire.calls>0?wire.input:lastPrompt>0?lastPrompt:session?.input_tokens??0,cumulative=wire.calls===0&&lastPrompt===0&&(session?.input_tokens??0)>0,output=wire.calls>0?wire.output:session?.output_tokens??0,pct=ctxLen>0?Math.round(fill/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_react56.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react56.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react56.useMemo(()=>toolsFromInfo(info)??toolsInfo,[info,toolsInfo]),top=import_react56.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,fill,sections,convTok,currentTools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react56.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":"free"),[view,drilledGroup]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react56.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react56.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_react56.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((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.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"&&currentTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&currentTools){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)"]}):$jsx("span",{fg:theme.info,children:" (click group to expand)"})]}),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,$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})})]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:wire.calls===0&&fill===0?"[no data]":cumulative?"[cumulative \u2014 not current fill]":wire.calls===0&&fill>0?"[live session]":"\u2191\u2193 nav \xB7 click a group to drill in",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:`Context \xB7 ${fmt2(fill)} / ${fmt2(ctxLen)} (${pct}%)`,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:[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,row2)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row2*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=row2*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)})},row2))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react58=__toESM(require_react_production(),1);init_hermes_analytics();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_react58.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost(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_react58.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_react58.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react58.useState(7),[data2,setData]=import_react58.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react58.useState(()=>cache3.get(days)?.byTool??null),[tick2,setTick]=import_react58.useState(0),gen=import_react58.useRef(0);import_react58.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick2]);let keys=useKeys();useKeyboard((key2)=>{if(!props.focused)return;if(keys.match("list.refresh",key2))return cache3.delete(days),setTick((n)=>n+1);if(key2.raw==="1")return setDays(1);if(key2.raw==="7")return setDays(7);if(key2.raw==="3")return setDays(30);if(key2.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react58.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost(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:$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:[$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:cost(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_react60=__toESM(require_react_production(),1);var SubTabBar=import_react60.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 & gallery"}],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"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Studio","Gallery"]},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},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},studio:{tab:4,sub:0},gallery:{tab:4,sub:1}};var SessionsGroup=import_react61.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[SESSIONS_TAB];import_react61.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} group \xB7 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})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react82=__toESM(require_react_production(),1);var import_react73=__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_react64=__toESM(require_react_production(),1);var import_react62=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react62.useState(""),[cursor,setCursor]=import_react62.useState(0),mode=import_react62.useRef("kb"),moved=import_react62.useRef(!1),sb=import_react62.useRef(null),theme=useTheme().theme,filtered=import_react62.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_react62.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_react62.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react62.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_react62.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((key2)=>{let onToggle=!filterable?()=>{let item=filtered[cursor];if(item)props.onSelect(item)}:void 0;if(handleListKey(keys,key2,{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)},onToggle}))return;if(props.onKey?.(key2))return});let idx=0,entries2=Array.from(groups.entries());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_react64.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react64.useRef(new Map),enabled2=import_react64.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react64.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react64.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react64.useCallback((val)=>{enabled2.current=val},[]),open2=import_react64.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((key2)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key2))return open2();for(let c of all())if(c.action&&keys.match(c.action,key2))return c.onSelect()});let value=import_react64.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");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){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{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);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react67=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.accept",key2))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_react67.useState(!1);useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.deny",key2))return props.done(null);if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.done(force);if(key2.name==="space"||key2.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_react69=__toESM(require_react_production(),1);import{existsSync as existsSync12,readFileSync as readFileSync4}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join9,basename as basename8,dirname as dirname5}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join9(home3(),".hermes");function root(){let hh=hermesHome(),parent2=dirname5(hh);return basename8(parent2)==="profiles"?dirname5(parent2):hh}function profileNameFrom(hh){let parent2=dirname5(hh);return basename8(parent2)==="profiles"?basename8(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync4(join9(root(),"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=readFileSync4(join9(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(),clean=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean(m2),clean(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:join9(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync4(join9(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 readFileSync4(join9(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join9(dir,"distribution.yaml");if(!existsSync12(path7))return null;let data2=(()=>{try{return $parse(readFileSync4(path7,"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 src=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join9(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:existsSync12(join9(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync12(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src(dir,dir.replace(home3()+"/","~/")),config:src(join9(dir,"config.yaml"),"config.yaml"),soul:src(join9(dir,"SOUL.md"),"SOUL.md"),env:src(join9(dir,".env"),".env"),distribution:src(join9(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync12(r))jobs.push(info("default",r,active,sticky));let pr=join9(r,"profiles");if(existsSync12(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join9(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(readFileSync4(join9(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=join9(dir,"state.db");if(existsSync12(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(join9(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=existsSync12(join9(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["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_react69.useState(""),[cloneIdx,setCloneIdx]=import_react69.useState(0),[alias,setAlias]=import_react69.useState(!0),[field,setField]=import_react69.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key2)=>{if(key2.name==="escape")return done(null);if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="return")return submit();if(field==="name"){if(key2.name==="backspace")return setName((n)=>n.slice(0,-1));if(key2.raw&&key2.raw.length===1&&/[a-z0-9_-]/.test(key2.raw))return setName((n)=>n+key2.raw);return}if(field==="clone"){if(key2.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key2.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key2.name==="space"||key2.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_react71=__toESM(require_react_production(),1);import{rmSync as rmSync2,mkdtempSync as mkdtempSync2}from"fs";import{join as join10}from"path";import{tmpdir as tmpdir2}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=mkdtempSync2(join10(tmpdir2(),"herm-dist-preview-")),cleanup=()=>{try{rmSync2(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{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 manifest=readDistributionManifest(tmp);if(!manifest){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,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react71.useState("");return useKeyboard((key2)=>{if(key2.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"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.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((key2)=>{if(keys.match("dialog.accept",key2)||keys.match("dialog.cancel",key2))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"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react71.useState(""),[alias,setAlias]=import_react71.useState(!1),[field,setField]=import_react71.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel();if(key2.name==="tab")return move(key2.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key2))return fire();if(field==="alias"&&(key2.name==="space"||key2.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=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(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,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react73.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react73.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_react73.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_react73.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_react73.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react73.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,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react73.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_react73.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react73.useState("profiles"),[pView,setPView]=import_react73.useState("list"),[profiles,setProfiles]=import_react73.useState([]),[deleg,setDeleg]=import_react73.useState(null),[liveMap,setLiveMap]=import_react73.useState(()=>new Map),[now,setNow]=import_react73.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react73.useState(0),[dSel,setDSel]=import_react73.useState(0),[err,setErr]=import_react73.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react73.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react73.useRef(void 0),[stats,setStats]=import_react73.useState(()=>new Map),[sticky,setSticky]=import_react73.useState(stickyDefault),loadProfiles=import_react73.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react73.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react73.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react73.useEffect(loadDeleg,[loadDeleg]),import_react73.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_react73.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_react73.useCallback((i)=>setPSel(i),[]),dHover=import_react73.useCallback((i)=>setDSel(i),[]),pDelete=import_react73.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
4108
+ `)){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_react56.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_react56.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_react56.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?.tools)return null;let tools=Object.entries(info.tools).flatMap(([group,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group.length})));if(tools.length===0)return null;return{source:makeSource("state.db","session.info"),tools}},Context=import_react56.memo(({messages=NO_MESSAGES,info,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"),recentSessions=useHome("recentSessions"),liveSessions=useHome("liveSessions"),[wire,setWire]=import_react56.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react56.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react56.useState(null),[selected,setSelected]=import_react56.useState(null),[drilled,setDrilled]=import_react56.useState(null);import_react56.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 session=recentSessions?.[0],ctxLen=info?.context_max??(config?.model?.context_length&&config.model.context_length>0?config.model.context_length:DEFAULT_CTX),lastPrompt=(session?Object.values(liveSessions??{}).find((ls)=>ls.session_id===session.id):void 0)?.last_prompt_tokens??0,fill=wire.calls>0?wire.input:lastPrompt>0?lastPrompt:session?.input_tokens??0,cumulative=wire.calls===0&&lastPrompt===0&&(session?.input_tokens??0)>0,output=wire.calls>0?wire.output:session?.output_tokens??0,pct=ctxLen>0?Math.round(fill/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_react56.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react56.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react56.useMemo(()=>toolsFromInfo(info)??toolsInfo,[info,toolsInfo]),top=import_react56.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,fill,sections,convTok,currentTools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react56.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":"free"),[view,drilledGroup]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react56.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react56.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_react56.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((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.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"&&currentTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&currentTools){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)"]}):$jsx("span",{fg:theme.info,children:" (click group to expand)"})]}),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,$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})})]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:wire.calls===0&&fill===0?"[no data]":cumulative?"[cumulative \u2014 not current fill]":wire.calls===0&&fill>0?"[live session]":"\u2191\u2193 nav \xB7 click a group to drill in",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:`Context \xB7 ${fmt2(fill)} / ${fmt2(ctxLen)} (${pct}%)`,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:[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,row2)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row2*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=row2*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)})},row2))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react58=__toESM(require_react_production(),1);init_hermes_analytics();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_react58.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost(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_react58.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_react58.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react58.useState(7),[data2,setData]=import_react58.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react58.useState(()=>cache3.get(days)?.byTool??null),[tick2,setTick]=import_react58.useState(0),gen=import_react58.useRef(0);import_react58.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick2]);let keys=useKeys();useKeyboard((key2)=>{if(!props.focused)return;if(keys.match("list.refresh",key2))return cache3.delete(days),setTick((n)=>n+1);if(key2.raw==="1")return setDays(1);if(key2.raw==="7")return setDays(7);if(key2.raw==="3")return setDays(30);if(key2.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react58.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost(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:$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:[$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:cost(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_react60=__toESM(require_react_production(),1);var SubTabBar=import_react60.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 & gallery"}],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"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Studio","Gallery"]},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},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},studio:{tab:4,sub:0},gallery:{tab:4,sub:1}};var SessionsGroup=import_react61.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[SESSIONS_TAB];import_react61.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} group \xB7 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})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react82=__toESM(require_react_production(),1);var import_react73=__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_react64=__toESM(require_react_production(),1);var import_react62=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react62.useState(""),[cursor,setCursor]=import_react62.useState(0),mode=import_react62.useRef("kb"),moved=import_react62.useRef(!1),sb=import_react62.useRef(null),theme=useTheme().theme,filtered=import_react62.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_react62.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_react62.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react62.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_react62.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((key2)=>{let onToggle=!filterable?()=>{let item=filtered[cursor];if(item)props.onSelect(item)}:void 0;if(handleListKey(keys,key2,{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)},onToggle}))return;if(props.onKey?.(key2))return});let idx=0,entries2=Array.from(groups.entries());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_react64.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react64.useRef(new Map),enabled2=import_react64.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react64.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react64.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react64.useCallback((val)=>{enabled2.current=val},[]),open2=import_react64.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((key2)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key2))return open2();for(let c of all())if(c.action&&keys.match(c.action,key2))return c.onSelect()});let value=import_react64.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");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){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{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);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react67=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.accept",key2))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_react67.useState(!1);useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.deny",key2))return props.done(null);if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.done(force);if(key2.name==="space"||key2.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_react69=__toESM(require_react_production(),1);import{existsSync as existsSync12,readFileSync as readFileSync4}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join9,basename as basename8,dirname as dirname5}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join9(home3(),".hermes");function root(){let hh=hermesHome(),parent2=dirname5(hh);return basename8(parent2)==="profiles"?dirname5(parent2):hh}function profileNameFrom(hh){let parent2=dirname5(hh);return basename8(parent2)==="profiles"?basename8(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync4(join9(root(),"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=readFileSync4(join9(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(),clean=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean(m2),clean(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:join9(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync4(join9(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 readFileSync4(join9(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join9(dir,"distribution.yaml");if(!existsSync12(path7))return null;let data2=(()=>{try{return $parse(readFileSync4(path7,"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 src=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join9(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:existsSync12(join9(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync12(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src(dir,dir.replace(home3()+"/","~/")),config:src(join9(dir,"config.yaml"),"config.yaml"),soul:src(join9(dir,"SOUL.md"),"SOUL.md"),env:src(join9(dir,".env"),".env"),distribution:src(join9(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync12(r))jobs.push(info("default",r,active,sticky));let pr=join9(r,"profiles");if(existsSync12(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join9(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(readFileSync4(join9(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=join9(dir,"state.db");if(existsSync12(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(join9(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=existsSync12(join9(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["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_react69.useState(""),[cloneIdx,setCloneIdx]=import_react69.useState(0),[alias,setAlias]=import_react69.useState(!0),[field,setField]=import_react69.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key2)=>{if(key2.name==="escape")return done(null);if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="return")return submit();if(field==="name"){if(key2.name==="backspace")return setName((n)=>n.slice(0,-1));if(key2.raw&&key2.raw.length===1&&/[a-z0-9_-]/.test(key2.raw))return setName((n)=>n+key2.raw);return}if(field==="clone"){if(key2.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key2.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key2.name==="space"||key2.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_react71=__toESM(require_react_production(),1);import{rmSync as rmSync2,mkdtempSync as mkdtempSync2}from"fs";import{join as join10}from"path";import{tmpdir as tmpdir2}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=mkdtempSync2(join10(tmpdir2(),"herm-dist-preview-")),cleanup=()=>{try{rmSync2(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{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 manifest=readDistributionManifest(tmp);if(!manifest){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,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react71.useState("");return useKeyboard((key2)=>{if(key2.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"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.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((key2)=>{if(keys.match("dialog.accept",key2)||keys.match("dialog.cancel",key2))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"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react71.useState(""),[alias,setAlias]=import_react71.useState(!1),[field,setField]=import_react71.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel();if(key2.name==="tab")return move(key2.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key2))return fire();if(field==="alias"&&(key2.name==="space"||key2.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=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(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,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react73.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react73.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_react73.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_react73.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_react73.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react73.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,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react73.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_react73.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react73.useState("profiles"),[pView,setPView]=import_react73.useState("list"),[profiles,setProfiles]=import_react73.useState([]),[deleg,setDeleg]=import_react73.useState(null),[liveMap,setLiveMap]=import_react73.useState(()=>new Map),[now,setNow]=import_react73.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react73.useState(0),[dSel,setDSel]=import_react73.useState(0),[err,setErr]=import_react73.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react73.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react73.useRef(void 0),[stats,setStats]=import_react73.useState(()=>new Map),[sticky,setSticky]=import_react73.useState(stickyDefault),loadProfiles=import_react73.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react73.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react73.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react73.useEffect(loadDeleg,[loadDeleg]),import_react73.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_react73.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_react73.useCallback((i)=>setPSel(i),[]),dHover=import_react73.useCallback((i)=>setDSel(i),[]),pDelete=import_react73.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
4109
4109
 
4110
4110
  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_react73.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_react73.useCallback((p,force)=>{let cmd2=`hermes profile update ${p.name} -y${force?" --force-config":""}`;toast.show({variant:"info",message:`Updating '${p.name}'\u2026`}),sh(cmd2).then(()=>{if(toast.show({variant:"success",message:`Updated '${p.name}'`}),p.is_active&&props.onSwitchProfile){props.onSwitchProfile(p.path,p.name);return}loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,toast,loadProfiles,props.onSwitchProfile]),pEnter=import_react73.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_react73.useCallback(async(i)=>{let r=live.current.active[i];if(!r)return;if(!await openConfirm(dialog,{title:"Interrupt subagent?",body:`${trunc5(r.goal,120)}
4111
4111
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herm-tui",
3
- "version": "1.8.2-dev.3",
3
+ "version": "1.8.2-dev.4",
4
4
  "description": "A modern TUI for Hermes Agent",
5
5
  "license": "MIT",
6
6
  "repository": {