herm-tui 1.6.0-dev.8 → 1.6.0-dev.9

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 +5 -5
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -4081,7 +4081,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
4081
4081
  `+tail;else buf.push(tail)}return flush(),out}var MediaChip=import_react34.memo((props)=>{let theme=useTheme().theme,[hover,setHover]=import_react34.useState(!1),kind=classify(props.path),badge={img:theme.accent,audio:theme.warning,video:theme.info,url:theme.primary,file:theme.secondary}[kind],click=props.onMouseDown??((e)=>{e.stopPropagation(),openFile(props.path)});return $jsx("box",{flexDirection:"row",height:1,onMouseDown:click,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:$jsxs("text",{children:[$jsxs("span",{bg:badge,fg:theme.background,children:[" ",kind," "]}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.text,attributes:hover?TextAttributes.UNDERLINE:TextAttributes.NONE,children:[" ",basename5(props.path)," "]})]})})});var import_react36=__toESM(require_react_production(),1);var import_react35=__toESM(require_react_production(),1);var Ctx3=import_react35.createContext(null),DEFAULT_DURATION=3000,ToastProvider=({children})=>{let[items,setItems]=import_react35.useState([]),counter=import_react35.useRef(0),timers=import_react35.useRef(new Map);import_react35.useEffect(()=>()=>{for(let t2 of timers.current.values())clearTimeout(t2)},[]);let show=import_react35.useCallback((opts)=>{let id=++counter.current;setItems((prev)=>[...prev,{...opts,id}]);let dur2=opts.duration??DEFAULT_DURATION;timers.current.set(id,setTimeout(()=>{timers.current.delete(id),setItems((prev)=>prev.filter((t2)=>t2.id!==id))},dur2))},[]),error=import_react35.useCallback((err)=>{show({variant:"error",title:"Error",message:err.message})},[show]),value=import_react35.useMemo(()=>({show,error}),[show,error]);return $jsxs(Ctx3.Provider,{value,children:[children,items.length>0?$jsx(ToastOverlay,{items}):null]})},ToastOverlay=({items})=>{let theme=useTheme().theme,color=(variant)=>{switch(variant){case"error":return theme.error;case"warning":return theme.warning;case"success":return theme.success;default:return theme.info}};return $jsx("box",{position:"absolute",top:2,right:2,flexDirection:"column",gap:1,zIndex:200,maxWidth:60,children:items.map((item)=>$jsxs("box",{backgroundColor:theme.backgroundPanel,border:["left"],borderStyle:"single",borderColor:color(item.variant),paddingLeft:1,paddingRight:1,flexDirection:"column",children:[item.title?$jsx("text",{fg:theme.text,children:$jsx("strong",{children:item.title})}):null,$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:item.message}),item.action?$jsx("box",{height:1,marginTop:0,onMouseDown:item.action.run,children:$jsx("text",{fg:color(item.variant),children:$jsx("u",{children:item.action.label})})}):null]},item.id))})},useToast=makeUse(Ctx3,"useToast");var FILETYPE={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",rb:"ruby",rs:"rust",sh:"bash",shell:"bash",yml:"yaml",md:"markdown"},CodeBlock=import_react36.memo((props)=>{let{theme,syntaxStyle}=useTheme(),toast=useToast(),[hover,setHover]=import_react36.useState(!1),ft=props.lang?FILETYPE[props.lang.toLowerCase()]??props.lang.toLowerCase():void 0,lines2=props.code.split(`
4082
4082
  `).length,onCopy=()=>{copy(props.code),toast.show({variant:"success",message:`Copied ${lines2} line${lines2===1?"":"s"}`})};return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsxs("box",{flexDirection:"row",height:1,backgroundColor:theme.backgroundElement,onMouseDown:onCopy,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:[$jsx("box",{flexGrow:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:props.lang||"text"})}),$jsx("box",{paddingRight:1,children:$jsx("text",{fg:hover?theme.accent:theme.textMuted,children:hover?"\u29C9 copy":`${lines2} ln`})})]}),$jsx("box",{paddingX:1,paddingY:ft?0:1,children:ft?$jsx("code",{content:props.code,filetype:ft,syntaxStyle,fg:theme.text,wrapMode:"none",streaming:props.streaming}):$jsx("text",{fg:theme.text,children:props.code})})]})});var import_react37=__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_react37.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react37.useState(0),done=import_react37.useRef(!1),send=(c)=>{if(done.current)return;done.current=!0,gw.request("approval.respond",{choice:c}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")};return import_react37.useImperativeHandle(ref,()=>({masked:!1,feed:(key2)=>{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]),$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]}),$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("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 esc deny"})})]})]})}),Clarify=import_react37.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react37.useState(0),[typing,setTyping]=import_react37.useState(choices.length===0),[custom,setCustom]=import_react37.useState(""),done=import_react37.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_react37.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_react37.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react37.useState(""),done=import_react37.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react37.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_react37.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_react37.memo(import_react37.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 pending(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_react38=__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(`
4083
4083
  `).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_react38.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react38.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react38.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_react39=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react39.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react39.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react39.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 trunc2=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",InlineDiff=import_react40.memo(({tool})=>{let theme=useTheme().theme,[open2,setOpen]=import_react40.useState(!1),diff=tool.diff??(isDiff(tool.result)?tool.result:void 0);if(!diff)return null;let lines2=diff.split(`
4084
- `),add=lines2.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines2.filter((l)=>/^-(?!--)/.test(l)).length;return $jsxs("box",{flexDirection:"column",marginTop:1,onMouseDown:(e)=>{e.stopPropagation(),setOpen((o)=>!o)},children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:open2?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:theme.text,children:trunc2(tool.preview??tool.name,50)}),$jsx("span",{fg:theme.textMuted,children:" "}),$jsxs("span",{fg:theme.success,children:["+",add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",del]})]})}),open2?$jsx("box",{marginTop:1,children:$jsx(DiffBlock,{text:diff})}):null]})});function useClick(fn){let at=import_react40.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_react40.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_react40.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_react40.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_react40.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react40.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),segs=import_react40.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_react40.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react40.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_react40.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:trunc2(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.map((t2)=>$jsx(InlineDiff,{tool:t2},t2.id||t2.name)),err?$jsx(ErrorBlock,{text:message.error}):null]})})});var import_react41=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react41.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react41.useState(0);return import_react41.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_react42.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react42.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_react43.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_react60=__toESM(require_react_production(),1);var import_react52=__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_react44=__toESM(require_react_production(),1);var Ctx5=import_react44.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),[stack,setStack]=import_react44.useState([]),gate=import_react44.useRef(!1),gen=import_react44.useRef(0),prev=import_react44.useRef(null),refocus=import_react44.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_react44.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_react44.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_react44.useCallback(()=>gate.current,[]),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_react44.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Overlay,{entry:top,onClose:clear}):null]})},Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react44.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,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,children:props.children})]})};var import_react46=__toESM(require_react_production(),1);var HintBar=import_react46.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_react47=__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_react47.useRef(null),node=import_react47.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react47.useState(!1);import_react47.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_react48=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react48.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 import_react50=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react50.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",trunc4=(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_react51=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync10,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}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(`
4084
+ `),add=lines2.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines2.filter((l)=>/^-(?!--)/.test(l)).length;return $jsxs("box",{flexDirection:"column",marginTop:1,onMouseDown:(e)=>{e.stopPropagation(),setOpen((o)=>!o)},children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:open2?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:theme.text,children:trunc2(tool.preview??tool.name,50)}),$jsx("span",{fg:theme.textMuted,children:" "}),$jsxs("span",{fg:theme.success,children:["+",add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",del]})]})}),open2?$jsx("box",{marginTop:1,children:$jsx(DiffBlock,{text:diff})}):null]})});function useClick(fn){let at=import_react40.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_react40.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_react40.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_react40.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_react40.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react40.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),segs=import_react40.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_react40.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react40.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_react40.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:trunc2(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.map((t2)=>$jsx(InlineDiff,{tool:t2},t2.id||t2.name)),err?$jsx(ErrorBlock,{text:message.error}):null]})})});var import_react41=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react41.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react41.useState(0);return import_react41.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_react42.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react42.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_react43.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_react60=__toESM(require_react_production(),1);var import_react52=__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_react44=__toESM(require_react_production(),1);var Ctx5=import_react44.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),[stack,setStack]=import_react44.useState([]),gate=import_react44.useRef(!1),gen=import_react44.useRef(0),prev=import_react44.useRef(null),refocus=import_react44.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_react44.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_react44.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_react44.useCallback(()=>gate.current,[]),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_react44.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Overlay,{entry:top,onClose:clear}):null]})},Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react44.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_react46=__toESM(require_react_production(),1);var HintBar=import_react46.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_react47=__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_react47.useRef(null),node=import_react47.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react47.useState(!1);import_react47.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_react48=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react48.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 import_react50=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react50.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",trunc4=(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_react51=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync10,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}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(`
4085
4085
  ---`,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(`
4086
4086
  `).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 text2=await Bun.file(hermesPath("sessions/sessions.json")).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 glob=new Bun.Glob("session_*.json"),latestPath="",latestTime=0;for await(let path7 of glob.scan({cwd:hermesPath("sessions")})){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(`
4087
4087
  `),text2=lines2.length>tailLines?`\u2026(${lines2.length-tailLines} earlier lines)
@@ -4102,7 +4102,7 @@ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid)
4102
4102
  `,skE);while(end<text2.length&&end>=0){let nl=text2.indexOf(`
4103
4103
  `,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(`
4104
4104
  `,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_react54=__toESM(require_react_production(),1);var FileLink=import_react54.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react54.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_react55.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_react55.memo(({seg,theme,label,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:label})}),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_react55.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line2 of sec.text.split(`
4105
- `)){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_react55.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label=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"})," ",label," \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_react55.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_react55.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([]),Context=import_react55.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_react55.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react55.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react55.useState(null),[selected,setSelected]=import_react55.useState(null),[drilled,setDrilled]=import_react55.useState(null);import_react55.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_react55.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react55.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),top=import_react55.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:toolsInfo?.tools??[]}),[ctxLen,fill,sections,convTok,toolsInfo?.tools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react55.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_react55.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react55.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_react55.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"&&toolsInfo){let{system}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&toolsInfo){let{mcp}=classifyTools(toolsInfo.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_react57=__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_react57.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_react57.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:trunc4(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_react57.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react57.useState(7),[data2,setData]=import_react57.useState(()=>cache2.get(days)??null),[tools,setTools]=import_react57.useState(()=>cache2.get(days)?.byTool??null),[tick2,setTick]=import_react57.useState(0),gen=import_react57.useRef(0);import_react57.useEffect(()=>{let hit=cache2.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;cache2.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 cache2.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_react57.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:trunc4(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_react59=__toESM(require_react_production(),1);var SubTabBar=import_react59.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},eikon:{tab:4,sub:0},studio:{tab:4,sub:0},eikons:{tab:4,sub:1},gallery:{tab:4,sub:1}};var SessionsGroup=import_react60.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[SESSIONS_TAB];import_react60.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,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,flexDirection:"column",children:children2}):null;var import_react81=__toESM(require_react_production(),1);var import_react72=__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 label=(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,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react63=__toESM(require_react_production(),1);var import_react61=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react61.useState(""),[cursor,setCursor]=import_react61.useState(0),mode=import_react61.useRef("kb"),sb=import_react61.useRef(null),theme=useTheme().theme,filtered=import_react61.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_react61.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]);import_react61.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]);let rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react61.useEffect(()=>{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",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",setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")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_react63.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react63.useRef(new Map),[,setRevision]=import_react63.useState(0),enabled2=import_react63.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react63.useCallback(()=>{let result=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>result.push(c))),result},[]),register=import_react63.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),setRevision((r)=>r+1),()=>{registry.current.delete(id),setRevision((r)=>r+1)}},[]),setEnabled=import_react63.useCallback((val)=>{enabled2.current=val},[]),open2=import_react63.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_react63.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:trunc4(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 ${trunc4(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_react66=__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_react66.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_react68=__toESM(require_react_production(),1);import{existsSync as existsSync11,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(),parent=dirname5(hh);return basename8(parent)==="profiles"?dirname5(parent):hh}function profileNameFrom(hh){let parent=dirname5(hh);return basename8(parent)==="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(!existsSync11(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,label)=>({file,relative:file.replace(home3()+"/","~/"),label});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:existsSync11(join9(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync11(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(existsSync11(r))jobs.push(info("default",r,active,sticky));let pr=join9(r,"profiles");if(existsSync11(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(existsSync11(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=existsSync11(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_react68.useState(""),[cloneIdx,setCloneIdx]=import_react68.useState(0),[alias,setAlias]=import_react68.useState(!0),[field,setField]=import_react68.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_react70=__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_react70.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_react70.useState(""),[alias,setAlias]=import_react70.useState(!1),[field,setField]=import_react70.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_react72.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react72.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_react72.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_react72.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_react72.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react72.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:trunc4(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_react72.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:trunc4(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?trunc4(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react72.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react72.useState("profiles"),[pView,setPView]=import_react72.useState("list"),[profiles,setProfiles]=import_react72.useState([]),[deleg,setDeleg]=import_react72.useState(null),[liveMap,setLiveMap]=import_react72.useState(()=>new Map),[now,setNow]=import_react72.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react72.useState(0),[dSel,setDSel]=import_react72.useState(0),[err,setErr]=import_react72.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_react72.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react72.useRef(void 0),[stats,setStats]=import_react72.useState(()=>new Map),[sticky,setSticky]=import_react72.useState(stickyDefault),loadProfiles=import_react72.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react72.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react72.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_react72.useEffect(loadDeleg,[loadDeleg]),import_react72.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_react72.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_react72.useCallback((i)=>setPSel(i),[]),dHover=import_react72.useCallback((i)=>setDSel(i),[]),pDelete=import_react72.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
4105
+ `)){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_react55.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label=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"})," ",label," \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_react55.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_react55.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([]),Context=import_react55.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_react55.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react55.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react55.useState(null),[selected,setSelected]=import_react55.useState(null),[drilled,setDrilled]=import_react55.useState(null);import_react55.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_react55.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react55.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),top=import_react55.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:toolsInfo?.tools??[]}),[ctxLen,fill,sections,convTok,toolsInfo?.tools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react55.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_react55.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react55.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_react55.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"&&toolsInfo){let{system}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&toolsInfo){let{mcp}=classifyTools(toolsInfo.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_react57=__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_react57.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_react57.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:trunc4(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_react57.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react57.useState(7),[data2,setData]=import_react57.useState(()=>cache2.get(days)??null),[tools,setTools]=import_react57.useState(()=>cache2.get(days)?.byTool??null),[tick2,setTick]=import_react57.useState(0),gen=import_react57.useRef(0);import_react57.useEffect(()=>{let hit=cache2.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;cache2.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 cache2.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_react57.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:trunc4(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_react59=__toESM(require_react_production(),1);var SubTabBar=import_react59.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},eikon:{tab:4,sub:0},studio:{tab:4,sub:0},eikons:{tab:4,sub:1},gallery:{tab:4,sub:1}};var SessionsGroup=import_react60.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[SESSIONS_TAB];import_react60.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,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_react81=__toESM(require_react_production(),1);var import_react72=__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 label=(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,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react63=__toESM(require_react_production(),1);var import_react61=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react61.useState(""),[cursor,setCursor]=import_react61.useState(0),mode=import_react61.useRef("kb"),sb=import_react61.useRef(null),theme=useTheme().theme,filtered=import_react61.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_react61.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]);import_react61.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]);let rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react61.useEffect(()=>{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",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",setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")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_react63.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react63.useRef(new Map),[,setRevision]=import_react63.useState(0),enabled2=import_react63.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react63.useCallback(()=>{let result=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>result.push(c))),result},[]),register=import_react63.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),setRevision((r)=>r+1),()=>{registry.current.delete(id),setRevision((r)=>r+1)}},[]),setEnabled=import_react63.useCallback((val)=>{enabled2.current=val},[]),open2=import_react63.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_react63.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:trunc4(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 ${trunc4(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_react66=__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_react66.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_react68=__toESM(require_react_production(),1);import{existsSync as existsSync11,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(),parent=dirname5(hh);return basename8(parent)==="profiles"?dirname5(parent):hh}function profileNameFrom(hh){let parent=dirname5(hh);return basename8(parent)==="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(!existsSync11(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,label)=>({file,relative:file.replace(home3()+"/","~/"),label});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:existsSync11(join9(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync11(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(existsSync11(r))jobs.push(info("default",r,active,sticky));let pr=join9(r,"profiles");if(existsSync11(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(existsSync11(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=existsSync11(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_react68.useState(""),[cloneIdx,setCloneIdx]=import_react68.useState(0),[alias,setAlias]=import_react68.useState(!0),[field,setField]=import_react68.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_react70=__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_react70.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_react70.useState(""),[alias,setAlias]=import_react70.useState(!1),[field,setField]=import_react70.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_react72.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react72.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_react72.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_react72.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_react72.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react72.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:trunc4(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_react72.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:trunc4(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?trunc4(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react72.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react72.useState("profiles"),[pView,setPView]=import_react72.useState("list"),[profiles,setProfiles]=import_react72.useState([]),[deleg,setDeleg]=import_react72.useState(null),[liveMap,setLiveMap]=import_react72.useState(()=>new Map),[now,setNow]=import_react72.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react72.useState(0),[dSel,setDSel]=import_react72.useState(0),[err,setErr]=import_react72.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_react72.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react72.useRef(void 0),[stats,setStats]=import_react72.useState(()=>new Map),[sticky,setSticky]=import_react72.useState(stickyDefault),loadProfiles=import_react72.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react72.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react72.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_react72.useEffect(loadDeleg,[loadDeleg]),import_react72.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_react72.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_react72.useCallback((i)=>setPSel(i),[]),dHover=import_react72.useCallback((i)=>setDSel(i),[]),pDelete=import_react72.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
4106
4106
 
4107
4107
  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_react72.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_react72.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_react72.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:trunc4(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_react72.useCallback(async(i)=>{let r=live.current.active[i];if(!r)return;if(!await openConfirm(dialog,{title:"Interrupt subagent?",body:`${trunc4(r.goal,120)}
4108
4108
 
@@ -4119,15 +4119,15 @@ The child returns whatever partial result it has so far.`,yes:"interrupt",danger
4119
4119
  `)[0].slice(0,200)}`}):null]},r.id)})]}):null,d2.events.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Events (${d2.events.length})`})}),d2.events.map((e)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:`${ago(e.created_at).padEnd(10)} `}),$jsx("span",{fg:theme.text,children:e.kind}),e.payload?$jsx("span",{fg:theme.textMuted,children:` ${JSON.stringify(e.payload)}`}):null]})},e.id))]}):null,d2.comments.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Comments (${d2.comments.length})`})}),d2.comments.map((c,i)=>$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${c.author} \xB7 ${ago(c.at)}`})}),$jsx("text",{wrapMode:"word",children:c.body})]},i))]}):null,p.on&&cur==="comment"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.accent,children:"Enter add comment"})}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.on?"Tab/\u2191\u2193 field Enter edit Esc grid a assign c comment l log":"Tab into pane a assign c comment u unblock d archive l log N child"})})]})}),Kanban=import_react79.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),keys=useKeys(),[boards,setBoards]=import_react79.useState(listBoards),[data2,setData]=import_react79.useState(()=>new Map(boards.map((b2)=>[b2.slug,boardOf(b2.slug)]))),[diags,setDiags]=import_react79.useState(()=>new Map),[masks,setMasks]=import_react79.useState(()=>maskFromPrefs(load().kanban?.masks)),[open2,setOpen]=import_react79.useState(()=>{let saved=load().kanban?.open;if(saved)return new Set(saved);let init=currentBoard();return new Set(listBoards().filter((b2)=>b2.slug===init||[...boardOf(b2.slug).values()].some((v2)=>v2.length>0)).map((b2)=>b2.slug))}),[at,setAt]=import_react79.useState(currentBoard),[tier,setTier]=import_react79.useState("grid"),[col,setCol]=import_react79.useState(0),[row2,setRow]=import_react79.useState(0),[chip,setChip]=import_react79.useState(0),[paneSel,setPaneSel]=import_react79.useState(0),[pane,setPane]=import_react79.useState(null),outer=import_react79.useRef(null),load3=import_react79.useCallback(()=>{let bs=listBoards();setBoards(bs),setData(new Map(bs.map((b2)=>[b2.slug,boardOf(b2.slug)]))),setPane((p)=>p?.kind==="detail"?((d2)=>d2?{...p,d:d2}:null)(detailOf(p.slug,p.d.id)):p),Promise.all(bs.map((b2)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(b2.slug)} diagnostics --json`}).then((r)=>r.code===0?parseDiagnostics(r.stdout):[]).catch(()=>[]).then((rows3)=>[b2.slug,indexDiags(rows3)]))).then((pairs)=>setDiags(new Map(pairs)))},[gw]);import_react79.useEffect(load3,[load3]),import_react79.useEffect(()=>{persist(masks,open2)},[masks,open2]);let maskOf=(s)=>masks.get(s)??EMPTY2,wide=dims.width>=160,maxH=Math.max(8,dims.height-16),sections=import_react79.useMemo(()=>{let built=boards.map((b2)=>{let d2=data2.get(b2.slug)??new Map,flat=STATUSES.flatMap((s)=>d2.get(s)??[]),total=flat.length,who=[...new Set(flat.map((t2)=>t2.assignee).filter((v2)=>!!v2))].sort(),pri=[...new Set(flat.map((t2)=>t2.priority).filter((n)=>n>0))].sort((a,z2)=>z2-a),chips=[...who.map((v2)=>({kind:"who",v:v2})),...pri.map((v2)=>({kind:"pri",v:v2})),...STATUSES.map((v2)=>({kind:"status",v:v2}))],m2=maskOf(b2.slug),cols3=STATUSES.filter((s)=>admits(m2.status,s)).map((s)=>({status:s,tasks:(d2.get(s)??[]).filter((t2)=>pass(t2,m2))})).filter((c)=>wide||c.tasks.length>0),shown=cols3.reduce((a,c)=>a+c.tasks.length,0),tall=cols3.reduce((a,c)=>Math.max(a,c.tasks.length),0);return{board:b2,cols:cols3,chips,total,shown,running:d2.get("running")?.length??0,cap:Math.min(maxH,Math.max(5,3+2*tall))}});return[...built.filter((s)=>s.total>0),...built.filter((s)=>s.total===0)]},[boards,data2,masks,wide,maxH]),idx=sections.findIndex((s)=>s.board.slug===at),sec3=sections[idx]??sections[0],cols2=sec3?.cols??[],clampCol=Math.min(col,Math.max(0,cols2.length-1)),cur=cols2[clampCol],task=tier==="grid"||tier==="pane"?cur?.tasks[Math.min(row2,Math.max(0,(cur?.tasks.length??1)-1))]:void 0,grand=sections.reduce((a,s)=>a+s.total,0),running2=sections.reduce((a,s)=>a+s.running,0);import_react79.useEffect(()=>{if(pane?.kind!=="detail")return;if(tier!=="grid"&&tier!=="pane"){setPane(null);return}if(!task){setPane(null);return}if(pane.slug===at&&pane.d.id===task.id)return;let d2=detailOf(at,task.id);setPane(d2?{kind:"detail",slug:at,d:d2}:null),setPaneSel(0)},[task?.id,at,tier]),import_react79.useEffect(()=>{if(!props.focused||running2===0)return;let t2=setInterval(load3,3000);return()=>clearInterval(t2)},[props.focused,running2,load3]),import_react79.useEffect(()=>{outer.current?.scrollChildIntoView(`kb-sec-${at}`)},[at,open2]);let sh=import_react79.useCallback((argv,ok)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(at)} ${argv}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());if(ok)toast.show({variant:"success",message:ok});return resetKanban(),load3(),r.stdout}).catch((e)=>void toast.show({variant:"error",message:trunc4(e.message,120)})),[gw,toast,load3,at]),patchDirect=import_react79.useCallback((id,p,ok)=>{try{if(!patchTask(at,id,p))return void toast.show({variant:"error",message:`no such task: ${id}`});toast.show({variant:"success",message:ok}),load3()}catch(e){toast.show({variant:"error",message:trunc4(e.message,120)})}},[at,toast,load3]),enterTop=(s)=>{setAt(s.board.slug),setTier("head"),setChip(0),setRow(0)},enterBottom=(s)=>{if(setAt(s.board.slug),setChip(Math.max(0,s.chips.length-1)),open2.has(s.board.slug)&&s.shown>0){let nc=Math.min(col,Math.max(0,s.cols.length-1));setTier("grid"),setCol(nc),setRow(Math.max(0,(s.cols[nc]?.tasks.length??1)-1));return}if(open2.has(s.board.slug)){setTier("filter");return}setTier("head")},stepBoard=(d2)=>{let n=idx+d2;return n<0||n>=sections.length?null:sections[n]},goBoard=import_react79.useCallback((d2)=>{let n=(idx+d2+sections.length)%sections.length,s=sections[n];setAt(s.board.slug),setTier("head"),setCol(0),setRow(0),setChip(0),setOpen((o)=>o.has(s.board.slug)?o:new Set(o).add(s.board.slug))},[idx,sections]),flip=import_react79.useCallback((c)=>setMasks((m2)=>{let cur2=m2.get(at)??EMPTY2,who=new Map(cur2.who),pri=new Map(cur2.pri),status=new Map(cur2.status),g=c.kind==="who"?who:c.kind==="pri"?pri:status,next2=cycle(g.get(c.v)??"off");next2==="off"?g.delete(c.v):g.set(c.v,next2);let out=new Map(m2);return out.set(at,{who,pri,status}),setRow(0),out}),[at]),toggle=import_react79.useCallback((s)=>setOpen((o)=>{let n=new Set(o);return n.has(s)?n.delete(s):n.add(s),n}),[]),newBoard=import_react79.useCallback(()=>openTextPrompt(dialog,{title:"New board",label:"Slug (a-z, 0-9, -_)"}).then((v2)=>{if(!v2)return;return gw.request("shell.exec",{command:`hermes kanban boards create ${q3(v2)}`}).then((r)=>r.code===0?(toast.show({variant:"success",message:`Board '${v2}' created`}),resetKanban(),load3(),setAt(v2),setTier("head")):Promise.reject(Error((r.stderr||r.stdout).trim()))).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)}))}),[dialog,gw,toast,load3]),live=import_react79.useRef({task,at,sec:sec3});live.current={task,at,sec:sec3};let create=import_react79.useCallback((parent)=>openCreateTask(dialog,{assignees:assignees(live.current.at),parent:parent?{id:parent.id,title:parent.title}:void 0}).then((d2)=>{if(!d2)return;let ws=d2.workspace.kind==="scratch"?"":d2.workspace.kind==="worktree"?"--workspace worktree":`--workspace ${q3(`dir:${d2.workspace.path}`)}`,flags=[d2.assignee?`--assignee ${q3(d2.assignee)}`:"",d2.body?`--body ${q3(d2.body)}`:"",d2.priority?`--priority ${d2.priority}`:"",d2.parent?`--parent ${q3(d2.parent)}`:"",d2.triage?"--triage":"",d2.tenant?`--tenant ${q3(d2.tenant)}`:"",ws,d2.maxRuntime?`--max-runtime ${q3(d2.maxRuntime)}`:"",...d2.skills.map((s)=>`--skill ${q3(s)}`)].filter(Boolean).join(" ");return sh(`create ${q3(d2.title)} ${flags}`.trim(),`Created${d2.triage?" (triage)":""}${d2.assignee?` \u2192 ${d2.assignee}`:""}`)}),[dialog,sh]),assign=import_react79.useCallback((t2)=>{let opts=[{title:"(unassigned)",value:"none"},...assignees(live.current.at).map((n)=>({title:n,value:n}))];dialog.replace($jsx(DialogSelect,{title:`Assign ${t2.id}`,options:opts,current:t2.assignee??"none",placeholder:"Search profiles\u2026",onSelect:(o)=>{dialog.clear(),sh(`assign ${q3(t2.id)} ${q3(o.value)}`,o.value==="none"?`Unassigned ${t2.id}`:`${t2.id} \u2192 ${o.value}`)}}))},[dialog,sh]),comment=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:`Comment on ${t2.id}`,label:t2.title}).then((v2)=>v2&&sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`,"Comment added")),[dialog,sh]),unblock=import_react79.useCallback((t2)=>{if(t2.status!=="blocked")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not blocked`});return openTextPrompt(dialog,{title:`Unblock ${t2.id}`,label:"Answer (posted as comment, then task \u2192 ready)"}).then((v2)=>{if(v2)return sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`)}).then(()=>sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`))},[dialog,sh,toast]),archive=import_react79.useCallback((t2)=>openConfirm(dialog,{title:"Archive task?",danger:!0,yes:"archive",body:`${t2.id} \xB7 ${trunc4(t2.title,60)}
4120
4120
 
4121
4121
  Moves to 'archived' and ends any open run. Children stay; their dependency on this task is treated as satisfied.`}).then((ok)=>{if(ok)sh(`archive ${q3(t2.id)}`,`Archived ${t2.id}`)}),[dialog,sh]),parseSpecify=(out)=>out.split(`
4122
- `).flatMap((l)=>l.trim()?[JSON.parse(l)]:[]),specify=import_react79.useCallback((t2)=>{if(t2.status!=="triage")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not triage`});return sh(`specify ${q3(t2.id)} --json`).then((out)=>{if(out==null)return;let r=parseSpecify(out)[0];if(!r)return;if(!r.ok)return void toast.show({variant:"error",message:`specify ${r.task_id}: ${trunc4(r.reason??"failed",100)}`});toast.show({variant:"success",message:r.new_title?`Specified ${r.task_id} \u2192 ${trunc4(r.new_title,60)}`:`Specified ${r.task_id} \u2192 todo`})})},[sh,toast]),specifyAll=import_react79.useCallback(()=>{let triage=live.current.sec?.cols.find((c)=>c.status==="triage")?.tasks.length??0;if(triage===0)return void toast.show({variant:"info",message:`No 'triage' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Specify all \xB7 ${live.current.at}`,body:`${triage} task${triage===1?"":"s"} in 'triage'. Auxiliary LLM expands each body and promotes to todo.`,yes:"specify"}).then((go)=>{if(!go)return;return sh("specify --all --json").then((out)=>{if(out==null)return;let rows3=parseSpecify(out),ok=rows3.filter((r)=>r.ok).length,bad=rows3.length-ok;toast.show({variant:ok===0&&bad>0?"error":"success",message:`Specified ${ok}/${rows3.length}${bad?` (${bad} failed)`:""}`})})})},[dialog,sh,toast]),dispatch=import_react79.useCallback(()=>{let ready=live.current.sec?.cols.find((c)=>c.status==="ready")?.tasks.length??0;if(ready===0)return void toast.show({variant:"info",message:`No 'ready' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Dispatch \xB7 ${live.current.at}`,body:`${ready} task${ready===1?"":"s"} in 'ready'. Spawns one worker per task (one pass).`,yes:"dispatch"}).then((ok)=>{if(ok)sh("dispatch --json",`Dispatched (${ready} ready)`)})},[dialog,sh,toast]),showLog=import_react79.useCallback((t2)=>{let s=live.current.at,text2=tailLogOf(s,t2.id);if(text2==null)return void toast.show({variant:"info",message:`No worker log for ${t2.id}`});setPane({kind:"log",slug:s,id:t2.id,text:text2})},[toast]),editTitle=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit title",label:t2.id,initial:t2.title}).then((v2)=>v2!==null&&v2!==void 0&&patchDirect(t2.id,{title:v2},`Updated ${t2.id}`)),[dialog,patchDirect]),editBody=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit body",label:t2.id,initial:t2.body??""}).then((v2)=>{if(v2===null||v2===void 0)return;patchDirect(t2.id,{body:v2},`Updated ${t2.id}`)}),[dialog,patchDirect]),editPriority=import_react79.useCallback((t2)=>{let opts=Array.from({length:10},(_2,i)=>({title:i===0?"P0 (none)":`P${i}`,value:String(i)}));dialog.replace($jsx(DialogSelect,{title:`Priority for ${t2.id}`,options:opts,current:String(t2.priority),filterable:!1,onSelect:(o)=>{dialog.clear(),patchDirect(t2.id,{priority:Number(o.value)},`${t2.id} \u2192 P${o.value}`)}}))},[dialog,patchDirect]),editResult=import_react79.useCallback((t2)=>{if(t2.status!=="done")return void toast.show({variant:"info",message:`${t2.id} is not done`});return openTextPrompt(dialog,{title:"Edit result",label:t2.id,initial:t2.result??""}).then((v2)=>{if(v2==null)return;sh(`edit ${q3(t2.id)} --result ${q3(v2)}`,`Updated ${t2.id} result`)})},[dialog,sh,toast]),editStatus=import_react79.useCallback((t2)=>{let opts=[];if(t2.status!=="done")opts.push({title:"done",value:"complete",description:"mark complete (prompts for result)"});if(t2.status!=="blocked")opts.push({title:"blocked",value:"block",description:"mark blocked (prompts for reason)"});if(t2.status==="blocked")opts.push({title:"ready",value:"unblock",description:"return to ready"});opts.push({title:"archived",value:"archive",description:"archive (terminal)"}),dialog.replace($jsx(DialogSelect,{title:`Status for ${t2.id}`,options:opts,current:t2.status,filterable:!1,onSelect:async(o)=>{if(dialog.clear(),o.value==="complete"){let res=await openTextPrompt(dialog,{title:`Complete ${t2.id}`,label:"Result (optional)",initial:t2.result??""}),flag=res?` --result ${q3(res)}`:"";sh(`complete ${q3(t2.id)}${flag}`,`Completed ${t2.id}`);return}if(o.value==="block"){let r=await openTextPrompt(dialog,{title:`Block ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`block ${q3(t2.id)}${arg}`,`Blocked ${t2.id}`);return}if(o.value==="unblock")return void sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`);if(o.value==="archive")return void archive(t2)}}))},[dialog,sh,archive]),editParents=import_react79.useCallback((t2)=>{let cur2=(pane?.kind==="detail"&&pane.d.id===t2.id?pane.d:detailOf(at,t2.id))?.parents??[],d2=data2.get(at)??new Map,opts=STATUSES.flatMap((s)=>d2.get(s)??[]).filter((x2)=>x2.id!==t2.id).map((x2)=>({title:x2.id,description:trunc4(x2.title,50),value:x2.id,category:cur2.includes(x2.id)?"linked":"available"}));dialog.replace($jsx(DialogSelect,{title:`Parents for ${t2.id}`,options:opts,placeholder:"Select to toggle link\u2026",onSelect:(o)=>{if(dialog.clear(),cur2.includes(o.value))sh(`unlink ${q3(o.value)} ${q3(t2.id)}`,`Unlinked ${o.value}`);else sh(`link ${q3(o.value)} ${q3(t2.id)}`,`Linked ${o.value}`)}}))},[dialog,sh,data2,at,pane]),openField=import_react79.useCallback((f,t2)=>{if(f==="title")return void editTitle(t2);if(f==="body")return void editBody(t2);if(f==="assignee")return assign(t2);if(f==="priority")return editPriority(t2);if(f==="status")return editStatus(t2);if(f==="parents")return editParents(t2);if(f==="result")return void editResult(t2);if(f==="comment")return void comment(t2)},[editTitle,editBody,assign,editPriority,editStatus,editParents,editResult,comment]),bumpPriority=import_react79.useCallback((t2,d2)=>{let next2=Math.max(0,Math.min(9,t2.priority+d2));if(next2===t2.priority)return;patchDirect(t2.id,{priority:next2},`${t2.id} \u2192 P${next2}`)},[patchDirect]),ACTS=import_react79.useMemo(()=>[{key:"n",title:"New task",when:()=>!0,run:()=>void create()},{key:"N",title:"New child",when:(t2)=>!!t2,run:(t2)=>void create(t2)},{key:"a",title:"Assign",when:(t2)=>!!t2,run:(t2)=>void assign(t2)},{key:"c",title:"Comment",when:(t2)=>!!t2,run:(t2)=>void comment(t2)},{key:"s",title:"Specify",when:(t2)=>t2?.status==="triage",run:(t2)=>void specify(t2)},{key:"S",title:"Specify all",when:()=>!0,run:()=>void specifyAll()},{key:"u",title:"Unblock",when:(t2)=>t2?.status==="blocked",run:(t2)=>void unblock(t2)},{key:"d",title:"Archive",when:(t2)=>!!t2,run:(t2)=>void archive(t2)},{key:"l",title:"Worker log",when:(t2)=>!!t2,run:(t2)=>showLog(t2)},{key:"b",title:"New board",when:()=>!0,run:()=>void newBoard()},{key:"D",title:"Dispatch",when:()=>!0,run:()=>void dispatch()}],[create,assign,comment,specify,specifyAll,unblock,archive,showLog,newBoard,dispatch]),isOpen=open2.has(at),paneOpen=pane?.kind==="detail",paneFields=paneOpen?fieldsFor(pane.d):[];useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="escape"&&pane){if(tier==="pane"){setTier("grid");return}return setPane(null)}if(keys.match("list.refresh",key2))return load3();if(key2.name==="tab"){if(paneOpen&&tier!=="pane"){setTier("pane"),setPaneSel(0);return}if(tier==="pane"){let n=paneFields.length;if(n===0)return;let d2=key2.shift?-1:1;setPaneSel((s)=>(s+d2+n)%n);return}return goBoard(key2.shift?-1:1)}if(tier==="pane"){let t3=live.current.task;if(!t3||!paneOpen)return;let f=paneFields[Math.min(paneSel,paneFields.length-1)];if(key2.name==="up"){if(f==="priority")return bumpPriority(t3,1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s-1+n)%n)}if(key2.name==="down"){if(f==="priority")return bumpPriority(t3,-1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s+1)%n)}if(key2.name==="return")return openField(f,t3);let hit2=ACTS.find((a)=>a.key===key2.raw&&a.when(t3));if(hit2)return hit2.run(t3);return}if(key2.name==="space"||key2.name===" "){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip])return flip(sec3.chips[chip]);return}if(key2.name==="down"){if(tier==="head"){if(isOpen)return setTier("filter");let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(tier==="filter"){if(sec3&&sec3.shown>0){setTier("grid"),setRow(0);return}let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(row2<(cur?.tasks.length??1)-1)return setRow((r)=>r+1);let n=stepBoard(1);return n?enterTop(n):void 0}if(key2.name==="up"){if(tier==="head"){let p=stepBoard(-1);return p?enterBottom(p):void 0}if(tier==="filter")return setTier("head");if(row2>0)return setRow((r)=>r-1);return setTier("filter")}if(key2.name==="left"){if(tier==="filter")return setChip((c)=>Math.max(0,c-1));if(tier==="grid")return setCol((c)=>{let n=Math.max(0,c-1);return setRow(0),n});return}if(key2.name==="right"){if(tier==="filter")return setChip((c)=>Math.min((sec3?.chips.length??1)-1,c+1));if(tier==="grid")return setCol((c)=>{let n=Math.min(cols2.length-1,c+1);return setRow(0),n});return}if(key2.name==="return"){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip])return flip(sec3.chips[chip]);if(task)return setPane((p)=>p?.kind==="detail"&&p.d.id===task.id?null:((d2)=>d2?{kind:"detail",slug:at,d:d2}:null)(detailOf(at,task.id)));return}let t2=live.current.task,hit=ACTS.find((a)=>a.key===key2.raw&&a.when(t2));if(hit)return hit.run(t2)});let hint=import_react79.useMemo(()=>{let t2=task;return[tier==="pane"?"Esc grid":"Tab board",tier==="head"?"\u2191\u2193 nav Space fold":tier==="filter"?"\u2190\u2192 chip Space toggle":tier==="pane"?"Tab/\u2191\u2193 field Enter edit Esc grid":"\u2190\u2192\u2191\u2193 nav Enter detail",...ACTS.filter((a)=>a.when(t2)).map((a)=>`${a.key} ${a.title.toLowerCase()}`),`${keys.print("list.refresh")} reload`].join(" ")},[ACTS,keys,task,tier]),onHead=import_react79.useCallback((s)=>{setAt(s),setTier("head"),toggle(s)},[toggle]),onChip=import_react79.useCallback((s,i,c)=>{setAt(s),setTier("filter"),setChip(i),flip(c)},[flip]),onPick=import_react79.useCallback((s,ci,ri,id)=>{setAt(s),setTier("grid"),setCol(ci),setRow(ri),setOpen((o)=>o.has(s)?o:new Set(o).add(s));let d2=detailOf(s,id);if(d2)setPane({kind:"detail",slug:s,d:d2})},[]);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Kanban \xB7 ${sections.length} board${sections.length===1?"":"s"} \xB7 ${grand} task${grand===1?"":"s"}${running2?` \xB7 ${running2} running`:""}`,children:$jsx("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:sections.map((s)=>{let on=s.board.slug===at,secOpen=open2.has(s.board.slug),m2=maskOf(s.board.slug),filt=m2.who.size+m2.pri.size+m2.status.size,dg=diags.get(s.board.slug)??EMPTY_DIAG;return $jsxs("box",{id:`kb-sec-${s.board.slug}`,flexDirection:"column",flexShrink:0,marginBottom:1,children:[$jsx("box",{height:1,onMouseDown:()=>onHead(s.board.slug),backgroundColor:on&&tier==="head"?theme.backgroundElement:void 0,children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:secOpen?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:on?theme.primary:theme.text,children:$jsx("strong",{children:s.board.name})}),$jsx("span",{fg:theme.textMuted,children:s.total===0?" \xB7 empty":` \xB7 ${filt?`${s.shown}/`:""}${s.total} task${s.total===1?"":"s"}${s.running?` \xB7 ${s.running} running`:""}`})]})}),secOpen?s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsxs("text",{fg:theme.textMuted,children:["no tasks \u2014 ",$jsx("span",{fg:theme.accent,children:"n"})," to create one here"]})}):$jsxs($Fragment,{children:[$jsx(FilterBar,{chips:s.chips,mask:m2,on:on&&tier==="filter",sel:on?Math.min(chip,s.chips.length-1):-1,onPick:(i)=>onChip(s.board.slug,i,s.chips[i])}),s.cols.length>0?$jsx("box",{flexDirection:"row",height:s.cap,gap:1,children:s.cols.map((c,ci)=>$jsx(Column,{slug:s.board.slug,status:c.status,tasks:c.tasks,diags:dg,on:on&&(tier==="grid"||tier==="pane")&&ci===clampCol,sel:on?row2:0,onPick:(ri)=>onPick(s.board.slug,ci,ri,c.tasks[ri].id)},c.status))}):$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.textMuted,children:"all columns hidden"})})]}):null]},s.board.slug)})})})}),pane?$jsx(SidePane,{pane,on:tier==="pane",sel:paneSel,diags:pane.kind==="detail"?diags.get(pane.slug)?.get(pane.d.id)??EMPTY_DIAGS:EMPTY_DIAGS}):null]}),$jsx(HintBar,{raw:hint})]})});var Automation=import_react81.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[AUTOMATION_TAB];import_react81.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(Pane2,{visible:props.sub===0,children:$jsx(Kanban,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane2,{visible:props.sub===1,children:$jsx(Agents,{focused:!!props.focused&&props.sub===1,sessionId:props.sessionId,onSwitchProfile:props.onSwitchProfile})}),$jsx(Pane2,{visible:props.sub===2,children:$jsx(Cron,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane2=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:children2}):null;var import_react93=__toESM(require_react_production(),1);var import_react83=__toESM(require_react_production(),1);init_lane();var int=(lo,hi,what=`${lo}\u2013${hi}`)=>(raw)=>{let n=Number(raw);if(!Number.isInteger(n))return`expected integer ${what}`;if(n<lo||n>hi)return`expected ${what}`;return null},float=(lo,hi)=>(raw)=>{let n=Number(raw);if(!Number.isFinite(n))return`expected number ${lo}\u2013${hi}`;if(n<lo||n>hi)return`expected ${lo}\u2013${hi}`;return null},oneOf=(...opts)=>(raw)=>opts.includes(raw)?null:`expected one of: ${opts.join(" | ")}`,nonNeg=(raw)=>{let n=Number(raw);return Number.isFinite(n)&&n>=0?null:"expected \u2265 0"},RULES={"compression.threshold":float(0.1,0.95),"compression.target_ratio":float(0.05,0.9),"prompt_caching.cache_ttl":(raw)=>/^\d+[smhd]$/.test(raw.trim())?null:"expected duration e.g. 5m, 1h","agent.max_turns":int(1,1e4),"delegation.max_iterations":int(1,1e4),"delegation.max_concurrent_children":int(1,64),"delegation.max_spawn_depth":int(1,3),"agent.gateway_timeout":nonNeg,"agent.gateway_timeout_warning":nonNeg,"agent.gateway_notify_interval":nonNeg,"agent.restart_drain_timeout":nonNeg,"delegation.child_timeout_seconds":int(30,86400),"browser.command_timeout":int(1,600),"approvals.timeout":int(1,3600),"security.tirith_timeout":int(1,120),"agent.api_max_retries":int(0,20),"tool_output.max_bytes":int(1024,1e7),"tool_output.max_lines":int(10,1e5),"sessions.retention_days":int(1,3650),"sessions.min_interval_hours":int(1,720),"agent.service_tier":oneOf("","fast","standard"),"display.busy_input_mode":oneOf("queue","steer","interrupt"),"display.details_mode":oneOf("hidden","collapsed","expanded"),"display.thinking_mode":oneOf("collapsed","truncated","full"),"display.tool_progress":oneOf("off","new","all","verbose"),"display.final_response_markdown":oneOf("render","strip","raw"),"logging.level":oneOf("DEBUG","INFO","WARNING","ERROR"),"approvals.mode":oneOf("manual","ask","yolo","deny"),"code_execution.mode":oneOf("project","strict")},check=(key2,raw)=>RULES[key2]?.(raw)??null;init_schema();init_lane();var SELECTS={"terminal.backend":["local","docker","ssh","modal","daytona","singularity","vercel_sandbox"],"tts.provider":["edge","elevenlabs","openai","neutts","xai","mistral"],"display.skin":[...SKINS],"logging.level":["DEBUG","INFO","WARNING","ERROR"],"agent.reasoning_effort":["","none","minimal","low","medium","high","xhigh"],"display.busy_input_mode":["queue","steer","interrupt"],"display.details_mode":["hidden","collapsed","expanded"],"display.thinking_mode":["collapsed","truncated","full"],"display.tool_progress":["off","new","all","verbose"],"approvals.mode":["manual","ask","yolo","deny"]},get3=(obj,path7)=>{let cur=obj;for(let p of path7.split("."))if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},classify2=(key2,t2)=>{if(route(key2).via==="readonly")return"readonly";if(SELECTS[key2])return"select";if(t2==="bool")return"boolean";if(t2==="int"||t2==="float")return"number";return"string"},labelOf=(key2)=>{let raw=SCHEMA[key2]?.group??key2.split(".")[0];return key2.startsWith(`${raw}.`)?key2.slice(raw.length+1):key2},buildFields=(user)=>{let seen=new Set,out=[];for(let key2 of SCHEMA_KEYS){let s=SCHEMA[key2],uv=get3(user,key2),set2=uv!==void 0;out.push({key:key2,label:labelOf(key2),type:classify2(key2,s.type),value:set2?uv:s.default,set:set2,doc:s.doc,effect:s.effect,options:SELECTS[key2]}),seen.add(key2)}let walk=(obj,prefix="")=>{for(let[k2,v2]of Object.entries(obj)){let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2)){if(SCHEMA[key2]?.type==="dict"){seen.add(key2);continue}walk(v2,key2);continue}if(seen.has(key2))continue;out.push({key:key2,label:labelOf(key2),type:Array.isArray(v2)?"readonly":typeof v2==="boolean"?"boolean":typeof v2==="number"?"number":"string",value:v2,set:!0,doc:"",effect:"live"})}};return walk(user),out},MERGE={approvals:"security",privacy:"security",checkpoints:"agent",context:"agent",cron:"agent",network:"agent",model_catalog:"general",onboarding:"general",human_delay:"display",dashboard:"display",tool_output:"agent",prompt_caching:"compression",code_execution:"terminal",lsp:"agent",x_search:"agent",slack:"platforms",telegram:"platforms",mattermost:"platforms",discord:"platforms",whatsapp:"platforms",matrix:"platforms"},rawGroupOf=(key2)=>SCHEMA[key2]?.group??(key2.includes(".")?key2.split(".")[0]:"general"),groupOf=(key2)=>{let raw=rawGroupOf(key2);return MERGE[raw]??raw},sections=(group,fields)=>{let by=new Map;for(let f of fields){let r=rawGroupOf(f.key);if(!by.has(r))by.set(r,[]);by.get(r).push(f)}if(by.size<=1)return[{head:null,items:fields}];return[...by.keys()].sort((a,b2)=>a===group?-1:b2===group?1:a.localeCompare(b2)).map((r)=>({head:r,items:by.get(r)}))},GROUPS=(()=>{let g=new Set(["general"]);for(let k2 of SCHEMA_KEYS)g.add(groupOf(k2));return[...g]})(),EFFECT_GLYPH={live:"",session:"\u21BB",restart:"\u27F3"};init_lane();var AUX_TASKS=[{key:"vision",label:"Vision",hint:"Image analysis"},{key:"web_extract",label:"Web Extract",hint:"Page summarization"},{key:"compression",label:"Compression",hint:"Context compaction"},{key:"session_search",label:"Session Search",hint:"Recall queries"},{key:"skills_hub",label:"Skills Hub",hint:"Skill search"},{key:"approval",label:"Approval",hint:"Smart auto-approve"},{key:"mcp",label:"MCP",hint:"MCP tool routing"},{key:"title_generation",label:"Title Gen",hint:"Session titles"},{key:"curator",label:"Curator",hint:"Skill-usage review"}],dig=(o,...path7)=>path7.reduce((c,p)=>c&&typeof c==="object"?c[p]:void 0,o),str2=(v2)=>typeof v2==="string"?v2:"",readSlots=(raw)=>{let main2={kind:"main",key:"main",label:"Main model",hint:"Primary agent model",provider:str2(dig(raw,"model","provider")),model:str2(dig(raw,"model","default"))||str2(dig(raw,"model","name")),auto:!1},aux=AUX_TASKS.map((t2)=>{let p=str2(dig(raw,"auxiliary",t2.key,"provider"));return{kind:"aux",key:t2.key,label:t2.label,hint:t2.hint,provider:p,model:str2(dig(raw,"auxiliary",t2.key,"model")),auto:p===""||p==="auto"}});return[main2,...aux]},assign=async(gw,slot,provider,model)=>{if(slot==="main"){let r=await gw.request("config.set",{key:"model",value:`${model} --provider ${provider} --global`,session_id:void 0});return{ok:["model.default","model.provider"],failed:[],warnings:[],warning:r.warning}}return writeConfig(gw,[{key:`auxiliary.${slot}.provider`,to:provider},{key:`auxiliary.${slot}.model`,to:model}])},resetAux=(gw,slot)=>{let keys=slot==="all"?AUX_TASKS.map((t2)=>t2.key):[slot];return writeConfig(gw,keys.flatMap((k2)=>[{key:`auxiliary.${k2}.provider`,to:"auto"},{key:`auxiliary.${k2}.model`,to:""}]))};var import_react82=__toESM(require_react_production(),1);var ModelPickerDialog=(props)=>{let dialog=useDialog(),toast=useToast(),theme=useTheme().theme,[data2,setData]=import_react82.useState(null),[step,setStep]=import_react82.useState("provider"),[provider,setProvider]=import_react82.useState(null),[global2,setGlobal]=import_react82.useState(!1);import_react82.useEffect(()=>{props.gw.request("model.options").then(setData).catch(()=>setData({providers:[]}))},[props.gw]);let apply=import_react82.useCallback((model,prov)=>{if(props.onApply)return void props.onApply(prov,model).catch((e)=>toast.show({variant:"error",message:e.message}));let value=`${model} --provider ${prov}${global2?" --global":""}`;props.gw.request("config.set",global2?{key:"model",value,session_id:void 0}:{key:"model",value}).then((r)=>{if(toast.show({variant:"success",message:`model \u2192 ${r.value??model}${global2?" (global)":""}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[props.gw,props.onApply,global2,toast]),onKey=import_react82.useCallback((k2)=>{if(k2.name==="tab"&&!props.onApply)return setGlobal((g)=>!g),!0;if(k2.name==="left"&&step==="model")return setStep("provider"),!0;return!1},[step,props.onApply]),footer=props.onApply?$jsx("text",{fg:theme.textMuted,children:step==="model"?"\u2190: providers":" "}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{children:"Scope: "}),$jsx("span",{fg:global2?theme.warning:theme.accent,children:global2?"global (persists to config)":"this session"}),$jsxs("span",{children:[" \xB7 Tab: toggle",step==="model"?" \xB7 \u2190: providers":""]})]});if(!data2)return $jsx("box",{width:50,padding:1,children:$jsx("text",{children:"Loading models\u2026"})});if(step==="provider"){let options2=(data2.providers??[]).map((p2)=>({title:p2.name,value:p2.slug,description:p2.total_models?`${p2.total_models} models`:void 0,category:p2.is_current?"Current":"Available"}));return $jsx(DialogSelect,{title:props.title??"Switch Provider",options:options2,current:data2.provider,onSelect:(o)=>{setProvider(o.value),setStep("model")},onKey,placeholder:"Search providers...",footer})}let p=data2.providers?.find((pp)=>pp.slug===provider),options=(p?.models??[]).map((m2)=>({title:m2,value:m2}));return $jsx(DialogSelect,{title:props.title?`${props.title} \xB7 ${p?.name??provider}`:`Switch Model (${p?.name??provider})`,options,current:data2.model,onSelect:(o)=>{if(provider)apply(o.value,provider);dialog.clear()},onKey,placeholder:"Search models...",footer})},openModelPicker=(dialog,gw,opts)=>{dialog.replace($jsx(ModelPickerDialog,{gw,title:opts?.title,onApply:opts?.onApply}))};var flatten=(obj,prefix="")=>Object.entries(obj).flatMap(([k2,v2])=>{let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2))return flatten(v2,key2);return[[key2,v2]]}),setNested=(obj,path7,val)=>{let parts2=path7.split("."),cur=obj;for(let i=0;i<parts2.length-1;i++){if(!cur[parts2[i]]||typeof cur[parts2[i]]!=="object")cur[parts2[i]]={};cur=cur[parts2[i]]}cur[parts2[parts2.length-1]]=val},getNested=(obj,path7)=>{let parts2=path7.split("."),cur=obj;for(let p of parts2)if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},FieldRow=import_react83.memo((props)=>{let theme=useTheme().theme,f=props.field,bg2=props.active?theme.backgroundElement:void 0,indicator=props.active?"\u25B8 ":" ",mark2=props.changed?"\u25CF ":f.set?"\xB7":" ",markFg=props.changed?theme.warning:theme.textMuted,display=()=>{if(props.editing)return props.buf+"\u2588";if(f.type==="readonly"){let n=Array.isArray(f.value)?f.value.length:f.value&&typeof f.value==="object"?Object.keys(f.value).length:0;return n===0?"\u2014":`${n} item${n===1?"":"s"}`}if(f.type==="boolean")return f.value?"\u2713 ON":"\u2717 OFF";return String(f.value??"")},hint=()=>{if(props.readonly||f.type==="readonly")return"\uD83D\uDD12";if(f.type==="boolean")return"[space]";if(f.type==="select")return"[h/l]";return"[enter]"},ro=props.readonly||f.type==="readonly",valFg=ro||!f.set?theme.textMuted:f.type==="boolean"?f.value?theme.success:theme.error:theme.text,labelFg=ro?theme.textMuted:props.active?theme.accent:theme.text,lead=4+(props.badge!==void 0?12:0),glyph=props.active?EFFECT_GLYPH[f.effect]:"";return $jsxs("box",{id:props.id,flexDirection:"column",backgroundColor:bg2,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:markFg,children:mark2}),$jsx(Col,{w:2,fg:props.active?theme.primary:theme.text,children:indicator}),props.badge!==void 0?$jsx(Col,{w:12,fg:theme.textMuted,children:props.badge}):null,$jsx(Col,{w:40,fg:labelFg,children:f.label}),$jsx(Col,{grow:!0,min:6,fg:valFg,children:display()}),$jsx(Col,{w:2,fg:theme.textMuted,children:glyph}),$jsx(Col,{w:9,fg:theme.textMuted,right:!0,children:props.active?hint():""})]}),props.error?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:lead+40,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:6,fg:theme.error,children:`\u2717 ${props.error}`})]}):props.active&&f.doc?$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:lead,flexShrink:0}),$jsx("box",{width:40,flexShrink:0,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:f.doc})})]}):null]})}),SlotRow=import_react83.memo((p)=>{let theme=useTheme().theme,main2=p.s.kind==="main",val=main2?`${p.s.provider||"(unset)"} \xB7 ${p.s.model||"(unset)"}`:p.s.auto?"auto (use main model)":`${p.s.provider} \xB7 ${p.s.model||"(provider default)"}`;return $jsxs("box",{id:p.id,flexDirection:"row",height:1,backgroundColor:p.on?theme.backgroundElement:void 0,children:[$jsx(Col,{w:2,fg:p.on?theme.primary:theme.text,children:p.on?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:main2?theme.primary:theme.textMuted,children:main2?"\u2605":" "}),$jsx(Col,{w:16,fg:p.on?theme.accent:theme.text,children:p.s.label}),$jsx(Col,{w:22,fg:theme.textMuted,children:p.s.hint}),$jsx(Col,{grow:!0,min:10,fg:p.s.auto?theme.textMuted:theme.text,children:val}),$jsx(Col,{w:14,fg:theme.textMuted,right:!0,children:p.on?main2?"[enter]":"[enter] [x]":""})]})}),Config=import_react83.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),toast=useToast(),dialog=useDialog(),[raw,setRaw]=import_react83.useState({}),[original,setOriginal]=import_react83.useState({}),[yaml,setYaml]=import_react83.useState(""),[mode,setMode]=import_react83.useState("form"),[cat,setCat]=import_react83.useState(0),[cursor,setCursor]=import_react83.useState(0),[editing,setEditing]=import_react83.useState(!1),[buf,setBuf]=import_react83.useState(""),[err,setErr]=import_react83.useState({}),[searching,setSearching]=import_react83.useState(!1),[query,setQuery]=import_react83.useState(""),[focus,setFocus]=import_react83.useState("categories"),[managed,setManaged]=import_react83.useState(null);import_react83.useEffect(()=>{managedSystem().then(setManaged)},[]);let load3=import_react83.useCallback(()=>{gw.request("config.get",{key:"full"}).then((res)=>{let parsed=res.config??{};setRaw(structuredClone(parsed)),setOriginal(structuredClone(parsed)),setYaml($stringify(parsed)),setErr({})}).catch(()=>{setRaw({}),setOriginal({}),setYaml("")})},[gw]);import_react83.useEffect(()=>{load3()},[load3]);let all=buildFields(raw),grouped=all.reduce((map,f)=>{let g=groupOf(f.key);if(!map.has(g))map.set(g,[]);return map.get(g).push(f),map},new Map(GROUPS.map((g)=>[g,[]]))),groups=[...grouped.keys()];groups.splice(1,0,"models");let active=groups[cat]??groups[0],onSlots=active==="models"&&!searching,slots=readSlots(raw),secs=searching&&query.trim()?[{head:null,items:all.filter((f)=>f.key.toLowerCase().includes(query.toLowerCase()))}]:sections(active,grouped.get(active)??[]),fields=secs.flatMap((s)=>s.items),count3=onSlots?slots.length:fields.length,follow=useFollow("cfg"),catFollow=useFollow("cfg-cat"),changed=(key2)=>JSON.stringify(getNested(raw,key2))!==JSON.stringify(getNested(original,key2)),nChanged=all.reduce((n,f)=>n+(changed(f.key)?1:0),0),update=(key2,val)=>{let next2=structuredClone(raw);setNested(next2,key2,val),setRaw(next2),setYaml($stringify(next2))},fmt3=(v2)=>v2===void 0?"\u2014":Array.isArray(v2)?v2.join(", "):String(v2),save2=async()=>{if(managed){toast.show({variant:"error",message:`Managed by ${managed} \u2014 edit configuration.nix`});return}let nErr=Object.keys(err).length;if(nErr>0){toast.show({variant:"error",message:`${nErr} invalid field${nErr===1?"":"s"}`});return}let target=mode==="yaml"?$parse(yaml)??{}:raw,diffs=flatten(target).filter(([key2])=>JSON.stringify(getNested(target,key2))!==JSON.stringify(getNested(original,key2))).map(([key2,val])=>({key:key2,from:getNested(original,key2),to:val}));if(diffs.length===0){toast.show({variant:"info",message:"No changes"});return}let body=diffs.map((d2)=>`${d2.key}: ${fmt3(d2.from)} \u2192 ${fmt3(d2.to)}`).join(`
4122
+ `).flatMap((l)=>l.trim()?[JSON.parse(l)]:[]),specify=import_react79.useCallback((t2)=>{if(t2.status!=="triage")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not triage`});return sh(`specify ${q3(t2.id)} --json`).then((out)=>{if(out==null)return;let r=parseSpecify(out)[0];if(!r)return;if(!r.ok)return void toast.show({variant:"error",message:`specify ${r.task_id}: ${trunc4(r.reason??"failed",100)}`});toast.show({variant:"success",message:r.new_title?`Specified ${r.task_id} \u2192 ${trunc4(r.new_title,60)}`:`Specified ${r.task_id} \u2192 todo`})})},[sh,toast]),specifyAll=import_react79.useCallback(()=>{let triage=live.current.sec?.cols.find((c)=>c.status==="triage")?.tasks.length??0;if(triage===0)return void toast.show({variant:"info",message:`No 'triage' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Specify all \xB7 ${live.current.at}`,body:`${triage} task${triage===1?"":"s"} in 'triage'. Auxiliary LLM expands each body and promotes to todo.`,yes:"specify"}).then((go)=>{if(!go)return;return sh("specify --all --json").then((out)=>{if(out==null)return;let rows3=parseSpecify(out),ok=rows3.filter((r)=>r.ok).length,bad=rows3.length-ok;toast.show({variant:ok===0&&bad>0?"error":"success",message:`Specified ${ok}/${rows3.length}${bad?` (${bad} failed)`:""}`})})})},[dialog,sh,toast]),dispatch=import_react79.useCallback(()=>{let ready=live.current.sec?.cols.find((c)=>c.status==="ready")?.tasks.length??0;if(ready===0)return void toast.show({variant:"info",message:`No 'ready' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Dispatch \xB7 ${live.current.at}`,body:`${ready} task${ready===1?"":"s"} in 'ready'. Spawns one worker per task (one pass).`,yes:"dispatch"}).then((ok)=>{if(ok)sh("dispatch --json",`Dispatched (${ready} ready)`)})},[dialog,sh,toast]),showLog=import_react79.useCallback((t2)=>{let s=live.current.at,text2=tailLogOf(s,t2.id);if(text2==null)return void toast.show({variant:"info",message:`No worker log for ${t2.id}`});setPane({kind:"log",slug:s,id:t2.id,text:text2})},[toast]),editTitle=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit title",label:t2.id,initial:t2.title}).then((v2)=>v2!==null&&v2!==void 0&&patchDirect(t2.id,{title:v2},`Updated ${t2.id}`)),[dialog,patchDirect]),editBody=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit body",label:t2.id,initial:t2.body??""}).then((v2)=>{if(v2===null||v2===void 0)return;patchDirect(t2.id,{body:v2},`Updated ${t2.id}`)}),[dialog,patchDirect]),editPriority=import_react79.useCallback((t2)=>{let opts=Array.from({length:10},(_2,i)=>({title:i===0?"P0 (none)":`P${i}`,value:String(i)}));dialog.replace($jsx(DialogSelect,{title:`Priority for ${t2.id}`,options:opts,current:String(t2.priority),filterable:!1,onSelect:(o)=>{dialog.clear(),patchDirect(t2.id,{priority:Number(o.value)},`${t2.id} \u2192 P${o.value}`)}}))},[dialog,patchDirect]),editResult=import_react79.useCallback((t2)=>{if(t2.status!=="done")return void toast.show({variant:"info",message:`${t2.id} is not done`});return openTextPrompt(dialog,{title:"Edit result",label:t2.id,initial:t2.result??""}).then((v2)=>{if(v2==null)return;sh(`edit ${q3(t2.id)} --result ${q3(v2)}`,`Updated ${t2.id} result`)})},[dialog,sh,toast]),editStatus=import_react79.useCallback((t2)=>{let opts=[];if(t2.status!=="done")opts.push({title:"done",value:"complete",description:"mark complete (prompts for result)"});if(t2.status!=="blocked")opts.push({title:"blocked",value:"block",description:"mark blocked (prompts for reason)"});if(t2.status==="blocked")opts.push({title:"ready",value:"unblock",description:"return to ready"});opts.push({title:"archived",value:"archive",description:"archive (terminal)"}),dialog.replace($jsx(DialogSelect,{title:`Status for ${t2.id}`,options:opts,current:t2.status,filterable:!1,onSelect:async(o)=>{if(dialog.clear(),o.value==="complete"){let res=await openTextPrompt(dialog,{title:`Complete ${t2.id}`,label:"Result (optional)",initial:t2.result??""}),flag=res?` --result ${q3(res)}`:"";sh(`complete ${q3(t2.id)}${flag}`,`Completed ${t2.id}`);return}if(o.value==="block"){let r=await openTextPrompt(dialog,{title:`Block ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`block ${q3(t2.id)}${arg}`,`Blocked ${t2.id}`);return}if(o.value==="unblock")return void sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`);if(o.value==="archive")return void archive(t2)}}))},[dialog,sh,archive]),editParents=import_react79.useCallback((t2)=>{let cur2=(pane?.kind==="detail"&&pane.d.id===t2.id?pane.d:detailOf(at,t2.id))?.parents??[],d2=data2.get(at)??new Map,opts=STATUSES.flatMap((s)=>d2.get(s)??[]).filter((x2)=>x2.id!==t2.id).map((x2)=>({title:x2.id,description:trunc4(x2.title,50),value:x2.id,category:cur2.includes(x2.id)?"linked":"available"}));dialog.replace($jsx(DialogSelect,{title:`Parents for ${t2.id}`,options:opts,placeholder:"Select to toggle link\u2026",onSelect:(o)=>{if(dialog.clear(),cur2.includes(o.value))sh(`unlink ${q3(o.value)} ${q3(t2.id)}`,`Unlinked ${o.value}`);else sh(`link ${q3(o.value)} ${q3(t2.id)}`,`Linked ${o.value}`)}}))},[dialog,sh,data2,at,pane]),openField=import_react79.useCallback((f,t2)=>{if(f==="title")return void editTitle(t2);if(f==="body")return void editBody(t2);if(f==="assignee")return assign(t2);if(f==="priority")return editPriority(t2);if(f==="status")return editStatus(t2);if(f==="parents")return editParents(t2);if(f==="result")return void editResult(t2);if(f==="comment")return void comment(t2)},[editTitle,editBody,assign,editPriority,editStatus,editParents,editResult,comment]),bumpPriority=import_react79.useCallback((t2,d2)=>{let next2=Math.max(0,Math.min(9,t2.priority+d2));if(next2===t2.priority)return;patchDirect(t2.id,{priority:next2},`${t2.id} \u2192 P${next2}`)},[patchDirect]),ACTS=import_react79.useMemo(()=>[{key:"n",title:"New task",when:()=>!0,run:()=>void create()},{key:"N",title:"New child",when:(t2)=>!!t2,run:(t2)=>void create(t2)},{key:"a",title:"Assign",when:(t2)=>!!t2,run:(t2)=>void assign(t2)},{key:"c",title:"Comment",when:(t2)=>!!t2,run:(t2)=>void comment(t2)},{key:"s",title:"Specify",when:(t2)=>t2?.status==="triage",run:(t2)=>void specify(t2)},{key:"S",title:"Specify all",when:()=>!0,run:()=>void specifyAll()},{key:"u",title:"Unblock",when:(t2)=>t2?.status==="blocked",run:(t2)=>void unblock(t2)},{key:"d",title:"Archive",when:(t2)=>!!t2,run:(t2)=>void archive(t2)},{key:"l",title:"Worker log",when:(t2)=>!!t2,run:(t2)=>showLog(t2)},{key:"b",title:"New board",when:()=>!0,run:()=>void newBoard()},{key:"D",title:"Dispatch",when:()=>!0,run:()=>void dispatch()}],[create,assign,comment,specify,specifyAll,unblock,archive,showLog,newBoard,dispatch]),isOpen=open2.has(at),paneOpen=pane?.kind==="detail",paneFields=paneOpen?fieldsFor(pane.d):[];useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="escape"&&pane){if(tier==="pane"){setTier("grid");return}return setPane(null)}if(keys.match("list.refresh",key2))return load3();if(key2.name==="tab"){if(paneOpen&&tier!=="pane"){setTier("pane"),setPaneSel(0);return}if(tier==="pane"){let n=paneFields.length;if(n===0)return;let d2=key2.shift?-1:1;setPaneSel((s)=>(s+d2+n)%n);return}return goBoard(key2.shift?-1:1)}if(tier==="pane"){let t3=live.current.task;if(!t3||!paneOpen)return;let f=paneFields[Math.min(paneSel,paneFields.length-1)];if(key2.name==="up"){if(f==="priority")return bumpPriority(t3,1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s-1+n)%n)}if(key2.name==="down"){if(f==="priority")return bumpPriority(t3,-1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s+1)%n)}if(key2.name==="return")return openField(f,t3);let hit2=ACTS.find((a)=>a.key===key2.raw&&a.when(t3));if(hit2)return hit2.run(t3);return}if(key2.name==="space"||key2.name===" "){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip])return flip(sec3.chips[chip]);return}if(key2.name==="down"){if(tier==="head"){if(isOpen)return setTier("filter");let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(tier==="filter"){if(sec3&&sec3.shown>0){setTier("grid"),setRow(0);return}let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(row2<(cur?.tasks.length??1)-1)return setRow((r)=>r+1);let n=stepBoard(1);return n?enterTop(n):void 0}if(key2.name==="up"){if(tier==="head"){let p=stepBoard(-1);return p?enterBottom(p):void 0}if(tier==="filter")return setTier("head");if(row2>0)return setRow((r)=>r-1);return setTier("filter")}if(key2.name==="left"){if(tier==="filter")return setChip((c)=>Math.max(0,c-1));if(tier==="grid")return setCol((c)=>{let n=Math.max(0,c-1);return setRow(0),n});return}if(key2.name==="right"){if(tier==="filter")return setChip((c)=>Math.min((sec3?.chips.length??1)-1,c+1));if(tier==="grid")return setCol((c)=>{let n=Math.min(cols2.length-1,c+1);return setRow(0),n});return}if(key2.name==="return"){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip])return flip(sec3.chips[chip]);if(task)return setPane((p)=>p?.kind==="detail"&&p.d.id===task.id?null:((d2)=>d2?{kind:"detail",slug:at,d:d2}:null)(detailOf(at,task.id)));return}let t2=live.current.task,hit=ACTS.find((a)=>a.key===key2.raw&&a.when(t2));if(hit)return hit.run(t2)});let hint=import_react79.useMemo(()=>{let t2=task;return[tier==="pane"?"Esc grid":"Tab board",tier==="head"?"\u2191\u2193 nav Space fold":tier==="filter"?"\u2190\u2192 chip Space toggle":tier==="pane"?"Tab/\u2191\u2193 field Enter edit Esc grid":"\u2190\u2192\u2191\u2193 nav Enter detail",...ACTS.filter((a)=>a.when(t2)).map((a)=>`${a.key} ${a.title.toLowerCase()}`),`${keys.print("list.refresh")} reload`].join(" ")},[ACTS,keys,task,tier]),onHead=import_react79.useCallback((s)=>{setAt(s),setTier("head"),toggle(s)},[toggle]),onChip=import_react79.useCallback((s,i,c)=>{setAt(s),setTier("filter"),setChip(i),flip(c)},[flip]),onPick=import_react79.useCallback((s,ci,ri,id)=>{setAt(s),setTier("grid"),setCol(ci),setRow(ri),setOpen((o)=>o.has(s)?o:new Set(o).add(s));let d2=detailOf(s,id);if(d2)setPane({kind:"detail",slug:s,d:d2})},[]);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Kanban \xB7 ${sections.length} board${sections.length===1?"":"s"} \xB7 ${grand} task${grand===1?"":"s"}${running2?` \xB7 ${running2} running`:""}`,children:$jsx("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:sections.map((s)=>{let on=s.board.slug===at,secOpen=open2.has(s.board.slug),m2=maskOf(s.board.slug),filt=m2.who.size+m2.pri.size+m2.status.size,dg=diags.get(s.board.slug)??EMPTY_DIAG;return $jsxs("box",{id:`kb-sec-${s.board.slug}`,flexDirection:"column",flexShrink:0,marginBottom:1,children:[$jsx("box",{height:1,onMouseDown:()=>onHead(s.board.slug),backgroundColor:on&&tier==="head"?theme.backgroundElement:void 0,children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:secOpen?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:on?theme.primary:theme.text,children:$jsx("strong",{children:s.board.name})}),$jsx("span",{fg:theme.textMuted,children:s.total===0?" \xB7 empty":` \xB7 ${filt?`${s.shown}/`:""}${s.total} task${s.total===1?"":"s"}${s.running?` \xB7 ${s.running} running`:""}`})]})}),secOpen?s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsxs("text",{fg:theme.textMuted,children:["no tasks \u2014 ",$jsx("span",{fg:theme.accent,children:"n"})," to create one here"]})}):$jsxs($Fragment,{children:[$jsx(FilterBar,{chips:s.chips,mask:m2,on:on&&tier==="filter",sel:on?Math.min(chip,s.chips.length-1):-1,onPick:(i)=>onChip(s.board.slug,i,s.chips[i])}),s.cols.length>0?$jsx("box",{flexDirection:"row",height:s.cap,gap:1,children:s.cols.map((c,ci)=>$jsx(Column,{slug:s.board.slug,status:c.status,tasks:c.tasks,diags:dg,on:on&&(tier==="grid"||tier==="pane")&&ci===clampCol,sel:on?row2:0,onPick:(ri)=>onPick(s.board.slug,ci,ri,c.tasks[ri].id)},c.status))}):$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.textMuted,children:"all columns hidden"})})]}):null]},s.board.slug)})})})}),pane?$jsx(SidePane,{pane,on:tier==="pane",sel:paneSel,diags:pane.kind==="detail"?diags.get(pane.slug)?.get(pane.d.id)??EMPTY_DIAGS:EMPTY_DIAGS}):null]}),$jsx(HintBar,{raw:hint})]})});var Automation=import_react81.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[AUTOMATION_TAB];import_react81.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(Pane2,{visible:props.sub===0,children:$jsx(Kanban,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane2,{visible:props.sub===1,children:$jsx(Agents,{focused:!!props.focused&&props.sub===1,sessionId:props.sessionId,onSwitchProfile:props.onSwitchProfile})}),$jsx(Pane2,{visible:props.sub===2,children:$jsx(Cron,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane2=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react93=__toESM(require_react_production(),1);var import_react83=__toESM(require_react_production(),1);init_lane();var int=(lo,hi,what=`${lo}\u2013${hi}`)=>(raw)=>{let n=Number(raw);if(!Number.isInteger(n))return`expected integer ${what}`;if(n<lo||n>hi)return`expected ${what}`;return null},float=(lo,hi)=>(raw)=>{let n=Number(raw);if(!Number.isFinite(n))return`expected number ${lo}\u2013${hi}`;if(n<lo||n>hi)return`expected ${lo}\u2013${hi}`;return null},oneOf=(...opts)=>(raw)=>opts.includes(raw)?null:`expected one of: ${opts.join(" | ")}`,nonNeg=(raw)=>{let n=Number(raw);return Number.isFinite(n)&&n>=0?null:"expected \u2265 0"},RULES={"compression.threshold":float(0.1,0.95),"compression.target_ratio":float(0.05,0.9),"prompt_caching.cache_ttl":(raw)=>/^\d+[smhd]$/.test(raw.trim())?null:"expected duration e.g. 5m, 1h","agent.max_turns":int(1,1e4),"delegation.max_iterations":int(1,1e4),"delegation.max_concurrent_children":int(1,64),"delegation.max_spawn_depth":int(1,3),"agent.gateway_timeout":nonNeg,"agent.gateway_timeout_warning":nonNeg,"agent.gateway_notify_interval":nonNeg,"agent.restart_drain_timeout":nonNeg,"delegation.child_timeout_seconds":int(30,86400),"browser.command_timeout":int(1,600),"approvals.timeout":int(1,3600),"security.tirith_timeout":int(1,120),"agent.api_max_retries":int(0,20),"tool_output.max_bytes":int(1024,1e7),"tool_output.max_lines":int(10,1e5),"sessions.retention_days":int(1,3650),"sessions.min_interval_hours":int(1,720),"agent.service_tier":oneOf("","fast","standard"),"display.busy_input_mode":oneOf("queue","steer","interrupt"),"display.details_mode":oneOf("hidden","collapsed","expanded"),"display.thinking_mode":oneOf("collapsed","truncated","full"),"display.tool_progress":oneOf("off","new","all","verbose"),"display.final_response_markdown":oneOf("render","strip","raw"),"logging.level":oneOf("DEBUG","INFO","WARNING","ERROR"),"approvals.mode":oneOf("manual","ask","yolo","deny"),"code_execution.mode":oneOf("project","strict")},check=(key2,raw)=>RULES[key2]?.(raw)??null;init_schema();init_lane();var SELECTS={"terminal.backend":["local","docker","ssh","modal","daytona","singularity","vercel_sandbox"],"tts.provider":["edge","elevenlabs","openai","neutts","xai","mistral"],"display.skin":[...SKINS],"logging.level":["DEBUG","INFO","WARNING","ERROR"],"agent.reasoning_effort":["","none","minimal","low","medium","high","xhigh"],"display.busy_input_mode":["queue","steer","interrupt"],"display.details_mode":["hidden","collapsed","expanded"],"display.thinking_mode":["collapsed","truncated","full"],"display.tool_progress":["off","new","all","verbose"],"approvals.mode":["manual","ask","yolo","deny"]},get3=(obj,path7)=>{let cur=obj;for(let p of path7.split("."))if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},classify2=(key2,t2)=>{if(route(key2).via==="readonly")return"readonly";if(SELECTS[key2])return"select";if(t2==="bool")return"boolean";if(t2==="int"||t2==="float")return"number";return"string"},labelOf=(key2)=>{let raw=SCHEMA[key2]?.group??key2.split(".")[0];return key2.startsWith(`${raw}.`)?key2.slice(raw.length+1):key2},buildFields=(user)=>{let seen=new Set,out=[];for(let key2 of SCHEMA_KEYS){let s=SCHEMA[key2],uv=get3(user,key2),set2=uv!==void 0;out.push({key:key2,label:labelOf(key2),type:classify2(key2,s.type),value:set2?uv:s.default,set:set2,doc:s.doc,effect:s.effect,options:SELECTS[key2]}),seen.add(key2)}let walk=(obj,prefix="")=>{for(let[k2,v2]of Object.entries(obj)){let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2)){if(SCHEMA[key2]?.type==="dict"){seen.add(key2);continue}walk(v2,key2);continue}if(seen.has(key2))continue;out.push({key:key2,label:labelOf(key2),type:Array.isArray(v2)?"readonly":typeof v2==="boolean"?"boolean":typeof v2==="number"?"number":"string",value:v2,set:!0,doc:"",effect:"live"})}};return walk(user),out},MERGE={approvals:"security",privacy:"security",checkpoints:"agent",context:"agent",cron:"agent",network:"agent",model_catalog:"general",onboarding:"general",human_delay:"display",dashboard:"display",tool_output:"agent",prompt_caching:"compression",code_execution:"terminal",lsp:"agent",x_search:"agent",slack:"platforms",telegram:"platforms",mattermost:"platforms",discord:"platforms",whatsapp:"platforms",matrix:"platforms"},rawGroupOf=(key2)=>SCHEMA[key2]?.group??(key2.includes(".")?key2.split(".")[0]:"general"),groupOf=(key2)=>{let raw=rawGroupOf(key2);return MERGE[raw]??raw},sections=(group,fields)=>{let by=new Map;for(let f of fields){let r=rawGroupOf(f.key);if(!by.has(r))by.set(r,[]);by.get(r).push(f)}if(by.size<=1)return[{head:null,items:fields}];return[...by.keys()].sort((a,b2)=>a===group?-1:b2===group?1:a.localeCompare(b2)).map((r)=>({head:r,items:by.get(r)}))},GROUPS=(()=>{let g=new Set(["general"]);for(let k2 of SCHEMA_KEYS)g.add(groupOf(k2));return[...g]})(),EFFECT_GLYPH={live:"",session:"\u21BB",restart:"\u27F3"};init_lane();var AUX_TASKS=[{key:"vision",label:"Vision",hint:"Image analysis"},{key:"web_extract",label:"Web Extract",hint:"Page summarization"},{key:"compression",label:"Compression",hint:"Context compaction"},{key:"session_search",label:"Session Search",hint:"Recall queries"},{key:"skills_hub",label:"Skills Hub",hint:"Skill search"},{key:"approval",label:"Approval",hint:"Smart auto-approve"},{key:"mcp",label:"MCP",hint:"MCP tool routing"},{key:"title_generation",label:"Title Gen",hint:"Session titles"},{key:"curator",label:"Curator",hint:"Skill-usage review"}],dig=(o,...path7)=>path7.reduce((c,p)=>c&&typeof c==="object"?c[p]:void 0,o),str2=(v2)=>typeof v2==="string"?v2:"",readSlots=(raw)=>{let main2={kind:"main",key:"main",label:"Main model",hint:"Primary agent model",provider:str2(dig(raw,"model","provider")),model:str2(dig(raw,"model","default"))||str2(dig(raw,"model","name")),auto:!1},aux=AUX_TASKS.map((t2)=>{let p=str2(dig(raw,"auxiliary",t2.key,"provider"));return{kind:"aux",key:t2.key,label:t2.label,hint:t2.hint,provider:p,model:str2(dig(raw,"auxiliary",t2.key,"model")),auto:p===""||p==="auto"}});return[main2,...aux]},assign=async(gw,slot,provider,model)=>{if(slot==="main"){let r=await gw.request("config.set",{key:"model",value:`${model} --provider ${provider} --global`,session_id:void 0});return{ok:["model.default","model.provider"],failed:[],warnings:[],warning:r.warning}}return writeConfig(gw,[{key:`auxiliary.${slot}.provider`,to:provider},{key:`auxiliary.${slot}.model`,to:model}])},resetAux=(gw,slot)=>{let keys=slot==="all"?AUX_TASKS.map((t2)=>t2.key):[slot];return writeConfig(gw,keys.flatMap((k2)=>[{key:`auxiliary.${k2}.provider`,to:"auto"},{key:`auxiliary.${k2}.model`,to:""}]))};var import_react82=__toESM(require_react_production(),1);var ModelPickerDialog=(props)=>{let dialog=useDialog(),toast=useToast(),theme=useTheme().theme,[data2,setData]=import_react82.useState(null),[step,setStep]=import_react82.useState("provider"),[provider,setProvider]=import_react82.useState(null),[global2,setGlobal]=import_react82.useState(!1);import_react82.useEffect(()=>{props.gw.request("model.options").then(setData).catch(()=>setData({providers:[]}))},[props.gw]);let apply=import_react82.useCallback((model,prov)=>{if(props.onApply)return void props.onApply(prov,model).catch((e)=>toast.show({variant:"error",message:e.message}));let value=`${model} --provider ${prov}${global2?" --global":""}`;props.gw.request("config.set",global2?{key:"model",value,session_id:void 0}:{key:"model",value}).then((r)=>{if(toast.show({variant:"success",message:`model \u2192 ${r.value??model}${global2?" (global)":""}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[props.gw,props.onApply,global2,toast]),onKey=import_react82.useCallback((k2)=>{if(k2.name==="tab"&&!props.onApply)return setGlobal((g)=>!g),!0;if(k2.name==="left"&&step==="model")return setStep("provider"),!0;return!1},[step,props.onApply]),footer=props.onApply?$jsx("text",{fg:theme.textMuted,children:step==="model"?"\u2190: providers":" "}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{children:"Scope: "}),$jsx("span",{fg:global2?theme.warning:theme.accent,children:global2?"global (persists to config)":"this session"}),$jsxs("span",{children:[" \xB7 Tab: toggle",step==="model"?" \xB7 \u2190: providers":""]})]});if(!data2)return $jsx("box",{width:50,padding:1,children:$jsx("text",{children:"Loading models\u2026"})});if(step==="provider"){let options2=(data2.providers??[]).map((p2)=>({title:p2.name,value:p2.slug,description:p2.total_models?`${p2.total_models} models`:void 0,category:p2.is_current?"Current":"Available"}));return $jsx(DialogSelect,{title:props.title??"Switch Provider",options:options2,current:data2.provider,onSelect:(o)=>{setProvider(o.value),setStep("model")},onKey,placeholder:"Search providers...",footer})}let p=data2.providers?.find((pp)=>pp.slug===provider),options=(p?.models??[]).map((m2)=>({title:m2,value:m2}));return $jsx(DialogSelect,{title:props.title?`${props.title} \xB7 ${p?.name??provider}`:`Switch Model (${p?.name??provider})`,options,current:data2.model,onSelect:(o)=>{if(provider)apply(o.value,provider);dialog.clear()},onKey,placeholder:"Search models...",footer})},openModelPicker=(dialog,gw,opts)=>{dialog.replace($jsx(ModelPickerDialog,{gw,title:opts?.title,onApply:opts?.onApply}))};var flatten=(obj,prefix="")=>Object.entries(obj).flatMap(([k2,v2])=>{let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2))return flatten(v2,key2);return[[key2,v2]]}),setNested=(obj,path7,val)=>{let parts2=path7.split("."),cur=obj;for(let i=0;i<parts2.length-1;i++){if(!cur[parts2[i]]||typeof cur[parts2[i]]!=="object")cur[parts2[i]]={};cur=cur[parts2[i]]}cur[parts2[parts2.length-1]]=val},getNested=(obj,path7)=>{let parts2=path7.split("."),cur=obj;for(let p of parts2)if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},FieldRow=import_react83.memo((props)=>{let theme=useTheme().theme,f=props.field,bg2=props.active?theme.backgroundElement:void 0,indicator=props.active?"\u25B8 ":" ",mark2=props.changed?"\u25CF ":f.set?"\xB7":" ",markFg=props.changed?theme.warning:theme.textMuted,display=()=>{if(props.editing)return props.buf+"\u2588";if(f.type==="readonly"){let n=Array.isArray(f.value)?f.value.length:f.value&&typeof f.value==="object"?Object.keys(f.value).length:0;return n===0?"\u2014":`${n} item${n===1?"":"s"}`}if(f.type==="boolean")return f.value?"\u2713 ON":"\u2717 OFF";return String(f.value??"")},hint=()=>{if(props.readonly||f.type==="readonly")return"\uD83D\uDD12";if(f.type==="boolean")return"[space]";if(f.type==="select")return"[h/l]";return"[enter]"},ro=props.readonly||f.type==="readonly",valFg=ro||!f.set?theme.textMuted:f.type==="boolean"?f.value?theme.success:theme.error:theme.text,labelFg=ro?theme.textMuted:props.active?theme.accent:theme.text,lead=4+(props.badge!==void 0?12:0),glyph=props.active?EFFECT_GLYPH[f.effect]:"";return $jsxs("box",{id:props.id,flexDirection:"column",backgroundColor:bg2,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:markFg,children:mark2}),$jsx(Col,{w:2,fg:props.active?theme.primary:theme.text,children:indicator}),props.badge!==void 0?$jsx(Col,{w:12,fg:theme.textMuted,children:props.badge}):null,$jsx(Col,{w:40,fg:labelFg,children:f.label}),$jsx(Col,{grow:!0,min:6,fg:valFg,children:display()}),$jsx(Col,{w:2,fg:theme.textMuted,children:glyph}),$jsx(Col,{w:9,fg:theme.textMuted,right:!0,children:props.active?hint():""})]}),props.error?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:lead+40,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:6,fg:theme.error,children:`\u2717 ${props.error}`})]}):props.active&&f.doc?$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:lead,flexShrink:0}),$jsx("box",{width:40,flexShrink:0,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:f.doc})})]}):null]})}),SlotRow=import_react83.memo((p)=>{let theme=useTheme().theme,main2=p.s.kind==="main",val=main2?`${p.s.provider||"(unset)"} \xB7 ${p.s.model||"(unset)"}`:p.s.auto?"auto (use main model)":`${p.s.provider} \xB7 ${p.s.model||"(provider default)"}`;return $jsxs("box",{id:p.id,flexDirection:"row",height:1,backgroundColor:p.on?theme.backgroundElement:void 0,children:[$jsx(Col,{w:2,fg:p.on?theme.primary:theme.text,children:p.on?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:main2?theme.primary:theme.textMuted,children:main2?"\u2605":" "}),$jsx(Col,{w:16,fg:p.on?theme.accent:theme.text,children:p.s.label}),$jsx(Col,{w:22,fg:theme.textMuted,children:p.s.hint}),$jsx(Col,{grow:!0,min:10,fg:p.s.auto?theme.textMuted:theme.text,children:val}),$jsx(Col,{w:14,fg:theme.textMuted,right:!0,children:p.on?main2?"[enter]":"[enter] [x]":""})]})}),Config=import_react83.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),toast=useToast(),dialog=useDialog(),[raw,setRaw]=import_react83.useState({}),[original,setOriginal]=import_react83.useState({}),[yaml,setYaml]=import_react83.useState(""),[mode,setMode]=import_react83.useState("form"),[cat,setCat]=import_react83.useState(0),[cursor,setCursor]=import_react83.useState(0),[editing,setEditing]=import_react83.useState(!1),[buf,setBuf]=import_react83.useState(""),[err,setErr]=import_react83.useState({}),[searching,setSearching]=import_react83.useState(!1),[query,setQuery]=import_react83.useState(""),[focus,setFocus]=import_react83.useState("categories"),[managed,setManaged]=import_react83.useState(null);import_react83.useEffect(()=>{managedSystem().then(setManaged)},[]);let load3=import_react83.useCallback(()=>{gw.request("config.get",{key:"full"}).then((res)=>{let parsed=res.config??{};setRaw(structuredClone(parsed)),setOriginal(structuredClone(parsed)),setYaml($stringify(parsed)),setErr({})}).catch(()=>{setRaw({}),setOriginal({}),setYaml("")})},[gw]);import_react83.useEffect(()=>{load3()},[load3]);let all=buildFields(raw),grouped=all.reduce((map,f)=>{let g=groupOf(f.key);if(!map.has(g))map.set(g,[]);return map.get(g).push(f),map},new Map(GROUPS.map((g)=>[g,[]]))),groups=[...grouped.keys()];groups.splice(1,0,"models");let active=groups[cat]??groups[0],onSlots=active==="models"&&!searching,slots=readSlots(raw),secs=searching&&query.trim()?[{head:null,items:all.filter((f)=>f.key.toLowerCase().includes(query.toLowerCase()))}]:sections(active,grouped.get(active)??[]),fields=secs.flatMap((s)=>s.items),count3=onSlots?slots.length:fields.length,follow=useFollow("cfg"),catFollow=useFollow("cfg-cat"),changed=(key2)=>JSON.stringify(getNested(raw,key2))!==JSON.stringify(getNested(original,key2)),nChanged=all.reduce((n,f)=>n+(changed(f.key)?1:0),0),update=(key2,val)=>{let next2=structuredClone(raw);setNested(next2,key2,val),setRaw(next2),setYaml($stringify(next2))},fmt3=(v2)=>v2===void 0?"\u2014":Array.isArray(v2)?v2.join(", "):String(v2),save2=async()=>{if(managed){toast.show({variant:"error",message:`Managed by ${managed} \u2014 edit configuration.nix`});return}let nErr=Object.keys(err).length;if(nErr>0){toast.show({variant:"error",message:`${nErr} invalid field${nErr===1?"":"s"}`});return}let target=mode==="yaml"?$parse(yaml)??{}:raw,diffs=flatten(target).filter(([key2])=>JSON.stringify(getNested(target,key2))!==JSON.stringify(getNested(original,key2))).map(([key2,val])=>({key:key2,from:getNested(original,key2),to:val}));if(diffs.length===0){toast.show({variant:"info",message:"No changes"});return}let body=diffs.map((d2)=>`${d2.key}: ${fmt3(d2.from)} \u2192 ${fmt3(d2.to)}`).join(`
4123
4123
  `);if(!await openConfirm(dialog,{title:`Write ${diffs.length} change${diffs.length===1?"":"s"} to config.yaml?`,body,yes:"save"}))return;let res=await writeConfig(gw,diffs.map((d2)=>({key:d2.key,to:d2.to})));for(let w2 of res.warnings)toast.show({variant:"info",message:`${w2.key}: ${w2.msg}`});if(load3(),res.failed.length>0){toast.show({variant:"error",message:`${res.failed.length} failed: ${res.failed.map((f)=>f.key).join(", ")}`});return}let landed=diffs.filter((d2)=>res.ok.includes(d2.key)),miss=await verifyWrite(gw,landed.map((d2)=>({key:d2.key,to:d2.to})));if(miss.length>0){toast.show({variant:"error",message:`Write didn't land: ${miss.join(", ")}`});return}let tier=maxEffect(res.ok);if(tier==="restart"){if(await openConfirm(dialog,{title:`Saved \u2014 ${res.ok.length} setting${res.ok.length===1?"":"s"} need a gateway restart`,body:"Restart now? This interrupts any running turn.",yes:"restart now",no:"later",danger:!0}))gw.start(),toast.show({variant:"info",message:"Gateway restarting\u2026"});return}toast.show({variant:"success",message:tier==="live"?"Saved":"Saved \u2014 new sessions pick this up"})},pick=import_react83.useCallback((s)=>{if(managed)return toast.show({variant:"error",message:`Managed by ${managed}`});openModelPicker(dialog,gw,{title:s.kind==="main"?"Set main model":`Set auxiliary \xB7 ${s.label}`,onApply:async(prov,model)=>{let r=await assign(gw,s.key,prov,model);if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});if(toast.show({variant:"success",message:s.kind==="main"?`main \u2192 ${prov} \xB7 ${model}`:`${s.key} \u2192 ${prov} \xB7 ${model}`}),r.warning)toast.show({variant:"warning",message:r.warning});load3()}})},[gw,dialog,toast,load3,managed]),unset=import_react83.useCallback((s)=>{if(managed||s.kind!=="aux"||s.auto)return;resetAux(gw,s.key).then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});toast.show({variant:"success",message:`${s.key} \u2192 auto`}),load3()})},[gw,toast,load3,managed]),unsetAll=import_react83.useCallback(()=>openConfirm(dialog,{title:"Reset all auxiliary slots to auto?",body:`${AUX_TASKS.length} slots. Each falls back to the main model.`,yes:"reset",danger:!0}).then((ok)=>{if(!ok)return;resetAux(gw,"all").then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:`${r.failed.length} failed`});toast.show({variant:"success",message:"All auxiliary slots \u2192 auto"}),load3()})}),[gw,dialog,toast,load3]),keys=useKeys();if(useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(keys.match("config.mode",key2)&&!editing&&!searching){setMode((m2)=>m2==="form"?"yaml":"form");return}if(keys.match("config.save",key2))return void save2();if(mode==="yaml"){if(key2.name==="backspace"){setYaml((prev)=>prev.slice(0,-1));return}if(key2.name==="return"){setYaml((prev)=>prev+`
4124
4124
  `);return}if(key2.raw&&key2.raw.length===1&&key2.raw>=" "){setYaml((prev)=>prev+key2.raw);return}return}if(searching){if(key2.name==="escape"){setSearching(!1),setQuery(""),setCursor(0);return}if(key2.name==="backspace"){setQuery((prev)=>prev.slice(0,-1)),setCursor(0);return}if(key2.name==="up"){setCursor((c)=>Math.max(0,c-1));return}if(key2.name==="down"){setCursor((c)=>Math.min(count3-1,c+1));return}if(key2.raw&&key2.raw.length===1&&key2.raw>=" "){setQuery((prev)=>prev+key2.raw),setCursor(0);return}return}if(editing){let f2=fields[cursor];if(key2.name==="escape"){if(setEditing(!1),setBuf(""),f2)setErr((e)=>{let{[f2.key]:_2,...rest}=e;return rest});return}if(key2.name==="return"){if(f2){let msg=check(f2.key,buf);if(msg){setErr((e)=>({...e,[f2.key]:msg}));return}setErr((e)=>{let{[f2.key]:_2,...rest}=e;return rest});let val=f2.type==="number"?Number(buf)||0:buf;update(f2.key,val)}setEditing(!1),setBuf("");return}if(key2.name==="backspace"){setBuf((prev)=>prev.slice(0,-1));return}if(key2.raw&&key2.raw.length===1){setBuf((prev)=>prev+key2.raw);return}return}if(key2.name==="tab"){setFocus((f2)=>f2==="categories"?"fields":"categories");return}if(keys.match("list.search",key2)){setSearching(!0),setQuery(""),setCursor(0);return}if(focus==="categories"){if(key2.name==="up"){setCat((c)=>{let n=Math.max(0,c-1);return catFollow.opts.scrollTo(n),n}),setCursor(0);return}if(key2.name==="down"){setCat((c)=>{let n=Math.min(groups.length-1,c+1);return catFollow.opts.scrollTo(n),n}),setCursor(0);return}if(key2.name==="return"){setFocus("fields");return}return}if(onSlots){let s=slots[cursor];if(handleListKey(keys,key2,{count:count3,setSel:setCursor,...follow.opts,onActivate:s?()=>pick(s):void 0,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})}})||!s)return;if(key2.raw==="x")return unset(s);if(key2.raw==="X")return void unsetAll();return}let f=fields[cursor],writable=!managed;if(handleListKey(keys,key2,{count:count3,setSel:setCursor,...follow.opts,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onToggle:writable&&f?.type==="boolean"?()=>update(f.key,!f.value):void 0,onActivate:f&&writable&&(f.type==="string"||f.type==="number")?()=>{setEditing(!0),setBuf(String(f.value??""))}:void 0})||!f||!writable)return;if(f.type==="select"&&f.options){let idx=f.options.indexOf(String(f.value));if(key2.raw==="l"||key2.raw==="]"){update(f.key,f.options[(idx+1)%f.options.length]);return}if(key2.raw==="h"||key2.raw==="["){update(f.key,f.options[(idx-1+f.options.length)%f.options.length]);return}}}),mode==="yaml")return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title:"Config \xB7 YAML",children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.text,children:yaml}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})})}),$jsx(HintBar,{pairs:[[keys.print("config.mode"),"form"],[keys.print("config.save"),"save"]]})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,children:[searching?$jsx("box",{height:1,paddingLeft:1,paddingRight:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"}),$jsx("span",{fg:theme.textMuted,children:` ${count3} of ${all.length} \xB7 \u2191\u2193 nav \xB7 Esc close`})]})}):null,$jsxs("box",{flexDirection:"row",flexGrow:1,children:[searching?null:$jsx(TabShell,{title:"Config",grow:1,focus:focus==="categories",children:$jsx("scrollbox",{ref:catFollow.ref,scrollY:!0,flexGrow:1,children:groups.map((c,i)=>{let sel=i===cat,hot=sel&&focus==="categories",items=grouped.get(c)??[],n=c==="models"?slots.length:items.length,catDirty=items.some((f)=>changed(f.key));return $jsx("box",{id:catFollow.id(i),backgroundColor:hot?theme.backgroundElement:void 0,onMouseDown:()=>{setCat(i),setCursor(0),setFocus("categories")},children:$jsxs("text",{children:[$jsx("span",{fg:catDirty?theme.warning:theme.textMuted,children:catDirty?"\u25CF":" "}),$jsxs("span",{fg:hot?theme.accent:sel?theme.primary:theme.text,children:[sel?"\u25B8 ":" ",c]}),$jsx("span",{fg:theme.textMuted,children:` (${n})`})]})},c)})})}),$jsxs(TabShell,{title:onSlots?"models \xB7 applies immediately":searching?"Search":nChanged>0?`${active} \xB7 ${nChanged} unsaved`:active,grow:3,focus:focus==="fields"||searching,children:[managed?$jsxs("box",{height:1,flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.warning,children:"\uD83D\uDD12 managed install \u2014 edit"}),$jsx(FileLink,{source:makeSource("config.yaml"),children:"config.yaml"}),$jsx("text",{fg:theme.warning,children:"via configuration.nix"})]}):null,onSlots?$jsxs("box",{flexDirection:"column",flexGrow:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Auxiliary tasks handle side-jobs. 'auto' = use main model. Per-task api_key/base_url/timeout live in the 'auxiliary' category."})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:slots.map((s,i)=>$jsx(SlotRow,{id:follow.id(i),s,on:i===cursor&&focus==="fields"},s.key))})]},"slots"):$jsxs($Fragment,{children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),searching?$jsx(Col,{w:12,fg:theme.textMuted,bold:!0,children:"Category"}):null,$jsx(Col,{w:40,fg:theme.textMuted,bold:!0,children:"Field"}),$jsx(Col,{grow:!0,min:6,fg:theme.textMuted,bold:!0,children:"Value"}),$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:9,fg:theme.textMuted,children:""})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching fields":"No fields in this category"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{if(s.head!==null)acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",s.head," "]})},`\xA7${s.head}`));return s.items.forEach((f,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(FieldRow,{id:follow.id(i),field:f,active:i===cursor&&(focus==="fields"||searching),changed:changed(f.key),editing:editing&&i===cursor,buf,readonly:!!managed,error:err[f.key],badge:searching?groupOf(f.key):void 0},f.key))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]})]})]}),managed?$jsx(HintBar,{raw:`read-only \xB7 managed by ${managed}`}):onSlots?$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],["Enter","pick"],["x","reset"],["X","reset-all"],["Tab","categories"]]}):focus==="categories"&&!searching?$jsx(HintBar,{pairs:[["\u2191\u2193","select"],["Tab","fields"]]}):$jsx(HintBar,{pairs:[[keys.print("config.mode"),"yaml"],["Tab","categories"],["\u2191\u2193","nav"],[keys.print("list.search"),"search"],[keys.print("config.save"),"save"]],suffix:nChanged>0?`\u25CF ${nChanged} unsaved`:void 0})]})});var import_react87=__toESM(require_react_production(),1);var import_react85=__toESM(require_react_production(),1);var iso2=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},parseList=(stdout)=>stdout.split(`
4125
- `).map((s)=>s.trim()).filter((s)=>s.length>0&&!s.startsWith("(")),CuratorDialog=()=>{let{theme,syntaxStyle}=useTheme(),gw=useGateway(),toast=useToast(),dialog=useDialog(),state2=useHome("curatorState"),cfg=useHome("config")?.curator,[report2,setReport]=import_react85.useState(null),[loaded,setLoaded]=import_react85.useState(!1),[busy,setBusy]=import_react85.useState(null),[archived,setArchived]=import_react85.useState([]),[mode,setMode]=import_react85.useState("report"),[sel,setSel]=import_react85.useState(0),sb=import_react85.useRef(null);import_react85.useEffect(()=>{readLatestCuratorReport().then((r)=>{setReport(r),setLoaded(!0)}).catch(()=>setLoaded(!0))},[]);let refreshArchived=import_react85.useCallback(()=>{gw.request("shell.exec",{command:"hermes curator list-archived"}).then((r)=>{if(r.code===0)setArchived(parseList(r.stdout))}).catch(()=>{})},[gw]);import_react85.useEffect(()=>{refreshArchived()},[refreshArchived]);let sh=import_react85.useCallback((verb,ok)=>{if(busy)return;setBusy(verb),gw.request("shell.exec",{command:`hermes curator ${verb}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:ok}),home2.invalidate("curatorState")}).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]),restore=import_react85.useCallback((name)=>{if(busy)return;setBusy("restore"),gw.request("shell.exec",{command:`hermes curator restore ${name}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:`Restored ${name}`}),setArchived((prev)=>prev.filter((n)=>n!==name)),setSel((s)=>Math.max(0,s-1))}).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]);useKeyboard((key2)=>{if(mode==="archived"){if(key2.name==="escape"){setMode("report");return}if(key2.raw==="a"){setMode("report");return}if(key2.name==="up")return setSel((s)=>Math.max(0,s-1));if(key2.name==="down")return setSel((s)=>Math.min(archived.length-1,s+1));if(key2.name==="return"){let name=archived[sel];if(name)restore(name);return}return}if(key2.name==="escape")return dialog.clear();if(key2.raw==="r")return sh("run","Curator run started (background)");if(key2.raw==="p")return state2?.paused?sh("resume","Curator resumed"):sh("pause","Curator paused");if(key2.raw==="a"&&archived.length>0)setSel(0),setMode("archived")}),import_react85.useEffect(()=>{if(mode==="archived")sb.current?.scrollChildIntoView(`arch-${sel}`)},[sel,mode]);let last3=iso2(state2?.last_run_at??null),due=last3&&cfg?last3+cfg.interval_hours*3600:null,status=cfg?.enabled===!1?"disabled":state2?.paused?"paused":"enabled",tint=status==="enabled"?theme.success:status==="paused"?theme.warning:theme.textMuted;return $jsxs("box",{flexDirection:"column",width:120,height:34,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Curator"})}),$jsx("span",{fg:tint,children:` \xB7 ${status}`})]}),busy?$jsx("box",{marginLeft:2,children:$jsx(Spinner,{color:theme.textMuted,label:busy})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:state2?`${state2.run_count} run${state2.run_count===1?"":"s"}${last3?" \xB7 last "+ago(last3):" \xB7 never"} \xB7 Esc to close`:"No curator state yet \xB7 Esc to close"})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:40,height:"100%",flexShrink:0,children:[$jsx(KVBlock,{rows:[["Next run",status!=="enabled"?`\u2014 (${status})`:due?until(due):"when idle"],["Last run",last3?ago(last3):"never"],["Duration",state2?.last_run_duration_seconds?dur2(state2.last_run_duration_seconds):void 0],["Archived",archived.length>0?String(archived.length):void 0]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Config \xB7 edit in Config tab"})}),$jsx(KVBlock,{rows:[["Interval",cfg?`${cfg.interval_hours}h`:"\u2014"],["Stale after",cfg?`${cfg.stale_after_days}d`:"\u2014"],["Archive after",cfg?`${cfg.archive_after_days}d`:"\u2014"]]}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"r "}),$jsx("span",{fg:theme.text,children:"run now"}),$jsx("span",{fg:theme.textMuted,children:" (background)"})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"p "}),$jsx("span",{fg:theme.text,children:state2?.paused?"resume":"pause"})]})}),archived.length>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"a "}),$jsx("span",{fg:theme.text,children:"archived skills"}),$jsx("span",{fg:theme.textMuted,children:` (${archived.length})`})]})}):null]}),state2?.last_run_summary?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Last run"})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("markdown",{content:state2.last_run_summary,fg:theme.markdownText,syntaxStyle})})]}):null]}),mode==="archived"?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Archived skills (${archived.length})`})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191\u2193 select \xB7 Enter restore \xB7 a/Esc back to report"})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,contentOptions:{flexDirection:"column"},children:archived.length===0?$jsx("text",{fg:theme.textMuted,children:"No archived skills."}):archived.map((name,i)=>$jsx("box",{id:`arch-${i}`,height:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>restore(name),children:$jsxs("text",{fg:i===sel?theme.text:theme.textMuted,children:[i===sel?"\u25B8 ":" ",name]})},name))})]}):!loaded?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading report\u2026"})}):report2?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Report \xB7 ${report2.runId}`})})}),$jsx(KVLink,{label:"File",source:report2.source,text:report2.source.relative}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx("markdown",{content:report2.content||"(empty)",fg:theme.markdownText,syntaxStyle})})})]}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No runs yet \u2014 curator has not completed a cycle."})})]})]})},openCurator=(dialog)=>dialog.replace($jsx(CuratorDialog,{}),void 0,{ownCancel:!0});var NO_EVENTS=[],iso3=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},SkillRow=import_react87.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,bg2=props.selected?theme.backgroundElement:void 0,used=iso3(u3?.last_used_at)??iso3(u3?.last_viewed_at),stale=u3?.state==="stale",archived=u3?.state==="archived";return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:theme.warning,children:u3?.pinned?"\uD83D\uDCCC":" "}),$jsx(Marquee,{grow:!0,min:8,active:props.selected,fg:archived?theme.textMuted:props.selected?theme.accent:theme.text,children:s.name}),archived?$jsx(Col,{w:10,fg:theme.textMuted,children:"archived"}):stale?$jsx(Col,{w:10,fg:theme.warning,children:"stale"}):$jsx(Col,{w:10,fg:theme.textMuted,children:used?ago(used):""})]})}),HitRow=import_react87.memo((props)=>{let theme=useTheme().theme,on=props.selected;return $jsxs("box",{flexDirection:"row",height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:on?theme.accent:theme.text,children:props.hit.name}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,children:props.hit.description||"\u2014"})]})}),line2=(e)=>{switch(e.kind){case"absorbed":return`absorbed ${e.sources.map((s)=>`\`${s}\``).join(", ")}`;case"merged":return`merged into \`${e.into}\`${e.reason?` \u2014 ${e.reason}`:""}`;case"transition":return`${e.from} \u2192 ${e.to}`;case"pruned":return`pruned${e.reason?` \u2014 ${e.reason}`:""}`;case"added":return"created by curator"}},DetailPanel2=import_react87.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,used=iso3(u3?.last_used_at),viewed=iso3(u3?.last_viewed_at),patched=iso3(u3?.last_patched_at);return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Detail"})}),u3?.pinned?$jsx("span",{fg:theme.warning,children:" \uD83D\uDCCC pinned"}):null,u3?.state==="stale"?$jsx("span",{fg:theme.warning,children:" \xB7 stale"}):null,u3?.state==="archived"?$jsx("span",{fg:theme.textMuted,children:" \xB7 archived"}):null]})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:s.name})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Category",s.category||"uncategorized",theme.info],["Tags",s.tags.length>0?s.tags.join(", "):void 0],u3?["Used",u3.use_count>0?`${u3.use_count}\xD7 \xB7 last ${used?ago(used):"never"}`:"never"]:null,u3&&viewed?["Viewed",`${u3.view_count}\xD7 \xB7 last ${ago(viewed)}`]:null,u3&&patched?["Patched",`${u3.patch_count}\xD7 \xB7 last ${ago(patched)}`]:null].filter(Boolean)}),$jsx(KVLink,{label:"File",source:s.source,text:s.source.relative}),$jsx("box",{height:1}),s.description?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:s.description})}):$jsx("text",{fg:theme.textMuted,children:"No description"}),props.events.length>0?$jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Curator lineage"})}),props.events.map((e,i)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:ago(e.at)})}),$jsx("box",{flexGrow:1,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:line2(e)})})]},i))]}):u3?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No curator events for this skill"})}):null]})}),EmptyState=import_react87.memo((props)=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:props.searching?"No matching skills on hub":"No skills found in ~/.hermes/skills/"})})})}),HistoryPanel=import_react87.memo((props)=>{let{theme,syntaxStyle}=useTheme(),keys=useKeys(),follow=useFollow("skills-history"),[runs,setRuns]=import_react87.useState(()=>listCuratorRuns()),[sel,setSel]=import_react87.useState(0),[open2,setOpen]=import_react87.useState(!1),[body,setBody]=import_react87.useState(""),run=runs[sel];import_react87.useEffect(()=>{if(!open2||!run)return;let live=!0;return readCuratorReport(run.id).then((t2)=>{if(live)setBody(t2)}),()=>{live=!1}},[open2,run?.id]);let moveSel=import_react87.useCallback((v2)=>{setOpen(!1),setSel(v2)},[]);return useKeyboard((key2)=>{if(!props.focused)return;handleListKey(keys,key2,{count:runs.length,setSel:moveSel,...follow.opts,onActivate:()=>setOpen((o)=>!o),onRefresh:()=>setRuns(listCuratorRuns())})}),$jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:props.focused?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Curator History"})}),$jsx("span",{fg:theme.textMuted,children:` ${runs.length} run${runs.length===1?"":"s"}${runs[0]?` \xB7 last ${ago(runs[0].at)}`:""}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select \xB7 Enter expand \xB7 ${keys.print("list.refresh")} reload \xB7 h close`})}),$jsx("box",{height:1}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:"no runs in ~/.hermes/logs/curator/"}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:runs.map((r,i)=>{let on=i===sel;return $jsxs("box",{id:follow.id(i),flexDirection:"column",children:[$jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),setOpen((o)=>i===sel?!o:!0)},children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:12,fg:on?theme.accent:theme.text,children:ago(r.at)}),$jsx(Col,{grow:!0,fg:theme.textMuted,children:`${r.before}\u2192${r.after} arch ${r.archived} cons ${r.consolidated}${r.added?` +${r.added}`:""}`})]}),on&&open2?$jsx("box",{marginLeft:2,marginTop:1,marginBottom:1,children:$jsx("markdown",{content:body||"\u2026",fg:theme.markdownText,syntaxStyle})}):null]},r.id)})})})]})}),Skills=import_react87.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),usage=useHome("skillUsage")??{},curator=useHome("curatorState"),lineage2=import_react87.useRef(indexCuratorLineage());import_react87.useEffect(()=>{lineage2.current=indexCuratorLineage()},[curator?.run_count]);let[skills,setSkills]=import_react87.useState([]),[selected,setSelected]=import_react87.useState(0),[searching,setSearching]=import_react87.useState(!1),[query,setQuery]=import_react87.useState(""),[hits,setHits]=import_react87.useState([]),[sort,setSort]=import_react87.useState("name"),[history,setHistory]=import_react87.useState(!1),seq=import_react87.useRef(0),load3=import_react87.useCallback(()=>{gw.request("skills.manage",{action:"list"}).then((res)=>{let raw=res.skills??{},rows3=Object.entries(raw).flatMap(([cat,names])=>names.map((n)=>{let source=makeSource(`skills/${cat}/${n}/SKILL.md`,`${n}/SKILL.md`),fm=readSkillFrontmatter(source);return{source,category:cat,name:n,description:fm.description,tags:fm.tags,tokenEstimate:count2(`${n} ${fm.description}`)}}));rows3.sort((a,b2)=>a.source.relative.localeCompare(b2.source.relative)),setSkills(rows3)}).catch(()=>{})},[gw]);import_react87.useEffect(()=>{load3()},[load3]),import_react87.useEffect(()=>{let id=++seq.current;if(!searching||!query.trim()){setHits([]);return}let t2=setTimeout(()=>{gw.request("skills.manage",{action:"search",query}).then((r)=>{if(seq.current!==id)return;setHits(r.results??[]),setSelected(0)}).catch(()=>{if(seq.current===id)setHits([])})},150);return()=>clearTimeout(t2)},[gw,query,searching]);let flat=[...sort==="used"?new Map([["by recency",[...skills].sort((a,b2)=>{let ta=iso3(usage[a.name]?.last_used_at)??iso3(usage[a.name]?.last_viewed_at)??0;return(iso3(usage[b2.name]?.last_used_at)??iso3(usage[b2.name]?.last_viewed_at)??0)-ta})]]):Map.groupBy(skills,(s)=>s.category||"uncategorized")].flatMap(([cat,items])=>[{type:"header",category:cat},...items.map((s)=>({type:"skill",skill:s}))]),skillRows=flat.filter((r)=>r.type==="skill"),count3=searching?hits.length:skillRows.length,current=!searching&&skillRows[selected]?.type==="skill"?skillRows[selected].skill:null,follow=useFollow("sk"),exit=import_react87.useCallback(()=>{setSearching(!1),setQuery(""),setHits([]),setSelected(0)},[]),install2=import_react87.useCallback(async(name)=>{if(!await openConfirm(dialog,{title:"Install skill?",body:name,yes:"install"}))return;gw.request("skills.manage",{action:"install",query:name}).then(()=>{toast.show({variant:"success",message:`Installed ${name}`}),exit(),load3()}).catch((e)=>toast.show({variant:"error",message:`Install failed: ${e.message}`}))},[dialog,gw,toast,exit,load3]),keys=useKeys();useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(searching){if(key2.name==="escape"){exit();return}if(key2.name==="backspace"){setQuery((p)=>p.slice(0,-1)),setSelected(0);return}if(key2.name==="up")return setSelected((p)=>Math.max(0,p-1));if(key2.name==="down")return setSelected((p)=>Math.min(count3-1,p+1));if(key2.name==="return"){let hit=hits[selected];if(hit)install2(hit.name);return}if(key2.raw&&key2.raw.length===1&&key2.raw>=" ")setQuery((p)=>p+key2.raw),setSelected(0);return}if(!key2.ctrl&&!key2.meta&&key2.raw==="s"){setSort((p)=>p==="name"?"used":"name"),setSelected(0);return}if(!key2.ctrl&&!key2.meta&&key2.raw==="c"){openCurator(dialog);return}if(!key2.ctrl&&!key2.meta&&key2.raw==="h"){setHistory((h2)=>!h2);return}if(history){if(key2.name==="escape")return setHistory(!1);return}handleListKey(keys,key2,{count:count3,setSel:setSelected,...follow.opts,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onSearch:()=>{setSearching(!0),setQuery(""),setHits([]),setSelected(0)}})});let skillIdx=-1;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Hub Search (${hits.length})`:`Skills (${skills.length}${sort==="used"?" \xB7 by use":""})`,children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,searching?null:$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,bold:!0,children:"Name"})]}),searching?null:$jsx("box",{height:1}),count3===0?$jsx(EmptyState,{searching}):searching?$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:hits.map((h2,i)=>$jsx(HitRow,{hit:h2,selected:i===selected,onHover:()=>setSelected(i)},h2.name))})}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:flat.map((row2,i)=>{if(row2.type==="header")return $jsx("box",{marginTop:i>0?1:0,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE ${row2.category}`})})},`h-${row2.category}`);skillIdx++;let idx=skillIdx;return $jsx(SkillRow,{id:follow.id(idx),skill:row2.skill,usage:usage[row2.skill.name],selected:idx===selected,onSelect:()=>setSelected(idx),onHover:()=>setSelected(idx)},row2.skill.name)})}),!searching&&curator?$jsx("box",{height:1,flexShrink:0,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"curator \xB7 "}),curator.paused?$jsx("span",{fg:theme.warning,children:"paused"}):curator.last_run_at?$jsx("span",{fg:theme.textMuted,children:`${curator.run_count} run${curator.run_count===1?"":"s"} \xB7 last ${ago(iso3(curator.last_run_at)??0)}`}):$jsx("span",{fg:theme.textMuted,children:"never run"})]})}):null]}),history?$jsx(HistoryPanel,{focused:!!props.focused&&!searching}):current?$jsx(DetailPanel2,{skill:current,usage:usage[current.name],events:lineage2.current.get(current.name)??NO_EVENTS}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter","install"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],[keys.print("list.search"),"search hub"],["s","sort"],["c","curator"],["h","history"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react89=__toESM(require_react_production(),1);var kindOf=(ts)=>ts.name.includes(":")?"mcp":ts.name.startsWith("hermes-")?"platform":"core",KIND_LABEL={core:"core",platform:"platform bundles",mcp:"mcp"},group=(list2)=>{let by={core:[],platform:[],mcp:[]};for(let ts of list2)by[kindOf(ts)].push(ts);return["core","platform","mcp"].filter((k2)=>by[k2].length>0).map((k2)=>({kind:k2,items:by[k2]}))},Row2=import_react89.memo((props)=>{let theme=useTheme().theme,ts=props.ts,bg2=props.selected?theme.backgroundElement:void 0,unavail=ts.available===!1,glyph=unavail?"\u25CC":ts.enabled?"\u25CF":"\u25CB",glyphFg=unavail?theme.warning:ts.enabled?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphFg,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:ts.name}),$jsx(Col,{w:9,fg:theme.info,right:!0,children:`${ts.tool_count} tools`})]})}),DetailPanel3=import_react89.memo((props)=>{let theme=useTheme().theme,ts=props.ts,unavail=ts.available===!1;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"40%",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:ts.name})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:KIND_LABEL[kindOf(ts)]})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",unavail?"unavailable":ts.enabled?"enabled":"disabled",unavail?theme.warning:ts.enabled?theme.success:theme.textMuted],["Tools",String(ts.tool_count),theme.info],["Includes",ts.includes?.length?ts.includes.join(", "):void 0,theme.text],["Requires",ts.requirements?.length?ts.requirements.join(", "):void 0,unavail?theme.warning:theme.text]]}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:ts.description||"\u2014"})}),ts.tools?.length?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Tools (",ts.tools.length,"):"]})}),$jsx("scrollbox",{flexGrow:1,scrollY:!0,children:ts.tools.map((n)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",n]},n))})]}):null]})}),Toolsets=import_react89.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),[list2,setList]=import_react89.useState([]),[sel,setSel]=import_react89.useState(0),[err,setErr]=import_react89.useState(null),secs=group(list2),flat=secs.flatMap((s)=>s.items),live=import_react89.useRef({flat,sel});live.current={flat,sel};let load3=import_react89.useCallback(()=>{gw.request("toolsets.list",{}).then((r)=>{setList(r.toolsets??[]),setErr(null)}).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]);import_react89.useEffect(()=>{load3()},[load3]);let toggle=import_react89.useCallback(()=>{let ts2=live.current.flat[live.current.sel];if(!ts2)return;if(ts2.available===!1){toast.show({variant:"warning",message:`${ts2.name} is unavailable`});return}let action=ts2.enabled?"disable":"enable",was=ts2.enabled;setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:!t2.enabled}:t2)),gw.request("tools.configure",{action,names:[ts2.name]}).then((r)=>{if(r.unknown?.includes(ts2.name)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`${ts2.name} is not configurable`});return}if(r.missing_servers?.length&&ts2.name.includes(":")){let server=ts2.name.split(":",1)[0];if(r.missing_servers.includes(server)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`MCP server '${server}' not in config`});return}}if(Array.isArray(r.enabled_toolsets)){let on=new Set(r.enabled_toolsets);setList((prev)=>prev.map((t2)=>({...t2,enabled:on.has(t2.name)})))}else load3()}).catch((e)=>{setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"error",message:e.message})})},[gw,toast,load3]),count3=flat.length,ts=flat[sel]??null,follow=useFollow("ts"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:count3,setSel,...follow.opts,onToggle:toggle,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})}});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:`Toolsets (${count3})`,error:err,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:9,fg:theme.textMuted,bold:!0,right:!0,children:"Tools"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:"No toolsets found"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{return acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",KIND_LABEL[s.kind]," (",s.items.length,") "]})},`\xA7${s.kind}`)),s.items.forEach((t2,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(Row2,{id:follow.id(i),ts:t2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},t2.name))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]}),ts?$jsx(DetailPanel3,{ts}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.toggle"),"toggle"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react90=__toESM(require_react_production(),1);var mask=(val)=>"\u2022".repeat(Math.min(val.length,12)),VarRow=import_react90.memo((props)=>{let theme=useTheme().theme,set2=props.value!==void 0,bg2=props.selected?theme.backgroundElement:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onClick,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:props.selected?theme.accent:theme.text,children:props.name}),$jsx(Col,{w:8,fg:set2?theme.success:theme.textMuted,children:set2?" SET ":"UNSET"}),$jsx(Col,{grow:!0,min:4,fg:props.shown?theme.text:theme.textMuted,children:set2?props.shown?props.value:mask(props.value):"\u2014"})]})}),Env=import_react90.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),vars=useHome("env")??{},[sel,setSel]=import_react90.useState(0),[reveal,setReveal]=import_react90.useState(new Set),[collapsed,setCollapsed]=import_react90.useState({}),[searching,setSearching]=import_react90.useState(!1),[query,setQuery]=import_react90.useState(""),known=new Set(ENV_CATALOG.flatMap((g)=>g.keys)),extra=Object.keys(vars).filter((k2)=>!known.has(k2)).sort(),rows3=(extra.length>0?[...ENV_CATALOG,{category:"Other",keys:extra}]:ENV_CATALOG).flatMap((g)=>{let keys2=searching&&query.trim()?g.keys.filter((k2)=>k2.toLowerCase().includes(query.toLowerCase())):g.keys;if(keys2.length===0)return[];let hide=collapsed[g.category]??!1,header={type:"header",category:g.category,collapsed:hide};if(hide)return[header];return[header,...keys2.map((key2)=>({type:"var",key:key2,value:vars[key2]}))]}),count3=rows3.length,cur=rows3[sel],setKeys=rows3.flatMap((r)=>r.type==="var"&&r.value!==void 0?[r.key]:[]),follow=useFollow("env"),edit=import_react90.useCallback(async(key2,initial)=>{let val=await openTextPrompt(dialog,{title:`Edit ${key2}`,label:"Value",initial});if(val==null)return;await writeEnvVar(key2,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key2} saved`})},[dialog,toast]),add=import_react90.useCallback(async()=>{let key2=await openTextPrompt(dialog,{title:"New Variable",label:"Name (e.g. FOO_API_KEY)"});if(!key2)return;let val=await openTextPrompt(dialog,{title:`Set ${key2}`,label:"Value"});if(val==null)return;await writeEnvVar(key2,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key2} added`})},[dialog,toast]),del=import_react90.useCallback(async(key2)=>{if(!await openConfirm(dialog,{title:"Delete Variable",body:`Remove ${key2} from .env?`,yes:"delete",danger:!0}))return;await removeEnvVar(key2),home2.invalidate("env"),toast.show({variant:"success",message:`${key2} removed`})},[dialog,toast]),revealAll=import_react90.useCallback(()=>setReveal((s)=>s.size===setKeys.length&&setKeys.length>0?new Set:new Set(setKeys)),[setKeys]),activateAt=import_react90.useCallback((i)=>{let r=rows3[i];if(r?.type==="header")return setCollapsed((p)=>({...p,[r.category]:!p[r.category]}));if(r?.type==="var"){if(r.value!==void 0&&!reveal.has(r.key))return setReveal((s)=>new Set(s).add(r.key));return void edit(r.key,r.value??"")}},[rows3,reveal,edit]),activate=import_react90.useCallback(()=>activateAt(sel),[activateAt,sel]),rowClick=import_react90.useCallback((i)=>{setSel(i),activateAt(i)},[activateAt]),keys=useKeys();return useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(searching){if(key2.name==="escape"){setSearching(!1),setQuery(""),setSel(0);return}if(key2.name==="backspace"){setQuery((q4)=>q4.slice(0,-1)),setSel(0);return}if(key2.name==="up")return setSel((p)=>Math.max(0,p-1));if(key2.name==="down")return setSel((p)=>Math.min(count3-1,p+1));if(key2.name==="return")return setSearching(!1),activate();if(key2.raw&&key2.raw.length===1&&key2.raw>=" "){setQuery((q4)=>q4+key2.raw),setSel(0);return}return}handleListKey(keys,key2,{count:count3,setSel,...follow.opts,onActivate:activate,onToggle:revealAll,onNew:add,onDelete:()=>{if(cur?.type==="var"&&cur.value!==void 0)del(cur.key)},onSearch:()=>{setSearching(!0),setQuery(""),setSel(0)},onRefresh:()=>{home2.invalidate("env"),toast.show({variant:"info",message:"Reloaded",duration:1000})}})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:searching?"Env (searching)":"Env / API Keys",children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:28,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:8,fg:theme.textMuted,bold:!0,children:"Status"}),$jsx(Col,{grow:!0,min:4,fg:theme.textMuted,bold:!0,children:"Value"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching variables":"No variables configured"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((row2,i)=>row2.type==="header"?$jsx("box",{id:follow.id(i),marginTop:i>0?1:0,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>rowClick(i),children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`${row2.collapsed?"\u25B8":"\u25BE"} ${row2.category}`})})},`h-${row2.category}`):$jsx(VarRow,{id:follow.id(i),name:row2.key,value:row2.value,shown:reveal.has(row2.key),selected:i===sel,onHover:()=>setSel(i),onClick:()=>rowClick(i)},row2.key))})},"list")]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","move"],["Enter","reveal/edit"],["Esc","cancel"]]:[["\u2191\u2193","move"],[keys.print("list.activate"),"reveal/edit"],[keys.print("list.toggle"),"show-all"],[keys.print("list.new"),"new"],[keys.print("list.delete"),"delete"],[keys.print("list.search"),"search"],[keys.print("list.refresh"),"reload"]]})]})});var import_react92=__toESM(require_react_production(),1);function usageColor(pct,theme){if(pct>=95)return theme.error;if(pct>=80)return theme.warning;return theme.success}function bar2(pct,w2){let filled=Math.round(pct/100*w2);return"\u2588".repeat(filled)+"\u2591".repeat(w2-filled)}var DESC={builtin:"File-based \xA7-delimited entries (MEMORY.md + USER.md). Always active.",mem0:"Server-side LLM fact extraction with semantic search and reranking.",honcho:"AI-native cross-session user modeling with dialectic Q&A.",hindsight:"Knowledge graph with entity resolution and multi-strategy retrieval.",holographic:"Local SQLite fact store with FTS5, trust scoring, HRR retrieval.",openviking:"Session-managed memory with tiered retrieval.",retaindb:"Cloud memory API with hybrid search and 7 memory types.",byterover:"Persistent knowledge tree via brv CLI.",supermemory:"Semantic long-term memory with profile recall and session ingest."},Memory=import_react92.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),gw=useGateway(),[sel,setSel]=import_react92.useState(0),config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),providers=useHome("memoryProviders")??[],activity=useHome("memoryActivity")??[],cfg=config?.memory,active=cfg?.provider||"",cur=providers[sel],on=!!cur&&(cur.name==="builtin"||cur.name===active),toggle=async()=>{if(!cur||cur.name==="builtin")return;let isOn=cur.name===active;if(!await openConfirm(dialog,{title:isOn?"Deactivate memory provider?":"Activate memory provider?",body:isOn?`Clear '${cur.name}' as the active provider (revert to built-in only).`:`Set '${cur.name}' as the active provider. Ensure required env vars are set (Env tab).`,yes:isOn?"deactivate":"activate"}))return;let{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"memory.provider",to:isOn?"":cur.name}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),home2.invalidate("memoryProviders"),toast.show({variant:"success",message:isOn?"Deactivated":`Activated ${cur.name} \u2014 new sessions pick this up`})},keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:providers.length,setSel,onToggle:toggle,onRefresh:()=>{home2.invalidate("memoryProviders"),home2.invalidate("memoryActivity"),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),feed=!cur?[]:cur.name==="builtin"?activity:activity.filter((a)=>a.provider===cur.name);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:"Memory Providers",grow:1,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:providers.map((p,i)=>{let pOn=p.name==="builtin"||p.name===active,has=Object.keys(p.config).length>0,dot=pOn?"\u25CF":has?"\u25D0":"\u25CB",fg2=pOn?theme.success:has?theme.warning:theme.textMuted,tag=pOn?"active":has?"configured":"";return $jsxs("box",{flexDirection:"column",marginBottom:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseDown:()=>setSel(i),onMouseMove:()=>setSel(i),children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[dot," "]}),$jsx("span",{fg:i===sel?theme.accent:theme.text,children:p.name}),tag?$jsxs("span",{fg:fg2,children:[" (",tag,")"]}):null]})}),$jsx("box",{height:1,overflow:"hidden",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:DESC[p.name]||"\u2014"})})]},p.name)})})}),$jsx(TabShell,{title:cur?.name??"Provider",grow:2,children:cur?$jsx(ProviderDetail,{provider:cur,active,cfg,memory,userProfile,feed}):$jsx("text",{fg:theme.textMuted,children:"Select a provider"})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.toggle"),"activate"]],suffix:on?"\u25CF active":"\u25CB inactive"})]})}),ProviderDetail=import_react92.memo((props)=>{let theme=useTheme().theme,p=props.provider,on=p.name==="builtin"||p.name===props.active;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:DESC[p.name]||"Memory provider"})}),$jsx("box",{height:1}),p.name==="builtin"?$jsxs("box",{flexDirection:"column",children:[props.cfg?$jsxs($Fragment,{children:[$jsx(KVBlock,{rows:[["Notes",props.cfg.memory_enabled?"enabled":"disabled",props.cfg.memory_enabled?theme.success:theme.error],["Profile",props.cfg.user_profile_enabled?"enabled":"disabled",props.cfg.user_profile_enabled?theme.success:theme.error]]}),$jsx("box",{height:1})]}):null,$jsx(CapacityBar,{title:"Notes (MEMORY.md)",info:props.memory??null}),$jsx("box",{height:1}),$jsx(CapacityBar,{title:"Profile (USER.md)",info:props.userProfile??null})]}):null,p.name!=="builtin"&&on&&props.cfg?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Agent Settings"})})}),$jsx(KVBlock,{rows:[["Nudge",`every ${props.cfg.nudge_interval} turns`],["Flush",`after ${props.cfg.flush_min_turns} turns`]]}),$jsx("box",{height:1})]}):null,Object.keys(p.config).length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Local Configuration"})})}),$jsx(KVBlock,{rows:Object.entries(p.config).map(([k2,v2])=>[k2,String(v2)])})]}):p.name!=="builtin"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No local config found. Run `hermes memory setup` to configure."})}):null,$jsx(ActivityFeed,{items:props.feed,own:p.name})]})})}),OP_GLYPH={write:"+",read:"?"},ActivityFeed=import_react92.memo((props)=>{let theme=useTheme().theme,all=props.own==="builtin",nW=props.items.filter((a)=>a.op==="write").length;return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"Recent Activity"})}),props.items.length?$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",nW," writes, ",props.items.length-nW," reads"]}):null]})}),props.items.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No memory-tool calls in the last ~2000 messages"})}):null,props.items.map((a,i)=>$jsx("box",{height:1,flexDirection:"row",overflow:"hidden",children:$jsxs("text",{children:[$jsxs("span",{fg:a.op==="write"?theme.success:theme.textMuted,children:[OP_GLYPH[a.op]," "]}),$jsx("span",{fg:theme.textMuted,children:ago(a.ts).padEnd(8)}),all&&a.provider!=="builtin"?$jsxs("span",{fg:theme.primary,children:[a.provider,"\xB7"]}):null,$jsx("span",{fg:theme.text,children:a.verb}),$jsxs("span",{fg:theme.textMuted,children:[" ",a.summary]})]})},i))]})}),CapacityBar=import_react92.memo((props)=>{let theme=useTheme().theme;if(!props.info)return $jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.title,": unavailable"]})});let color=usageColor(props.info.usagePercent,theme);return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:props.title}),$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",props.info.entryCount," entries"]})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:color,children:bar2(props.info.usagePercent,20)}),$jsxs("span",{fg:theme.textMuted,children:[" ",props.info.charCount,"/",props.info.charLimit," (",props.info.usagePercent,"%)"]})]})})]})});var ConfigGroup=import_react93.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[CONFIG_TAB];import_react93.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(Pane3,{visible:props.sub===0,children:$jsx(Config,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane3,{visible:props.sub===1,children:$jsx(Skills,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane3,{visible:props.sub===2,children:$jsx(Toolsets,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane3,{visible:props.sub===3,children:$jsx(Env,{focused:!!props.focused&&props.sub===3})}),$jsx(Pane3,{visible:props.sub===4,children:$jsx(Memory,{focused:!!props.focused&&props.sub===4})})]})]})}),Pane3=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:children2}):null;var import_react98=__toESM(require_react_production(),1);var import_react94=__toESM(require_react_production(),1);import{readFileSync as readFileSync7}from"fs";import{basename as basename10}from"path";var exports_eikon={};__export(exports_eikon,{writeStudio:()=>writeStudio,studioFile:()=>studioFile,sourceDir:()=>sourceDir,save:()=>save2,revision:()=>revision,remove:()=>remove2,register:()=>register,readStudio:()=>readStudio,rasterizers:()=>rasterizers,rasterizer:()=>rasterizer,probe:()=>probe,pick:()=>pick,peekSource:()=>peekSource,parseEikon:()=>parseEikon,onRevision:()=>onRevision,onRegistry:()=>onRegistry,list:()=>list2,header:()=>header,findSource:()=>findSource,file:()=>file,fetchSource:()=>fetchSource,ensure:()=>ensure,eikon:()=>exports_eikon,dir:()=>dir,baked:()=>baked,adopt:()=>adopt});import{existsSync as existsSync14,mkdirSync as mkdirSync4,readdirSync as readdirSync6,copyFileSync as copyFileSync2,readFileSync as readFileSync6,writeFileSync as writeFileSync4,rmSync as rmSync3}from"fs";import{join as join12,extname as extname3,basename as basename9}from"path";import{existsSync as existsSync13}from"fs";import{join as join11,dirname as dirname6}from"path";var locate2=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join11(d2,"assets/eikons");if(existsSync13(p))return p;let up=dirname6(d2);if(up===d2)break;d2=up}return join11(import.meta.dir,"../../../assets/eikons")},BUNDLED_EIKON_DIR=locate2();function bundledEikonPath(name){if(!name)return;let p=join11(BUNDLED_EIKON_DIR,`${name}.eikon`);return existsSync13(p)?p:void 0}import{deflateSync}from"zlib";import{spawnSync as spawnSync2}from"child_process";import{statSync as statSync5}from"fs";var W2=48,H=24,FPS0=16,MAXF=256,S0={zoom:1,ox:0.5,oy:0.5},defaults=(r)=>Object.fromEntries(Object.entries(r.knobs).map(([k2,d2])=>[k2,d2.default])),caps={chafa:chafaBin(),ffmpeg:spawnSync2("ffmpeg",["-version"],{stdio:"ignore"}).status===0,ffprobe:spawnSync2("ffprobe",["-version"],{stdio:"ignore"}).status===0};function probe(path7){if(!caps.ffprobe)return null;let r=spawnSync2("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",path7],{encoding:"utf8"});if(r.status!==0)return null;let m2=r.stdout.trim().match(/^(\d+),(\d+)/);return m2?{w:+m2[1],h:+m2[2]}:null}var clamp=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),SCALE=384,PLANE=SCALE*SCALE,VID=/\.(mp4|webm|mov|mkv|m4v|gif)$/i,clips=new Map,CLIP_CAP=8;function decode(src2,fps=FPS0){let full=resolveImage(src2);if(!full)return Promise.resolve(`not found: ${src2}`);let mt=statSync5(full,{throwIfNoEntry:!1})?.mtimeMs??0,key2=`${full}:${mt}:${fps}`,got=clips.get(key2);if(got)return clips.delete(key2),clips.set(key2,got),got;if(!caps.ffmpeg)return Promise.resolve("ffmpeg not installed");let video=VID.test(full),vf=[...video?[`fps=${fps}`]:[],`scale=${SCALE}:${SCALE}:force_original_aspect_ratio=increase`,`crop=${SCALE}:${SCALE}`].join(","),p=(async()=>{let ff=Bun.spawn(["ffmpeg","-hide_banner","-loglevel","error","-i",full,"-vf",vf,"-frames:v",video?String(MAXF):"1","-f","rawvideo","-pix_fmt","gray","-"],{stdout:"pipe",stderr:"pipe"}),[buf,err]=await Promise.all([new Response(ff.stdout).arrayBuffer().then((b2)=>new Uint8Array(b2)),new Response(ff.stderr).text()]);if(await ff.exited,ff.exitCode!==0)return`ffmpeg: ${err.trim()||"failed"}`;if(buf.length===0||buf.length%PLANE!==0)return`ffmpeg: bad read (${buf.length})`;let n=buf.length/PLANE;return{planes:Array.from({length:n},(_2,i)=>buf.subarray(i*PLANE,(i+1)*PLANE)),fps:video?fps:0,w:SCALE,h:SCALE}})();if(clips.size>=CLIP_CAP)clips.delete(clips.keys().next().value);return clips.set(key2,p),p}var prewarm=(src2,fps=FPS0)=>void decode(src2,fps);function crop(clip,sp){let side=Math.max(1,Math.round(clip.w*clamp(sp.zoom,0.1,1))),x0=Math.round((clip.w-side)*clamp(sp.ox,0,1)),y0=Math.round((clip.h-side)*clamp(sp.oy,0,1)),n=clip.planes.length,gray=new Uint8Array(side*side*n);for(let f=0;f<n;f++){let pl=clip.planes[f],off=f*side*side;for(let y2=0;y2<side;y2++)gray.set(pl.subarray((y0+y2)*clip.w+x0,(y0+y2)*clip.w+x0+side),off+y2*side)}let enc2;return{gray,w:side,h:side,frames:n,png:()=>enc2??=png(gray,side,side*n)}}function png(gray,w2,h2){let be32=(n)=>new Uint8Array([n>>>24,n>>>16&255,n>>>8&255,n&255]),T2=png_crc,crc=(b2)=>{let c=4294967295;for(let i=0;i<b2.length;i++)c=T2[(c^b2[i])&255]^c>>>8;return~c>>>0},chunk=(tag,data2)=>{let t2=new TextEncoder().encode(tag),body=new Uint8Array(t2.length+data2.length);return body.set(t2),body.set(data2,4),[be32(data2.length),body,be32(crc(body))]},ihdr=new Uint8Array(13);ihdr.set(be32(w2),0),ihdr.set(be32(h2),4),ihdr[8]=8,ihdr[9]=0,ihdr[10]=0,ihdr[11]=0,ihdr[12]=0;let raw=new Uint8Array(h2*(w2+1));for(let y2=0;y2<h2;y2++)raw.set(gray.subarray(y2*w2,(y2+1)*w2),y2*(w2+1)+1);let idat=new Uint8Array(deflateSync(raw,{level:1})),parts2=[new Uint8Array([137,80,78,71,13,10,26,10]),...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))],out=new Uint8Array(parts2.reduce((n,p)=>n+p.length,0)),o=0;for(let p of parts2)out.set(p,o),o+=p.length;return out}var png_crc=(()=>{let t2=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k2=0;k2<8;k2++)c=c&1?3988292384^c>>>1:c>>>1;t2[n]=c>>>0}return t2})(),cache3=new Map,CAP3=256;function put(key2,v2){if(cache3.size>=CAP3)cache3.delete(cache3.keys().next().value);return cache3.set(key2,v2),v2}function hit(key2){let v2=cache3.get(key2);if(!v2)return;return cache3.delete(key2),cache3.set(key2,v2),v2}function resetCache(){cache3.clear(),clips.clear()}var keyOf=(r,src2,sp,fps,k2)=>`${r}|${src2}|${fps}|${sp.zoom.toFixed(3)}:${sp.ox.toFixed(3)}:${sp.oy.toFixed(3)}|${JSON.stringify(k2)}`;async function cached2(r,src2,sp,fps,k2,signal){let key2=keyOf(r.name,src2,sp,fps,k2),got=hit(key2);if(got)return{frames:got};let cl=await decode(src2,fps);if(typeof cl==="string")return{err:cl};if(signal?.aborted)return{err:"aborted"};let out=await r.render(crop(cl,sp),k2,signal);if("err"in out)return out;if(signal?.aborted)return{err:"aborted"};return{frames:put(key2,out.frames)}}function pad(rows3){let out=rows3.slice(0,H);while(out.length<H)out.push("");return out.map((l)=>{if(l.includes("\x1B["))return l;let cp=Array.from(l);return cp.length>=W2?cp.slice(0,W2).join(""):l+" ".repeat(W2-cp.length)})}function box(out,n){let rows3=out.replace(/\n$/,"").split(`
4125
+ `).map((s)=>s.trim()).filter((s)=>s.length>0&&!s.startsWith("(")),CuratorDialog=()=>{let{theme,syntaxStyle}=useTheme(),gw=useGateway(),toast=useToast(),dialog=useDialog(),state2=useHome("curatorState"),cfg=useHome("config")?.curator,[report2,setReport]=import_react85.useState(null),[loaded,setLoaded]=import_react85.useState(!1),[busy,setBusy]=import_react85.useState(null),[archived,setArchived]=import_react85.useState([]),[mode,setMode]=import_react85.useState("report"),[sel,setSel]=import_react85.useState(0),sb=import_react85.useRef(null);import_react85.useEffect(()=>{readLatestCuratorReport().then((r)=>{setReport(r),setLoaded(!0)}).catch(()=>setLoaded(!0))},[]);let refreshArchived=import_react85.useCallback(()=>{gw.request("shell.exec",{command:"hermes curator list-archived"}).then((r)=>{if(r.code===0)setArchived(parseList(r.stdout))}).catch(()=>{})},[gw]);import_react85.useEffect(()=>{refreshArchived()},[refreshArchived]);let sh=import_react85.useCallback((verb,ok)=>{if(busy)return;setBusy(verb),gw.request("shell.exec",{command:`hermes curator ${verb}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:ok}),home2.invalidate("curatorState")}).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]),restore=import_react85.useCallback((name)=>{if(busy)return;setBusy("restore"),gw.request("shell.exec",{command:`hermes curator restore ${name}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:`Restored ${name}`}),setArchived((prev)=>prev.filter((n)=>n!==name)),setSel((s)=>Math.max(0,s-1))}).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]);useKeyboard((key2)=>{if(mode==="archived"){if(key2.name==="escape"){setMode("report");return}if(key2.raw==="a"){setMode("report");return}if(key2.name==="up")return setSel((s)=>Math.max(0,s-1));if(key2.name==="down")return setSel((s)=>Math.min(archived.length-1,s+1));if(key2.name==="return"){let name=archived[sel];if(name)restore(name);return}return}if(key2.name==="escape")return dialog.clear();if(key2.raw==="r")return sh("run","Curator run started (background)");if(key2.raw==="p")return state2?.paused?sh("resume","Curator resumed"):sh("pause","Curator paused");if(key2.raw==="a"&&archived.length>0)setSel(0),setMode("archived")}),import_react85.useEffect(()=>{if(mode==="archived")sb.current?.scrollChildIntoView(`arch-${sel}`)},[sel,mode]);let last3=iso2(state2?.last_run_at??null),due=last3&&cfg?last3+cfg.interval_hours*3600:null,status=cfg?.enabled===!1?"disabled":state2?.paused?"paused":"enabled",tint=status==="enabled"?theme.success:status==="paused"?theme.warning:theme.textMuted;return $jsxs("box",{flexDirection:"column",width:120,height:34,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Curator"})}),$jsx("span",{fg:tint,children:` \xB7 ${status}`})]}),busy?$jsx("box",{marginLeft:2,children:$jsx(Spinner,{color:theme.textMuted,label:busy})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:state2?`${state2.run_count} run${state2.run_count===1?"":"s"}${last3?" \xB7 last "+ago(last3):" \xB7 never"} \xB7 Esc to close`:"No curator state yet \xB7 Esc to close"})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:40,height:"100%",flexShrink:0,children:[$jsx(KVBlock,{rows:[["Next run",status!=="enabled"?`\u2014 (${status})`:due?until(due):"when idle"],["Last run",last3?ago(last3):"never"],["Duration",state2?.last_run_duration_seconds?dur2(state2.last_run_duration_seconds):void 0],["Archived",archived.length>0?String(archived.length):void 0]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Config \xB7 edit in Config tab"})}),$jsx(KVBlock,{rows:[["Interval",cfg?`${cfg.interval_hours}h`:"\u2014"],["Stale after",cfg?`${cfg.stale_after_days}d`:"\u2014"],["Archive after",cfg?`${cfg.archive_after_days}d`:"\u2014"]]}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"r "}),$jsx("span",{fg:theme.text,children:"run now"}),$jsx("span",{fg:theme.textMuted,children:" (background)"})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"p "}),$jsx("span",{fg:theme.text,children:state2?.paused?"resume":"pause"})]})}),archived.length>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"a "}),$jsx("span",{fg:theme.text,children:"archived skills"}),$jsx("span",{fg:theme.textMuted,children:` (${archived.length})`})]})}):null]}),state2?.last_run_summary?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Last run"})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("markdown",{content:state2.last_run_summary,fg:theme.markdownText,syntaxStyle})})]}):null]}),mode==="archived"?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Archived skills (${archived.length})`})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191\u2193 select \xB7 Enter restore \xB7 a/Esc back to report"})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,contentOptions:{flexDirection:"column"},children:archived.length===0?$jsx("text",{fg:theme.textMuted,children:"No archived skills."}):archived.map((name,i)=>$jsx("box",{id:`arch-${i}`,height:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>restore(name),children:$jsxs("text",{fg:i===sel?theme.text:theme.textMuted,children:[i===sel?"\u25B8 ":" ",name]})},name))})]}):!loaded?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading report\u2026"})}):report2?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Report \xB7 ${report2.runId}`})})}),$jsx(KVLink,{label:"File",source:report2.source,text:report2.source.relative}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx("markdown",{content:report2.content||"(empty)",fg:theme.markdownText,syntaxStyle})})})]}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No runs yet \u2014 curator has not completed a cycle."})})]})]})},openCurator=(dialog)=>dialog.replace($jsx(CuratorDialog,{}),void 0,{ownCancel:!0});var NO_EVENTS=[],iso3=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},SkillRow=import_react87.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,bg2=props.selected?theme.backgroundElement:void 0,used=iso3(u3?.last_used_at)??iso3(u3?.last_viewed_at),stale=u3?.state==="stale",archived=u3?.state==="archived";return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:theme.warning,children:u3?.pinned?"\uD83D\uDCCC":" "}),$jsx(Marquee,{grow:!0,min:8,active:props.selected,fg:archived?theme.textMuted:props.selected?theme.accent:theme.text,children:s.name}),archived?$jsx(Col,{w:10,fg:theme.textMuted,children:"archived"}):stale?$jsx(Col,{w:10,fg:theme.warning,children:"stale"}):$jsx(Col,{w:10,fg:theme.textMuted,children:used?ago(used):""})]})}),HitRow=import_react87.memo((props)=>{let theme=useTheme().theme,on=props.selected;return $jsxs("box",{flexDirection:"row",height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:on?theme.accent:theme.text,children:props.hit.name}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,children:props.hit.description||"\u2014"})]})}),line2=(e)=>{switch(e.kind){case"absorbed":return`absorbed ${e.sources.map((s)=>`\`${s}\``).join(", ")}`;case"merged":return`merged into \`${e.into}\`${e.reason?` \u2014 ${e.reason}`:""}`;case"transition":return`${e.from} \u2192 ${e.to}`;case"pruned":return`pruned${e.reason?` \u2014 ${e.reason}`:""}`;case"added":return"created by curator"}},DetailPanel2=import_react87.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,used=iso3(u3?.last_used_at),viewed=iso3(u3?.last_viewed_at),patched=iso3(u3?.last_patched_at);return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Detail"})}),u3?.pinned?$jsx("span",{fg:theme.warning,children:" \uD83D\uDCCC pinned"}):null,u3?.state==="stale"?$jsx("span",{fg:theme.warning,children:" \xB7 stale"}):null,u3?.state==="archived"?$jsx("span",{fg:theme.textMuted,children:" \xB7 archived"}):null]})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:s.name})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Category",s.category||"uncategorized",theme.info],["Tags",s.tags.length>0?s.tags.join(", "):void 0],u3?["Used",u3.use_count>0?`${u3.use_count}\xD7 \xB7 last ${used?ago(used):"never"}`:"never"]:null,u3&&viewed?["Viewed",`${u3.view_count}\xD7 \xB7 last ${ago(viewed)}`]:null,u3&&patched?["Patched",`${u3.patch_count}\xD7 \xB7 last ${ago(patched)}`]:null].filter(Boolean)}),$jsx(KVLink,{label:"File",source:s.source,text:s.source.relative}),$jsx("box",{height:1}),s.description?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:s.description})}):$jsx("text",{fg:theme.textMuted,children:"No description"}),props.events.length>0?$jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Curator lineage"})}),props.events.map((e,i)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:ago(e.at)})}),$jsx("box",{flexGrow:1,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:line2(e)})})]},i))]}):u3?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No curator events for this skill"})}):null]})}),EmptyState=import_react87.memo((props)=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:props.searching?"No matching skills on hub":"No skills found in ~/.hermes/skills/"})})})}),HistoryPanel=import_react87.memo((props)=>{let{theme,syntaxStyle}=useTheme(),keys=useKeys(),follow=useFollow("skills-history"),[runs,setRuns]=import_react87.useState(()=>listCuratorRuns()),[sel,setSel]=import_react87.useState(0),[open2,setOpen]=import_react87.useState(!1),[body,setBody]=import_react87.useState(""),run=runs[sel];import_react87.useEffect(()=>{if(!open2||!run)return;let live=!0;return readCuratorReport(run.id).then((t2)=>{if(live)setBody(t2)}),()=>{live=!1}},[open2,run?.id]);let moveSel=import_react87.useCallback((v2)=>{setOpen(!1),setSel(v2)},[]);return useKeyboard((key2)=>{if(!props.focused)return;handleListKey(keys,key2,{count:runs.length,setSel:moveSel,...follow.opts,onActivate:()=>setOpen((o)=>!o),onRefresh:()=>setRuns(listCuratorRuns())})}),$jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:props.focused?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Curator History"})}),$jsx("span",{fg:theme.textMuted,children:` ${runs.length} run${runs.length===1?"":"s"}${runs[0]?` \xB7 last ${ago(runs[0].at)}`:""}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select \xB7 Enter expand \xB7 ${keys.print("list.refresh")} reload \xB7 h close`})}),$jsx("box",{height:1}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:"no runs in ~/.hermes/logs/curator/"}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:runs.map((r,i)=>{let on=i===sel;return $jsxs("box",{id:follow.id(i),flexDirection:"column",children:[$jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),setOpen((o)=>i===sel?!o:!0)},children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:12,fg:on?theme.accent:theme.text,children:ago(r.at)}),$jsx(Col,{grow:!0,fg:theme.textMuted,children:`${r.before}\u2192${r.after} arch ${r.archived} cons ${r.consolidated}${r.added?` +${r.added}`:""}`})]}),on&&open2?$jsx("box",{marginLeft:2,marginTop:1,marginBottom:1,children:$jsx("markdown",{content:body||"\u2026",fg:theme.markdownText,syntaxStyle})}):null]},r.id)})})})]})}),Skills=import_react87.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),usage=useHome("skillUsage")??{},curator=useHome("curatorState"),lineage2=import_react87.useRef(indexCuratorLineage());import_react87.useEffect(()=>{lineage2.current=indexCuratorLineage()},[curator?.run_count]);let[skills,setSkills]=import_react87.useState([]),[selected,setSelected]=import_react87.useState(0),[searching,setSearching]=import_react87.useState(!1),[query,setQuery]=import_react87.useState(""),[hits,setHits]=import_react87.useState([]),[sort,setSort]=import_react87.useState("name"),[history,setHistory]=import_react87.useState(!1),seq=import_react87.useRef(0),load3=import_react87.useCallback(()=>{gw.request("skills.manage",{action:"list"}).then((res)=>{let raw=res.skills??{},rows3=Object.entries(raw).flatMap(([cat,names])=>names.map((n)=>{let source=makeSource(`skills/${cat}/${n}/SKILL.md`,`${n}/SKILL.md`),fm=readSkillFrontmatter(source);return{source,category:cat,name:n,description:fm.description,tags:fm.tags,tokenEstimate:count2(`${n} ${fm.description}`)}}));rows3.sort((a,b2)=>a.source.relative.localeCompare(b2.source.relative)),setSkills(rows3)}).catch(()=>{})},[gw]);import_react87.useEffect(()=>{load3()},[load3]),import_react87.useEffect(()=>{let id=++seq.current;if(!searching||!query.trim()){setHits([]);return}let t2=setTimeout(()=>{gw.request("skills.manage",{action:"search",query}).then((r)=>{if(seq.current!==id)return;setHits(r.results??[]),setSelected(0)}).catch(()=>{if(seq.current===id)setHits([])})},150);return()=>clearTimeout(t2)},[gw,query,searching]);let flat=[...sort==="used"?new Map([["by recency",[...skills].sort((a,b2)=>{let ta=iso3(usage[a.name]?.last_used_at)??iso3(usage[a.name]?.last_viewed_at)??0;return(iso3(usage[b2.name]?.last_used_at)??iso3(usage[b2.name]?.last_viewed_at)??0)-ta})]]):Map.groupBy(skills,(s)=>s.category||"uncategorized")].flatMap(([cat,items])=>[{type:"header",category:cat},...items.map((s)=>({type:"skill",skill:s}))]),skillRows=flat.filter((r)=>r.type==="skill"),count3=searching?hits.length:skillRows.length,current=!searching&&skillRows[selected]?.type==="skill"?skillRows[selected].skill:null,follow=useFollow("sk"),exit=import_react87.useCallback(()=>{setSearching(!1),setQuery(""),setHits([]),setSelected(0)},[]),install2=import_react87.useCallback(async(name)=>{if(!await openConfirm(dialog,{title:"Install skill?",body:name,yes:"install"}))return;gw.request("skills.manage",{action:"install",query:name}).then(()=>{toast.show({variant:"success",message:`Installed ${name}`}),exit(),load3()}).catch((e)=>toast.show({variant:"error",message:`Install failed: ${e.message}`}))},[dialog,gw,toast,exit,load3]),keys=useKeys();useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(searching){if(key2.name==="escape"){exit();return}if(key2.name==="backspace"){setQuery((p)=>p.slice(0,-1)),setSelected(0);return}if(key2.name==="up")return setSelected((p)=>Math.max(0,p-1));if(key2.name==="down")return setSelected((p)=>Math.min(count3-1,p+1));if(key2.name==="return"){let hit=hits[selected];if(hit)install2(hit.name);return}if(key2.raw&&key2.raw.length===1&&key2.raw>=" ")setQuery((p)=>p+key2.raw),setSelected(0);return}if(!key2.ctrl&&!key2.meta&&key2.raw==="s"){setSort((p)=>p==="name"?"used":"name"),setSelected(0);return}if(!key2.ctrl&&!key2.meta&&key2.raw==="c"){openCurator(dialog);return}if(!key2.ctrl&&!key2.meta&&key2.raw==="h"){setHistory((h2)=>!h2);return}if(history){if(key2.name==="escape")return setHistory(!1);return}handleListKey(keys,key2,{count:count3,setSel:setSelected,...follow.opts,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onSearch:()=>{setSearching(!0),setQuery(""),setHits([]),setSelected(0)}})});let skillIdx=-1;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Hub Search (${hits.length})`:`Skills (${skills.length}${sort==="used"?" \xB7 by use":""})`,children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,searching?null:$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,bold:!0,children:"Name"})]}),searching?null:$jsx("box",{height:1}),count3===0?$jsx(EmptyState,{searching}):searching?$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:hits.map((h2,i)=>$jsx(HitRow,{hit:h2,selected:i===selected,onHover:()=>setSelected(i)},h2.name))})}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:flat.map((row2,i)=>{if(row2.type==="header")return $jsx("box",{marginTop:i>0?1:0,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE ${row2.category}`})})},`h-${row2.category}`);skillIdx++;let idx=skillIdx;return $jsx(SkillRow,{id:follow.id(idx),skill:row2.skill,usage:usage[row2.skill.name],selected:idx===selected,onSelect:()=>setSelected(idx),onHover:()=>setSelected(idx)},row2.skill.name)})}),!searching&&curator?$jsx("box",{height:1,flexShrink:0,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"curator \xB7 "}),curator.paused?$jsx("span",{fg:theme.warning,children:"paused"}):curator.last_run_at?$jsx("span",{fg:theme.textMuted,children:`${curator.run_count} run${curator.run_count===1?"":"s"} \xB7 last ${ago(iso3(curator.last_run_at)??0)}`}):$jsx("span",{fg:theme.textMuted,children:"never run"})]})}):null]}),history?$jsx(HistoryPanel,{focused:!!props.focused&&!searching}):current?$jsx(DetailPanel2,{skill:current,usage:usage[current.name],events:lineage2.current.get(current.name)??NO_EVENTS}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter","install"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],[keys.print("list.search"),"search hub"],["s","sort"],["c","curator"],["h","history"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react89=__toESM(require_react_production(),1);var kindOf=(ts)=>ts.name.includes(":")?"mcp":ts.name.startsWith("hermes-")?"platform":"core",KIND_LABEL={core:"core",platform:"platform bundles",mcp:"mcp"},group=(list2)=>{let by={core:[],platform:[],mcp:[]};for(let ts of list2)by[kindOf(ts)].push(ts);return["core","platform","mcp"].filter((k2)=>by[k2].length>0).map((k2)=>({kind:k2,items:by[k2]}))},Row2=import_react89.memo((props)=>{let theme=useTheme().theme,ts=props.ts,bg2=props.selected?theme.backgroundElement:void 0,unavail=ts.available===!1,glyph=unavail?"\u25CC":ts.enabled?"\u25CF":"\u25CB",glyphFg=unavail?theme.warning:ts.enabled?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphFg,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:ts.name}),$jsx(Col,{w:9,fg:theme.info,right:!0,children:`${ts.tool_count} tools`})]})}),DetailPanel3=import_react89.memo((props)=>{let theme=useTheme().theme,ts=props.ts,unavail=ts.available===!1;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"40%",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:ts.name})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:KIND_LABEL[kindOf(ts)]})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",unavail?"unavailable":ts.enabled?"enabled":"disabled",unavail?theme.warning:ts.enabled?theme.success:theme.textMuted],["Tools",String(ts.tool_count),theme.info],["Includes",ts.includes?.length?ts.includes.join(", "):void 0,theme.text],["Requires",ts.requirements?.length?ts.requirements.join(", "):void 0,unavail?theme.warning:theme.text]]}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:ts.description||"\u2014"})}),ts.tools?.length?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Tools (",ts.tools.length,"):"]})}),$jsx("scrollbox",{flexGrow:1,scrollY:!0,children:ts.tools.map((n)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",n]},n))})]}):null]})}),Toolsets=import_react89.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),[list2,setList]=import_react89.useState([]),[sel,setSel]=import_react89.useState(0),[err,setErr]=import_react89.useState(null),secs=group(list2),flat=secs.flatMap((s)=>s.items),live=import_react89.useRef({flat,sel});live.current={flat,sel};let load3=import_react89.useCallback(()=>{gw.request("toolsets.list",{}).then((r)=>{setList(r.toolsets??[]),setErr(null)}).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]);import_react89.useEffect(()=>{load3()},[load3]);let toggle=import_react89.useCallback(()=>{let ts2=live.current.flat[live.current.sel];if(!ts2)return;if(ts2.available===!1){toast.show({variant:"warning",message:`${ts2.name} is unavailable`});return}let action=ts2.enabled?"disable":"enable",was=ts2.enabled;setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:!t2.enabled}:t2)),gw.request("tools.configure",{action,names:[ts2.name]}).then((r)=>{if(r.unknown?.includes(ts2.name)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`${ts2.name} is not configurable`});return}if(r.missing_servers?.length&&ts2.name.includes(":")){let server=ts2.name.split(":",1)[0];if(r.missing_servers.includes(server)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`MCP server '${server}' not in config`});return}}if(Array.isArray(r.enabled_toolsets)){let on=new Set(r.enabled_toolsets);setList((prev)=>prev.map((t2)=>({...t2,enabled:on.has(t2.name)})))}else load3()}).catch((e)=>{setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"error",message:e.message})})},[gw,toast,load3]),count3=flat.length,ts=flat[sel]??null,follow=useFollow("ts"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:count3,setSel,...follow.opts,onToggle:toggle,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})}});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:`Toolsets (${count3})`,error:err,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:9,fg:theme.textMuted,bold:!0,right:!0,children:"Tools"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:"No toolsets found"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{return acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",KIND_LABEL[s.kind]," (",s.items.length,") "]})},`\xA7${s.kind}`)),s.items.forEach((t2,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(Row2,{id:follow.id(i),ts:t2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},t2.name))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]}),ts?$jsx(DetailPanel3,{ts}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.toggle"),"toggle"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react90=__toESM(require_react_production(),1);var mask=(val)=>"\u2022".repeat(Math.min(val.length,12)),VarRow=import_react90.memo((props)=>{let theme=useTheme().theme,set2=props.value!==void 0,bg2=props.selected?theme.backgroundElement:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onClick,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:props.selected?theme.accent:theme.text,children:props.name}),$jsx(Col,{w:8,fg:set2?theme.success:theme.textMuted,children:set2?" SET ":"UNSET"}),$jsx(Col,{grow:!0,min:4,fg:props.shown?theme.text:theme.textMuted,children:set2?props.shown?props.value:mask(props.value):"\u2014"})]})}),Env=import_react90.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),vars=useHome("env")??{},[sel,setSel]=import_react90.useState(0),[reveal,setReveal]=import_react90.useState(new Set),[collapsed,setCollapsed]=import_react90.useState({}),[searching,setSearching]=import_react90.useState(!1),[query,setQuery]=import_react90.useState(""),known=new Set(ENV_CATALOG.flatMap((g)=>g.keys)),extra=Object.keys(vars).filter((k2)=>!known.has(k2)).sort(),rows3=(extra.length>0?[...ENV_CATALOG,{category:"Other",keys:extra}]:ENV_CATALOG).flatMap((g)=>{let keys2=searching&&query.trim()?g.keys.filter((k2)=>k2.toLowerCase().includes(query.toLowerCase())):g.keys;if(keys2.length===0)return[];let hide=collapsed[g.category]??!1,header={type:"header",category:g.category,collapsed:hide};if(hide)return[header];return[header,...keys2.map((key2)=>({type:"var",key:key2,value:vars[key2]}))]}),count3=rows3.length,cur=rows3[sel],setKeys=rows3.flatMap((r)=>r.type==="var"&&r.value!==void 0?[r.key]:[]),follow=useFollow("env"),edit=import_react90.useCallback(async(key2,initial)=>{let val=await openTextPrompt(dialog,{title:`Edit ${key2}`,label:"Value",initial});if(val==null)return;await writeEnvVar(key2,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key2} saved`})},[dialog,toast]),add=import_react90.useCallback(async()=>{let key2=await openTextPrompt(dialog,{title:"New Variable",label:"Name (e.g. FOO_API_KEY)"});if(!key2)return;let val=await openTextPrompt(dialog,{title:`Set ${key2}`,label:"Value"});if(val==null)return;await writeEnvVar(key2,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key2} added`})},[dialog,toast]),del=import_react90.useCallback(async(key2)=>{if(!await openConfirm(dialog,{title:"Delete Variable",body:`Remove ${key2} from .env?`,yes:"delete",danger:!0}))return;await removeEnvVar(key2),home2.invalidate("env"),toast.show({variant:"success",message:`${key2} removed`})},[dialog,toast]),revealAll=import_react90.useCallback(()=>setReveal((s)=>s.size===setKeys.length&&setKeys.length>0?new Set:new Set(setKeys)),[setKeys]),activateAt=import_react90.useCallback((i)=>{let r=rows3[i];if(r?.type==="header")return setCollapsed((p)=>({...p,[r.category]:!p[r.category]}));if(r?.type==="var"){if(r.value!==void 0&&!reveal.has(r.key))return setReveal((s)=>new Set(s).add(r.key));return void edit(r.key,r.value??"")}},[rows3,reveal,edit]),activate=import_react90.useCallback(()=>activateAt(sel),[activateAt,sel]),rowClick=import_react90.useCallback((i)=>{setSel(i),activateAt(i)},[activateAt]),keys=useKeys();return useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(searching){if(key2.name==="escape"){setSearching(!1),setQuery(""),setSel(0);return}if(key2.name==="backspace"){setQuery((q4)=>q4.slice(0,-1)),setSel(0);return}if(key2.name==="up")return setSel((p)=>Math.max(0,p-1));if(key2.name==="down")return setSel((p)=>Math.min(count3-1,p+1));if(key2.name==="return")return setSearching(!1),activate();if(key2.raw&&key2.raw.length===1&&key2.raw>=" "){setQuery((q4)=>q4+key2.raw),setSel(0);return}return}handleListKey(keys,key2,{count:count3,setSel,...follow.opts,onActivate:activate,onToggle:revealAll,onNew:add,onDelete:()=>{if(cur?.type==="var"&&cur.value!==void 0)del(cur.key)},onSearch:()=>{setSearching(!0),setQuery(""),setSel(0)},onRefresh:()=>{home2.invalidate("env"),toast.show({variant:"info",message:"Reloaded",duration:1000})}})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:searching?"Env (searching)":"Env / API Keys",children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:28,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:8,fg:theme.textMuted,bold:!0,children:"Status"}),$jsx(Col,{grow:!0,min:4,fg:theme.textMuted,bold:!0,children:"Value"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching variables":"No variables configured"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((row2,i)=>row2.type==="header"?$jsx("box",{id:follow.id(i),marginTop:i>0?1:0,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>rowClick(i),children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`${row2.collapsed?"\u25B8":"\u25BE"} ${row2.category}`})})},`h-${row2.category}`):$jsx(VarRow,{id:follow.id(i),name:row2.key,value:row2.value,shown:reveal.has(row2.key),selected:i===sel,onHover:()=>setSel(i),onClick:()=>rowClick(i)},row2.key))})},"list")]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","move"],["Enter","reveal/edit"],["Esc","cancel"]]:[["\u2191\u2193","move"],[keys.print("list.activate"),"reveal/edit"],[keys.print("list.toggle"),"show-all"],[keys.print("list.new"),"new"],[keys.print("list.delete"),"delete"],[keys.print("list.search"),"search"],[keys.print("list.refresh"),"reload"]]})]})});var import_react92=__toESM(require_react_production(),1);function usageColor(pct,theme){if(pct>=95)return theme.error;if(pct>=80)return theme.warning;return theme.success}function bar2(pct,w2){let filled=Math.round(pct/100*w2);return"\u2588".repeat(filled)+"\u2591".repeat(w2-filled)}var DESC={builtin:"File-based \xA7-delimited entries (MEMORY.md + USER.md). Always active.",mem0:"Server-side LLM fact extraction with semantic search and reranking.",honcho:"AI-native cross-session user modeling with dialectic Q&A.",hindsight:"Knowledge graph with entity resolution and multi-strategy retrieval.",holographic:"Local SQLite fact store with FTS5, trust scoring, HRR retrieval.",openviking:"Session-managed memory with tiered retrieval.",retaindb:"Cloud memory API with hybrid search and 7 memory types.",byterover:"Persistent knowledge tree via brv CLI.",supermemory:"Semantic long-term memory with profile recall and session ingest."},Memory=import_react92.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),gw=useGateway(),[sel,setSel]=import_react92.useState(0),config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),providers=useHome("memoryProviders")??[],activity=useHome("memoryActivity")??[],cfg=config?.memory,active=cfg?.provider||"",cur=providers[sel],on=!!cur&&(cur.name==="builtin"||cur.name===active),toggle=async()=>{if(!cur||cur.name==="builtin")return;let isOn=cur.name===active;if(!await openConfirm(dialog,{title:isOn?"Deactivate memory provider?":"Activate memory provider?",body:isOn?`Clear '${cur.name}' as the active provider (revert to built-in only).`:`Set '${cur.name}' as the active provider. Ensure required env vars are set (Env tab).`,yes:isOn?"deactivate":"activate"}))return;let{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"memory.provider",to:isOn?"":cur.name}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),home2.invalidate("memoryProviders"),toast.show({variant:"success",message:isOn?"Deactivated":`Activated ${cur.name} \u2014 new sessions pick this up`})},keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:providers.length,setSel,onToggle:toggle,onRefresh:()=>{home2.invalidate("memoryProviders"),home2.invalidate("memoryActivity"),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),feed=!cur?[]:cur.name==="builtin"?activity:activity.filter((a)=>a.provider===cur.name);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:"Memory Providers",grow:1,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:providers.map((p,i)=>{let pOn=p.name==="builtin"||p.name===active,has=Object.keys(p.config).length>0,dot=pOn?"\u25CF":has?"\u25D0":"\u25CB",fg2=pOn?theme.success:has?theme.warning:theme.textMuted,tag=pOn?"active":has?"configured":"";return $jsxs("box",{flexDirection:"column",marginBottom:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseDown:()=>setSel(i),onMouseMove:()=>setSel(i),children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[dot," "]}),$jsx("span",{fg:i===sel?theme.accent:theme.text,children:p.name}),tag?$jsxs("span",{fg:fg2,children:[" (",tag,")"]}):null]})}),$jsx("box",{height:1,overflow:"hidden",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:DESC[p.name]||"\u2014"})})]},p.name)})})}),$jsx(TabShell,{title:cur?.name??"Provider",grow:2,children:cur?$jsx(ProviderDetail,{provider:cur,active,cfg,memory,userProfile,feed}):$jsx("text",{fg:theme.textMuted,children:"Select a provider"})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.toggle"),"activate"]],suffix:on?"\u25CF active":"\u25CB inactive"})]})}),ProviderDetail=import_react92.memo((props)=>{let theme=useTheme().theme,p=props.provider,on=p.name==="builtin"||p.name===props.active;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:DESC[p.name]||"Memory provider"})}),$jsx("box",{height:1}),p.name==="builtin"?$jsxs("box",{flexDirection:"column",children:[props.cfg?$jsxs($Fragment,{children:[$jsx(KVBlock,{rows:[["Notes",props.cfg.memory_enabled?"enabled":"disabled",props.cfg.memory_enabled?theme.success:theme.error],["Profile",props.cfg.user_profile_enabled?"enabled":"disabled",props.cfg.user_profile_enabled?theme.success:theme.error]]}),$jsx("box",{height:1})]}):null,$jsx(CapacityBar,{title:"Notes (MEMORY.md)",info:props.memory??null}),$jsx("box",{height:1}),$jsx(CapacityBar,{title:"Profile (USER.md)",info:props.userProfile??null})]}):null,p.name!=="builtin"&&on&&props.cfg?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Agent Settings"})})}),$jsx(KVBlock,{rows:[["Nudge",`every ${props.cfg.nudge_interval} turns`],["Flush",`after ${props.cfg.flush_min_turns} turns`]]}),$jsx("box",{height:1})]}):null,Object.keys(p.config).length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Local Configuration"})})}),$jsx(KVBlock,{rows:Object.entries(p.config).map(([k2,v2])=>[k2,String(v2)])})]}):p.name!=="builtin"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No local config found. Run `hermes memory setup` to configure."})}):null,$jsx(ActivityFeed,{items:props.feed,own:p.name})]})})}),OP_GLYPH={write:"+",read:"?"},ActivityFeed=import_react92.memo((props)=>{let theme=useTheme().theme,all=props.own==="builtin",nW=props.items.filter((a)=>a.op==="write").length;return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"Recent Activity"})}),props.items.length?$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",nW," writes, ",props.items.length-nW," reads"]}):null]})}),props.items.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No memory-tool calls in the last ~2000 messages"})}):null,props.items.map((a,i)=>$jsx("box",{height:1,flexDirection:"row",overflow:"hidden",children:$jsxs("text",{children:[$jsxs("span",{fg:a.op==="write"?theme.success:theme.textMuted,children:[OP_GLYPH[a.op]," "]}),$jsx("span",{fg:theme.textMuted,children:ago(a.ts).padEnd(8)}),all&&a.provider!=="builtin"?$jsxs("span",{fg:theme.primary,children:[a.provider,"\xB7"]}):null,$jsx("span",{fg:theme.text,children:a.verb}),$jsxs("span",{fg:theme.textMuted,children:[" ",a.summary]})]})},i))]})}),CapacityBar=import_react92.memo((props)=>{let theme=useTheme().theme;if(!props.info)return $jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.title,": unavailable"]})});let color=usageColor(props.info.usagePercent,theme);return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:props.title}),$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",props.info.entryCount," entries"]})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:color,children:bar2(props.info.usagePercent,20)}),$jsxs("span",{fg:theme.textMuted,children:[" ",props.info.charCount,"/",props.info.charLimit," (",props.info.usagePercent,"%)"]})]})})]})});var ConfigGroup=import_react93.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[CONFIG_TAB];import_react93.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(Pane3,{visible:props.sub===0,children:$jsx(Config,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane3,{visible:props.sub===1,children:$jsx(Skills,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane3,{visible:props.sub===2,children:$jsx(Toolsets,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane3,{visible:props.sub===3,children:$jsx(Env,{focused:!!props.focused&&props.sub===3})}),$jsx(Pane3,{visible:props.sub===4,children:$jsx(Memory,{focused:!!props.focused&&props.sub===4})})]})]})}),Pane3=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react98=__toESM(require_react_production(),1);var import_react94=__toESM(require_react_production(),1);import{readFileSync as readFileSync7}from"fs";import{basename as basename10}from"path";var exports_eikon={};__export(exports_eikon,{writeStudio:()=>writeStudio,studioFile:()=>studioFile,sourceDir:()=>sourceDir,save:()=>save2,revision:()=>revision,remove:()=>remove2,register:()=>register,readStudio:()=>readStudio,rasterizers:()=>rasterizers,rasterizer:()=>rasterizer,probe:()=>probe,pick:()=>pick,peekSource:()=>peekSource,parseEikon:()=>parseEikon,onRevision:()=>onRevision,onRegistry:()=>onRegistry,list:()=>list2,header:()=>header,findSource:()=>findSource,file:()=>file,fetchSource:()=>fetchSource,ensure:()=>ensure,eikon:()=>exports_eikon,dir:()=>dir,baked:()=>baked,adopt:()=>adopt});import{existsSync as existsSync14,mkdirSync as mkdirSync4,readdirSync as readdirSync6,copyFileSync as copyFileSync2,readFileSync as readFileSync6,writeFileSync as writeFileSync4,rmSync as rmSync3}from"fs";import{join as join12,extname as extname3,basename as basename9}from"path";import{existsSync as existsSync13}from"fs";import{join as join11,dirname as dirname6}from"path";var locate2=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join11(d2,"assets/eikons");if(existsSync13(p))return p;let up=dirname6(d2);if(up===d2)break;d2=up}return join11(import.meta.dir,"../../../assets/eikons")},BUNDLED_EIKON_DIR=locate2();function bundledEikonPath(name){if(!name)return;let p=join11(BUNDLED_EIKON_DIR,`${name}.eikon`);return existsSync13(p)?p:void 0}import{deflateSync}from"zlib";import{spawnSync as spawnSync2}from"child_process";import{statSync as statSync5}from"fs";var W2=48,H=24,FPS0=16,MAXF=256,S0={zoom:1,ox:0.5,oy:0.5},defaults=(r)=>Object.fromEntries(Object.entries(r.knobs).map(([k2,d2])=>[k2,d2.default])),caps={chafa:chafaBin(),ffmpeg:spawnSync2("ffmpeg",["-version"],{stdio:"ignore"}).status===0,ffprobe:spawnSync2("ffprobe",["-version"],{stdio:"ignore"}).status===0};function probe(path7){if(!caps.ffprobe)return null;let r=spawnSync2("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",path7],{encoding:"utf8"});if(r.status!==0)return null;let m2=r.stdout.trim().match(/^(\d+),(\d+)/);return m2?{w:+m2[1],h:+m2[2]}:null}var clamp=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),SCALE=384,PLANE=SCALE*SCALE,VID=/\.(mp4|webm|mov|mkv|m4v|gif)$/i,clips=new Map,CLIP_CAP=8;function decode(src2,fps=FPS0){let full=resolveImage(src2);if(!full)return Promise.resolve(`not found: ${src2}`);let mt=statSync5(full,{throwIfNoEntry:!1})?.mtimeMs??0,key2=`${full}:${mt}:${fps}`,got=clips.get(key2);if(got)return clips.delete(key2),clips.set(key2,got),got;if(!caps.ffmpeg)return Promise.resolve("ffmpeg not installed");let video=VID.test(full),vf=[...video?[`fps=${fps}`]:[],`scale=${SCALE}:${SCALE}:force_original_aspect_ratio=increase`,`crop=${SCALE}:${SCALE}`].join(","),p=(async()=>{let ff=Bun.spawn(["ffmpeg","-hide_banner","-loglevel","error","-i",full,"-vf",vf,"-frames:v",video?String(MAXF):"1","-f","rawvideo","-pix_fmt","gray","-"],{stdout:"pipe",stderr:"pipe"}),[buf,err]=await Promise.all([new Response(ff.stdout).arrayBuffer().then((b2)=>new Uint8Array(b2)),new Response(ff.stderr).text()]);if(await ff.exited,ff.exitCode!==0)return`ffmpeg: ${err.trim()||"failed"}`;if(buf.length===0||buf.length%PLANE!==0)return`ffmpeg: bad read (${buf.length})`;let n=buf.length/PLANE;return{planes:Array.from({length:n},(_2,i)=>buf.subarray(i*PLANE,(i+1)*PLANE)),fps:video?fps:0,w:SCALE,h:SCALE}})();if(clips.size>=CLIP_CAP)clips.delete(clips.keys().next().value);return clips.set(key2,p),p}var prewarm=(src2,fps=FPS0)=>void decode(src2,fps);function crop(clip,sp){let side=Math.max(1,Math.round(clip.w*clamp(sp.zoom,0.1,1))),x0=Math.round((clip.w-side)*clamp(sp.ox,0,1)),y0=Math.round((clip.h-side)*clamp(sp.oy,0,1)),n=clip.planes.length,gray=new Uint8Array(side*side*n);for(let f=0;f<n;f++){let pl=clip.planes[f],off=f*side*side;for(let y2=0;y2<side;y2++)gray.set(pl.subarray((y0+y2)*clip.w+x0,(y0+y2)*clip.w+x0+side),off+y2*side)}let enc2;return{gray,w:side,h:side,frames:n,png:()=>enc2??=png(gray,side,side*n)}}function png(gray,w2,h2){let be32=(n)=>new Uint8Array([n>>>24,n>>>16&255,n>>>8&255,n&255]),T2=png_crc,crc=(b2)=>{let c=4294967295;for(let i=0;i<b2.length;i++)c=T2[(c^b2[i])&255]^c>>>8;return~c>>>0},chunk=(tag,data2)=>{let t2=new TextEncoder().encode(tag),body=new Uint8Array(t2.length+data2.length);return body.set(t2),body.set(data2,4),[be32(data2.length),body,be32(crc(body))]},ihdr=new Uint8Array(13);ihdr.set(be32(w2),0),ihdr.set(be32(h2),4),ihdr[8]=8,ihdr[9]=0,ihdr[10]=0,ihdr[11]=0,ihdr[12]=0;let raw=new Uint8Array(h2*(w2+1));for(let y2=0;y2<h2;y2++)raw.set(gray.subarray(y2*w2,(y2+1)*w2),y2*(w2+1)+1);let idat=new Uint8Array(deflateSync(raw,{level:1})),parts2=[new Uint8Array([137,80,78,71,13,10,26,10]),...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))],out=new Uint8Array(parts2.reduce((n,p)=>n+p.length,0)),o=0;for(let p of parts2)out.set(p,o),o+=p.length;return out}var png_crc=(()=>{let t2=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k2=0;k2<8;k2++)c=c&1?3988292384^c>>>1:c>>>1;t2[n]=c>>>0}return t2})(),cache3=new Map,CAP3=256;function put(key2,v2){if(cache3.size>=CAP3)cache3.delete(cache3.keys().next().value);return cache3.set(key2,v2),v2}function hit(key2){let v2=cache3.get(key2);if(!v2)return;return cache3.delete(key2),cache3.set(key2,v2),v2}function resetCache(){cache3.clear(),clips.clear()}var keyOf=(r,src2,sp,fps,k2)=>`${r}|${src2}|${fps}|${sp.zoom.toFixed(3)}:${sp.ox.toFixed(3)}:${sp.oy.toFixed(3)}|${JSON.stringify(k2)}`;async function cached2(r,src2,sp,fps,k2,signal){let key2=keyOf(r.name,src2,sp,fps,k2),got=hit(key2);if(got)return{frames:got};let cl=await decode(src2,fps);if(typeof cl==="string")return{err:cl};if(signal?.aborted)return{err:"aborted"};let out=await r.render(crop(cl,sp),k2,signal);if("err"in out)return out;if(signal?.aborted)return{err:"aborted"};return{frames:put(key2,out.frames)}}function pad(rows3){let out=rows3.slice(0,H);while(out.length<H)out.push("");return out.map((l)=>{if(l.includes("\x1B["))return l;let cp=Array.from(l);return cp.length>=W2?cp.slice(0,W2).join(""):l+" ".repeat(W2-cp.length)})}function box(out,n){let rows3=out.replace(/\n$/,"").split(`
4126
4126
  `);return Array.from({length:n},(_2,i)=>pad(rows3.slice(i*H,(i+1)*H)))}function thumb(frame,w2=16,h2=8){let fx=W2/w2,fy=H/h2;return Array.from({length:h2},(_2,y2)=>{let row2=Array.from(frame[Math.min(H-1,Math.floor(y2*fy+fy/2))]??""),n=row2.length;return Array.from({length:w2},(_3,x2)=>row2[Math.min(n-1,Math.floor(x2*fx+fx/2))]??" ").join("")})}function tone(win,flip,con){let{gray:g,w:w2,h:h2,frames:n}=win,sz=w2*h2;for(let f=0;f<n;f++){let o=f*sz;if(flip==="h"||flip==="hv")for(let y2=0;y2<h2;y2++){let ro=o+y2*w2;for(let x2=0;x2<w2>>1;x2++){let t2=g[ro+x2];g[ro+x2]=g[ro+w2-1-x2],g[ro+w2-1-x2]=t2}}if(flip==="v"||flip==="hv")for(let y2=0;y2<h2>>1;y2++){let a=g.subarray(o+y2*w2,o+(y2+1)*w2),b2=g.subarray(o+(h2-1-y2)*w2,o+(h2-y2)*w2),t2=new Uint8Array(a);a.set(b2),b2.set(t2)}}if(Math.abs(con-1)>0.001)for(let i=0;i<g.length;i++)g[i]=clamp(Math.round((g[i]-128)*con+128),0,255);return win}var chafa={name:"chafa",knobs:{symbols:{kind:"cycle",options:["braille","block","ascii","sextant","quad","half","wedge"],default:"braille"},fill:{kind:"cycle",options:["none","stipple","ascii","braille"],default:"none"},dither:{kind:"cycle",options:["none","ordered","diffusion","noise"],default:"none"},invert:{kind:"toggle",default:!0},flip:{kind:"cycle",options:["none","h","v","hv"],default:"none"},contrast:{kind:"slider",min:0.5,max:3,step:0.1,default:1}},available:()=>caps.chafa?!0:"chafa not installed",async render(win,k2,signal){let bin=caps.chafa;if(!bin)return{err:"chafa not installed"};let fill=String(k2.fill??"none");tone(win,String(k2.flip??"none"),clamp(Number(k2.contrast??1),0.5,3));let args=[`--size=${W2}x${H*win.frames}`,"--format=symbols","--stretch","--colors=none",`--symbols=${String(k2.symbols??"braille")}`,...fill==="none"?[]:[`--fill=${fill}`],`--dither=${String(k2.dither??"none")}`,"--preprocess","off",...k2.invert?["--invert"]:[],"-"];if(signal?.aborted)return{err:"aborted"};let ch=Bun.spawn([bin,...args],{stdin:win.png(),stdout:"pipe",stderr:"pipe"}),kill=()=>ch.kill();signal?.addEventListener("abort",kill,{once:!0});let[out,cerr]=await Promise.all([new Response(ch.stdout).text(),new Response(ch.stderr).text()]);if(await ch.exited,signal?.removeEventListener("abort",kill),signal?.aborted)return{err:"aborted"};if(ch.exitCode!==0)return{err:`chafa: ${cerr.trim()||"failed"}`};return{frames:box(out,win.frames)}}},DOT=[[1,8],[2,16],[4,32],[64,128]],RAMP=" .:-=+*#%@";function sample(g,w2,h2,fw,fh){let sx=w2/fw,sy=h2/fh;return(gx,gy)=>g[Math.min(h2-1,Math.floor(gy*sy))*w2+Math.min(w2-1,Math.floor(gx*sx))]}function braille(g,w2,h2,inv,con){let at=sample(g,w2,h2,W2*2,H*4),thr=128/con,rows3=[];for(let y2=0;y2<H;y2++){let row2="";for(let x2=0;x2<W2;x2++){let bits=0;for(let dy=0;dy<4;dy++)for(let dx=0;dx<2;dx++)if(at(x2*2+dx,y2*4+dy)>thr!==inv)bits|=DOT[dy][dx];row2+=String.fromCodePoint(10240+bits)}rows3.push(row2)}return rows3}function block(g,w2,h2,inv,con){let at=sample(g,w2,h2,W2,H),n=RAMP.length-1,rows3=[];for(let y2=0;y2<H;y2++){let row2="";for(let x2=0;x2<W2;x2++){let v2=clamp((at(x2,y2)-128)*con+128,0,255),i=Math.round((inv?255-v2:v2)/255*n);row2+=RAMP[i]}rows3.push(row2)}return rows3}var native={name:"native",knobs:{symbols:{kind:"cycle",options:["braille","block"],default:"braille"},invert:{kind:"toggle",default:!0},contrast:{kind:"slider",min:0.5,max:3,step:0.1,default:1}},available:()=>caps.ffmpeg?!0:"ffmpeg not installed",async render(win,k2){let con=clamp(Number(k2.contrast??1),0.5,3),inv=!!k2.invert,fn=k2.symbols==="block"?block:braille,sz=win.w*win.h;return{frames:Array.from({length:win.frames},(_2,i)=>fn(win.gray.subarray(i*sz,(i+1)*sz),win.w,win.h,inv,con))}}},BUILTIN=[chafa,native];var exports_eikon_knobs={};__export(exports_eikon_knobs,{zoom:()=>zoom,unfork:()=>unfork,toStudio:()=>toStudio,swap:()=>swap,step:()=>step,slug:()=>slug2,setState:()=>setState,setSlider:()=>setSlider,reset:()=>reset2,pan:()=>pan,knobs:()=>exports_eikon_knobs,fresh:()=>fresh,fork:()=>fork,eff:()=>eff,edit:()=>edit,cycle:()=>cycle2,STATES:()=>STATES2});var STATES2=["idle","listening","thinking","speaking","working","error"],clamp2=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),round=(x2,p=3)=>+x2.toFixed(p),wrap=(arr,cur,d2)=>arr[(Math.max(0,arr.indexOf(cur))+d2+arr.length)%arr.length];function fresh(name,r,seed){return{name,state:"idle",dims:null,dirty:!1,rasterizer:seed?.rasterizer??r.name,spatial:seed?.spatial??{...S0},fps:seed?.fps??FPS0,base:seed?.base??defaults(r),per:seed?.per??{},glyph:seed?.glyph??"\u25C6",sources:seed?.sources??{}}}var eff=(s,state2)=>s.per[state2]??s.base;function edit(s,fn){let own=s.per[s.state];return own?{...s,per:{...s.per,[s.state]:fn(own)},dirty:!0}:{...s,base:fn(s.base),dirty:!0}}var fork=(s)=>s.per[s.state]?s:{...s,per:{...s.per,[s.state]:{...s.base}},dirty:!0},unfork=(s)=>{if(!s.per[s.state])return s;let{[s.state]:_2,...rest}=s.per;return{...s,per:rest,dirty:!0}},setState=(s,state2)=>({...s,state:state2}),cycle2=(s,d2)=>setState(s,wrap(STATES2,s.state,d2));function step(k2,id,def2,d2){if(def2.kind==="cycle")return{...k2,[id]:wrap(def2.options,String(k2[id]??def2.default),d2)};if(def2.kind==="toggle")return{...k2,[id]:!(k2[id]??def2.default)};let cur=Number(k2[id]??def2.default);return{...k2,[id]:round(clamp2(cur+d2*def2.step,def2.min,def2.max))}}function setSlider(k2,id,def2,v2){if(def2.kind!=="slider")return k2;return{...k2,[id]:round(clamp2(v2,def2.min,def2.max))}}function pan(sp,dx,dy,fine=!1){let s=fine?0.01:0.03;return{zoom:sp.zoom,ox:round(clamp2(sp.ox+dx*s,0,1)),oy:round(clamp2(sp.oy+dy*s,0,1))}}function zoom(sp,d2,fine=!1){let s=fine?0.02:0.05;return{...sp,zoom:round(clamp2(sp.zoom+d2*s,0.1,1))}}function swap(s,r){return{...s,rasterizer:r.name,base:defaults(r),per:{},dirty:!0}}var reset2=(s,r)=>({...s,spatial:{...S0},base:defaults(r),per:{},dirty:!0}),slug2=(v2)=>v2.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")||"wip",toStudio=(s)=>({rasterizer:s.rasterizer,spatial:s.spatial,fps:s.fps,base:s.base,per:s.per,glyph:s.glyph,sources:s.sources});var ROOT=()=>hermesPath("eikons"),dir=(name)=>join12(ROOT(),name),file=(name)=>join12(dir(name),`${name}.eikon`),sourceDir=(name)=>join12(dir(name),"source"),studioFile=(name)=>join12(dir(name),"studio.json");function ensure(name){return mkdirSync4(sourceDir(name),{recursive:!0}),{dir:dir(name),file:file(name),source:sourceDir(name)}}function list2(){let root2=ROOT();if(!existsSync14(root2))return[];return readdirSync6(root2,{withFileTypes:!0}).filter((e)=>e.isDirectory()&&existsSync14(join12(root2,e.name,`${e.name}.eikon`))).map((e)=>{let src2=join12(root2,e.name,"source"),has=existsSync14(src2)&&readdirSync6(src2).length>0,head=header(join12(root2,e.name,`${e.name}.eikon`));return{name:e.name,file:join12(root2,e.name,`${e.name}.eikon`),source:src2,hasSource:has,sourceUrl:typeof head?.source_url==="string"?head.source_url:void 0}})}var IMG=/\.(png|jpe?g|webp|gif|bmp)$/i,VID2=/\.(mp4|webm|mov|mkv)$/i;function findSource(name,state2){let src2=sourceDir(name);if(!existsSync14(src2))return;let files=readdirSync6(src2).filter((f)=>IMG.test(f)||VID2.test(f));if(files.length===0)return;let by=(stem)=>files.find((f)=>basename9(f,extname3(f)).toLowerCase()===stem),pick=(state2&&by(state2))??by("base")??by("idle")??by(name)??files.find((f)=>IMG.test(f))??files[0];return join12(src2,pick)}function adopt(name,from2,role="base"){let fname=`${role}${extname3(from2).toLowerCase()}`,dst=join12(ensure(name).source,fname);if(from2!==dst)copyFileSync2(from2,dst);return fname}function readStudio(name){let p=studioFile(name);if(!existsSync14(p))return;let raw=JSON.parse(readFileSync6(p,"utf8"));if(!raw||typeof raw!=="object")return;return raw}function writeStudio(name,s){ensure(name),writeFileSync4(studioFile(name),JSON.stringify(s,null,2)+`
4127
4127
  `,"utf8")}function header(path7){if(!existsSync14(path7))return;return peek2(path7)??void 0}function baked(name){let local=file(name);if(existsSync14(local))return local;for(let f of[`${name}.eikon`,"default.eikon"]){let p=join12(BUNDLED_EIKON_DIR,f),head=header(p);if(head&&String(head.name).toLowerCase()===name.toLowerCase())return p}return}var registry=new Map(BUILTIN.map((r)=>[r.name,r])),subs2=new Set;function register(r){registry.set(r.name,r);for(let f of subs2)f();return()=>{if(registry.get(r.name)===r)registry.delete(r.name);for(let f of subs2)f()}}var rasterizers=()=>[...registry.values()],rasterizer=(name)=>registry.get(name),onRegistry=(fn)=>{return subs2.add(fn),()=>subs2.delete(fn)};function pick(prefer){let want=prefer&&registry.get(prefer);if(want&&want.available()===!0)return want;for(let r of registry.values())if(r.available()===!0)return r;return registry.get("native")}var rev=0,revSubs=new Set,revision=()=>rev,onRevision=(fn)=>{return revSubs.add(fn),()=>revSubs.delete(fn)},bump=()=>{rev++;for(let f of revSubs)f()};function serialize2(name,glyph,fps,clips2,url){let out=[JSON.stringify({eikon:1,name,width:W2,height:H,glyph,author:process.env.USER??"unknown",created:new Date().toISOString(),...url?{source_url:url}:{}})];for(let st of STATES2){let fs7=clips2.get(st);out.push(JSON.stringify({state:st,fps,frame_count:fs7.length,loop_from:0})),fs7.forEach((f,i)=>out.push(JSON.stringify({f:i,data:f.join(`
4128
4128
  `)})))}return out.join(`
4129
4129
  `)+`
4130
- `}async function save2(s){let r=rasterizer(s.rasterizer)??pick(s.rasterizer),paths=ensure(s.name),sources={};for(let[role,p]of Object.entries(s.sources)){if(!p)continue;let abs2=p.includes("/")?p:join12(paths.source,p);sources[role]=existsSync14(abs2)?adopt(s.name,abs2,role):p}let seen=new Map,clips2=new Map,blank=[Array.from({length:H},(_2,i)=>(i===H>>1?s.glyph.padStart(W2>>1):"").padEnd(W2))];for(let st of STATES2){let src2=findSource(s.name,st),k2=eff(s,st),key2=`${src2??""}|${JSON.stringify(k2)}`,fs7=seen.get(key2);if(!fs7){if(!src2)fs7=blank;else{let out=await cached2(r,src2,s.spatial,s.fps,k2);if("err"in out)throw Error(out.err);fs7=out.frames}seen.set(key2,fs7)}clips2.set(st,fs7)}let url=header(paths.file)?.source_url;return await Bun.write(paths.file,serialize2(s.name,s.glyph,s.fps,clips2,url)),writeStudio(s.name,{...toStudio(s),sources}),set("eikon",s.name),bump(),paths.file}function remove2(name){if(rmSync3(dir(name),{recursive:!0,force:!0}),get("eikon")===name)set("eikon",void 0);bump()}var peekSource=peek3;async function fetchSource(src2,opts){let out=await install(src2,ROOT(),opts),prev=readStudio(out.name);return writeStudio(out.name,{...prev??toStudio(fresh(out.name,pick())),sources:{...prev?.sources,...out.sources}}),bump(),{name:out.name,sources:out.sources,n:out.n,bytes:out.bytes}}extend({slider:SliderRenderable});var PANES=["knobs","preview","strip"],mb2=(n)=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,HEAD2=[{id:"rasterizer",kind:"select",label:"rasterizer"},{id:"source",kind:"prompt",label:"source"},{id:"name",kind:"prompt",label:"name"},{id:"-1",kind:"divider",label:""},{id:"fetch",kind:"action",label:"fetch source",show:(s,live,url)=>!live&&!!url},{id:"fork",kind:"action",label:"fork state",show:(_s,live)=>live},{id:"reset",kind:"action",label:"reset knobs",show:(_s,live)=>live},{id:"-2",kind:"divider",label:"",show:(_s,live)=>live}];function buildRows(r,s,live,url){let dyn=live?Object.entries(r.knobs).map(([id,def2])=>({id,kind:"knob",label:def2.label??id,knob:def2})):[];return[...HEAD2.filter((h2)=>h2.show?h2.show(s,live,url):!0),...dyn]}var MINI_W=12;function Mini(props){let theme=useTheme().theme,d2=props.dims??{w:1,h:1},ar=d2.w/d2.h,bw=ar>=1?MINI_W:Math.max(4,Math.round(MINI_W*ar)),bh=ar>=1?Math.max(4,Math.round(MINI_W/ar)):MINI_W,short2=Math.min(bw,bh),cw=Math.max(1,short2*props.sp.zoom),cx=(bw-cw)*props.sp.ox,cy=(bh-cw)*props.sp.oy,on=(x2,y2)=>x2>=cx&&x2<cx+cw&&y2>=cy&&y2<cy+cw,cell=(x2,ty)=>{let up=on(x2,ty*2),dn=on(x2,ty*2+1);return up&&dn?"\u2588":up?"\u2580":dn?"\u2584":"\xB7"};return $jsx("box",{flexDirection:"column",flexShrink:0,backgroundColor:theme.backgroundElement,children:Array.from({length:Math.ceil(bh/2)},(_2,ty)=>$jsx("text",{fg:theme.textMuted,children:Array.from({length:bw},(_3,x2)=>cell(x2,ty)).join("")},ty))})}var SP_ROWS=["pan x","pan y","zoom","fps"];function PanBars(props){let theme=useTheme().theme,z2=props.sp.zoom,slack=1-z2,on=(i)=>props.focused&&props.sel===i,fg2=(i)=>on(i)?theme.accent:theme.textMuted,wheel=(k2)=>(e)=>{let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(k2,-1);if(d2==="down"||d2==="right")props.onWheel(k2,1)},drag=import_react94.useRef(null),grab=(k2,at)=>{drag.current={at,v:props.sp[k2],k:k2}},scrub=(at,L2)=>{let d2=drag.current;if(!d2||slack<=0)return;props.onSet(d2.k,Math.max(0,Math.min(1,+(d2.v+(at-d2.at)/(slack*L2)).toFixed(3))))},drop=()=>{drag.current=null},tw=Math.max(1,Math.round(z2*W2)),tl=Math.min(W2-tw,Math.round(props.sp.ox*slack*W2)),hbar=" ".repeat(tl)+"\u2588".repeat(tw)+" ".repeat(W2-tl-tw),vh=H*2,th=Math.max(1,z2*vh),ty=props.sp.oy*slack*vh,vbar=Array.from({length:H},(_2,y2)=>{let up=y2*2>=ty&&y2*2<ty+th,dn=y2*2+1>=ty&&y2*2+1<ty+th;return up&&dn?"\u2588\u2588":up?"\u2580\u2580":dn?"\u2584\u2584":" "});return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.children,$jsx("box",{width:W2,height:1,backgroundColor:theme.border,onMouseMove:()=>props.onHover(0),onMouseScroll:wheel("ox"),onMouseDown:(e)=>grab("ox",e.x),onMouseDrag:(e)=>scrub(e.x,W2),onMouseUp:drop,onMouseDragEnd:drop,children:$jsx("text",{fg:fg2(0),children:hbar})})]}),$jsx("box",{flexDirection:"column",width:2,height:H,backgroundColor:theme.border,onMouseMove:()=>props.onHover(1),onMouseScroll:wheel("oy"),onMouseDown:(e)=>grab("oy",e.y),onMouseDrag:(e)=>scrub(e.y,H),onMouseUp:drop,onMouseDragEnd:drop,children:vbar.map((g,y2)=>$jsx("text",{fg:fg2(1),children:g},y2))})]})}function SpatialBar(props){let theme=useTheme().theme,rows3=[{label:"zoom",k:"zoom",min:0.1,max:1,v:props.sp.zoom,i:2},{label:"fps",k:"fps",min:4,max:30,v:props.fps,i:3}],wheel=(k2)=>(e)=>{let d2=e.scroll?.direction;if(d2==="up")props.onWheel(k2,-1);if(d2==="down")props.onWheel(k2,1)};return $jsxs("box",{flexDirection:"row",marginTop:1,flexShrink:0,children:[$jsx("box",{flexDirection:"column",gap:1,flexShrink:0,children:rows3.map((d2)=>{let on=props.focused&&d2.i===props.sel;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onHover(d2.i),onMouseScroll:wheel(d2.k),children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:d2.label})}),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:d2.min,max:d2.max,value:d2.v,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>props.onSet(d2.k,d2.k==="fps"?Math.round(v2):+v2.toFixed(3))})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:` ${d2.k==="fps"?d2.v.toFixed(0):d2.v.toFixed(2)}`})})]},d2.label)})}),$jsx("box",{width:2}),$jsx(Mini,{sp:props.sp,dims:props.dims})]})}function valueOf(s,r,row2,src2,peek5,busy){if(row2.id==="rasterizer")return`${r.name} \u25B8`;if(row2.id==="source")return src2?src2.replace(process.env.HOME??"","~"):"(none \u2014 Enter to attach)";if(row2.id==="name")return s.name;if(row2.id==="fork")return s.per[s.state]?"(forked)":"\u25B8 copy base \u2192 "+s.state;if(row2.id==="reset")return"\u25B8 defaults";if(row2.id==="fetch")return busy?"fetching\u2026":peek5?`\u25B8 download to edit (${peek5.n} files, ${mb2(peek5.bytes)})`:"\u25B8 download to edit";if(row2.kind==="knob"&&row2.knob){let k2=exports_eikon_knobs.eff(s,s.state)[row2.id]??row2.knob.default;if(row2.knob.kind==="cycle")return`\u25C2 ${String(k2)} \u25B8`;if(row2.knob.kind==="toggle")return k2?"\u25CF on":"\u25CB off";if(row2.knob.kind==="slider")return Number(k2).toFixed(2)}return""}function KnobRow(props){let theme=useTheme().theme,{row:row2,on,dim:dim2}=props;if(row2.kind==="divider")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(24)})});let slider=row2.knob?.kind==="slider"?row2.knob:void 0;return $jsxs("box",{id:props.id,height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onClick,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:12,children:$jsx("text",{fg:dim2?theme.textMuted:on?theme.text:theme.textMuted,children:row2.label})}),slider?$jsxs($Fragment,{children:[$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:slider.min,max:slider.max,value:Number(exports_eikon_knobs.eff(props.s,props.s.state)[row2.id]??slider.default),foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:props.onSlide})}),$jsx("box",{width:1})]}):null,$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:props.busy&&row2.id==="fetch"?$jsx(Spinner,{color:theme.accent,label:"fetching\u2026"}):$jsx("text",{fg:dim2?theme.textMuted:theme.text,children:valueOf(props.s,props.r,row2,props.src,props.peek,props.busy)})})]})}function Strip(props){let theme=useTheme().theme;return $jsx("box",{flexDirection:"row",gap:1,children:STATES2.map((st)=>{let on=props.s.state===st,own=!!props.s.per[st],has=!!props.s.sources[st],f=props.frames.get(st);return $jsxs("box",{flexDirection:"column",alignItems:"center",onMouseDown:()=>props.onPick(st),children:[$jsx("box",{border:!0,borderStyle:"rounded",borderColor:on&&props.focused?theme.primary:on?theme.accent:theme.border,width:18,height:10,overflow:"hidden",alignItems:"center",justifyContent:"center",children:f?f.map((ln,i)=>$jsx("text",{fg:on?theme.text:theme.textMuted,children:ln},i)):$jsx("text",{fg:theme.textMuted,children:"\xB7"})}),$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.accent:theme.textMuted,children:`${own?"*":" "}${has?"\uD83D\uDCCE":" "}${st}`})})]},st)})})}var BLANK3=Array.from({length:H},()=>" ".repeat(W2)),EikonStudio=import_react94.memo((props)=>{let theme=useTheme().theme,keys=useKeys(),dialog=useDialog(),toast=useToast(),wide=useTerminalDimensions().width>=120;import_react94.useSyncExternalStore(exports_eikon.onRegistry,()=>exports_eikon.rasterizers().length);let[s,setS]=import_react94.useState(null),[pane,setPane]=import_react94.useState("knobs"),[sel,setSel]=import_react94.useState(0),[spSel,setSpSel]=import_react94.useState(0),selRef=import_react94.useRef(0);selRef.current=sel;let spRef=import_react94.useRef(0);spRef.current=spSel;let sRef=import_react94.useRef(null);sRef.current=s;let[frames,setFrames]=import_react94.useState([BLANK3]),[tick2,setTick]=import_react94.useState(0),[play,setPlay]=import_react94.useState(!0),[busy,setBusy]=import_react94.useState(!1),[fetching,setFetching]=import_react94.useState(!1),[peek5,setPeek]=import_react94.useState(void 0),[thumbs,setThumbs]=import_react94.useState(new Map),[err,setErr]=import_react94.useState(null),frame=frames[tick2%frames.length]??BLANK3,r=import_react94.useMemo(()=>exports_eikon.pick(s?.rasterizer??get("eikonRasterizer")),[s?.rasterizer]),spatialOk=caps.ffmpeg,open2=import_react94.useCallback((name)=>{resetCache();let seed=exports_eikon.readStudio(name),ra=exports_eikon.pick(seed?.rasterizer??get("eikonRasterizer")),next2=exports_eikon_knobs.fresh(name,ra,seed),src3=exports_eikon.findSource(name,"idle");next2.dims=src3?exports_eikon.probe(src3)??null:null;for(let st of STATES2){let p=exports_eikon.findSource(name,st);if(p)prewarm(p,next2.fps)}setS(next2),setSel(0),setPane("knobs"),setErr(null),setTick(0),setFrames([BLANK3])},[]),tried=import_react94.useRef(!1);import_react94.useEffect(()=>{if(tried.current)return;if(tried.current=!0,props.name)return open2(props.name||exports_eikon_knobs.slug("new"));let n2=get("eikon");if(n2)open2(n2)},[open2,props.name]),import_react94.useEffect(()=>{if(props.name!==void 0)open2(props.name||exports_eikon_knobs.slug("new"))},[props.name,open2]);let src2=import_react94.useMemo(()=>s?exports_eikon.findSource(s.name,s.state):void 0,[s?.name,s?.state,s?.sources]),live=import_react94.useMemo(()=>!!(s&&exports_eikon.findSource(s.name)),[s?.name,s?.sources]),baked2=import_react94.useMemo(()=>{if(live||!s)return;let p=exports_eikon.baked(s.name);if(!p)return;try{return exports_eikon.parseEikon(readFileSync7(p,"utf8"))}catch{return}},[live,s?.name]),url=import_react94.useMemo(()=>{if(!s)return;let p=exports_eikon.baked(s.name);return p?exports_eikon.header(p)?.source_url:void 0},[s?.name]);import_react94.useEffect(()=>{if(setPeek(void 0),!url||live)return;let dead=!1;return exports_eikon.peekSource(url).then((x2)=>{if(!dead)setPeek(x2)}),()=>{dead=!0}},[url,live]);let rows3=import_react94.useMemo(()=>s?buildRows(r,s,live,url):[],[r,s,live,url]),navRows=import_react94.useMemo(()=>rows3.map((x2,i)=>({...x2,i})).filter((x2)=>x2.kind!=="divider"),[rows3]);import_react94.useEffect(()=>{if(!s)return;if(!src2){let clip=baked2?.states.get(s.state);setFrames(clip?.frames.length?clip.frames:[BLANK3]),setErr(null),setBusy(!1),setTick(0);return}let ctrl=new AbortController;return setBusy(!0),cached2(r,src2,s.spatial,s.fps,exports_eikon_knobs.eff(s,s.state),ctrl.signal).then((out)=>{if(ctrl.signal.aborted)return;if(setBusy(!1),"err"in out){setErr(out.err);return}setErr(null),setFrames(out.frames),setTick((t2)=>t2%out.frames.length)}),()=>ctrl.abort()},[s?.spatial,s?.base,s?.per,s?.state,s?.fps,s?.rasterizer,src2,r,baked2]),import_react94.useEffect(()=>{if(!play||!props.focused||frames.length<=1||busy)return;let fps=live?s?.fps??FPS0:baked2?.states.get(s?.state??"idle")?.fps??FPS0,id=setInterval(()=>setTick((t2)=>t2+1),1000/Math.max(1,fps));return()=>clearInterval(id)},[play,props.focused,frames.length,busy,live,s?.fps,s?.state,baked2]),import_react94.useEffect(()=>{if(!s)return;let dead=!1,t2=setTimeout(()=>{if(dead)return;let jobs=STATES2.map((st)=>{let sp=exports_eikon.findSource(s.name,st);if(!sp){let f=baked2?.states.get(st)?.frames[0];return Promise.resolve([st,f?thumb(f):void 0])}return cached2(r,sp,s.spatial,s.fps,exports_eikon_knobs.eff(s,st)).then((res)=>[st,"err"in res?void 0:thumb(res.frames[0])])});Promise.all(jobs).then((done)=>{if(dead)return;setThumbs(new Map(done))})},400);return()=>{dead=!0,clearTimeout(t2)}},[frames,s?.per,s?.sources,s?.name,s?.fps,r,baked2]);let mutate=(fn)=>setS((p)=>p?fn(p):p),setSpatial=(sp)=>mutate((p)=>({...p,spatial:{...p.spatial,...sp},dirty:!0})),setBar=(k2,v2)=>k2==="fps"?mutate((p)=>({...p,fps:Math.round(v2),dirty:!0})):setSpatial({[k2]:v2}),stepBar=(k2,d2)=>{let cur=sRef.current;if(!cur)return;if(k2==="fps")return setBar("fps",Math.max(4,Math.min(30,cur.fps+d2*2)));if(k2==="zoom")return setSpatial({zoom:Math.max(0.1,Math.min(1,+(cur.spatial.zoom+d2*0.03).toFixed(3)))});return setSpatial({[k2]:Math.max(0,Math.min(1,+(cur.spatial[k2]+d2*0.03).toFixed(3)))})},doSave=import_react94.useCallback(async()=>{if(!s)return;if(!live)return toast.show({variant:"warning",message:"No source \u2014 fetch or attach before saving"});await exports_eikon.save({...s,dirty:!1}).then((f)=>{mutate((p)=>({...p,dirty:!1})),toast.show({variant:"success",message:`Saved \u2192 ${basename10(f)}`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[s,live,toast]),doSelectRasterizer=()=>{let opts=exports_eikon.rasterizers().map((x2)=>{let a=x2.available();return{title:x2.name,value:x2.name,description:Object.keys(x2.knobs).join(" \xB7 "),hint:a===!0?void 0:a}});dialog.replace($jsx(DialogSelect,{title:"Rasterizer",filterable:!1,current:r.name,options:opts,onSelect:(o)=>{dialog.clear();let next2=exports_eikon.rasterizer(o.value);if(!next2)return;let a=next2.available();if(a!==!0)return toast.show({variant:"warning",message:`${o.value}: ${a}`});set("eikonRasterizer",o.value),mutate((p)=>exports_eikon_knobs.swap(p,next2))}}),()=>{})},doPrompt=async(id)=>{if(!s)return;if(id==="source"){let v2=await openTextPrompt(dialog,{title:"Source image",label:`for state '${s.state}' (png/jpg/webp/gif/mp4)`});if(!v2)return;let role=s.state==="idle"&&!s.sources.base?"base":s.state;try{let f=exports_eikon.adopt(s.name,v2,role);mutate((p)=>({...p,sources:{...p.sources,[role]:f},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}return}if(id==="name"){let v2=await openTextPrompt(dialog,{title:"Name",initial:s.name});if(v2)mutate((p)=>({...p,name:exports_eikon_knobs.slug(v2),dirty:!0}))}},doAction=async(id)=>{if(!s)return;if(id==="fork")return mutate(exports_eikon_knobs.fork);if(id==="reset"){if(await openConfirm(dialog,{title:"Reset knobs?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!url||fetching)return;setFetching(!0),await exports_eikon.fetchSource(url,{name:s.name}).then((out)=>{toast.show({variant:"success",message:`Fetched ${out.n} file(s) \xB7 ${mb2(out.bytes)}`}),open2(s.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e)))).finally(()=>setFetching(!1))}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Attach source image\u2026",value:"attach"},{title:s.per[s.state]?"Clear override (back to base)":"Fork knobs from base",value:"fork"}],onSelect:(o)=>{if(dialog.clear(),o.value==="attach")return void doPrompt("source");mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},stepRow=(row2,d2)=>{if(row2.kind!=="knob"||!row2.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row2.id,row2.knob,d2)))},act=(row2,via)=>{if(!row2||!sRef.current)return;if(row2.kind==="select")return doSelectRasterizer();if(row2.kind==="prompt")return void doPrompt(row2.id);if(row2.kind==="action"){if(via==="space"&&row2.id==="reset")return;return void doAction(row2.id)}if(row2.kind==="knob"){if(row2.knob.kind==="slider")return;return stepRow(row2,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row2=navRows[selRef.current];if(row2)stepRow(row2,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;if(await openConfirm(dialog,{title:"Discard unsaved edits?",danger:!0,body:`Reload '${cur.name}' from disk and drop in-memory changes.`}))open2(cur.name);return!0};useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.eventType==="release")return;if(keys.match("eikon.save",key2))return void doSave();if(key2.name==="escape")return void discard();if(key2.name==="tab"){let i=PANES.indexOf(pane);return setPane(PANES[(i+(key2.shift?PANES.length-1:1))%PANES.length])}if(!s){if(key2.name==="return")return void doPrompt("source");return}if(pane==="knobs"){if(handleListKey(keys,key2,{count:navRows.length,setSel,onActivate:activate,onToggle:toggle,onNew:()=>void doPrompt("source")}))return;if(key2.name==="left")return adjust(-1);if(key2.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key2))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key2,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key2.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key2.name==="left"||key2.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key2.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key2.name))}return}if(key2.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key2.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key2.name==="return")return doStripMenu()});let onScroll=(e)=>{if(!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,d2==="up"?-1:1),dirty:!0}))},n=frames.length,title=s?`Preview \u2014 ${s.state}${s.per[s.state]?" (forked)":""}`+(n>1?` \xB7 ${play?"\u25B6":"\u23F8"} ${tick2%n+1}/${n}`:"")+(live?"":baked2?" \xB7 (baked)":""):"Preview",previewErr=err??(!s||src2||baked2?null:url?"no source \u2014 Enter on 'fetch source' to download":"no source \u2014 Enter on 'source' to attach"),hint=pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"open"],[keys.print("eikon.save"),"save"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","zoom"],[keys.print("eikon.save"),"save"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),body=$jsxs("box",{position:"relative",flexDirection:"column",width:W2,height:H,flexShrink:0,backgroundColor:theme.background,onMouseScroll:onScroll,onMouseDown:()=>setPlay((p)=>!p),children:[frame.map((ln,i)=>$jsx("text",{fg:err?theme.textMuted:theme.hermAvatar,children:ln},i)),busy&&frames[0]===BLANK3?$jsx("box",{position:"absolute",left:0,top:H>>1,width:W2,justifyContent:"center",children:$jsx(Spinner,{color:theme.textMuted,label:"decoding\u2026"})}):null]}),preview2=$jsx(TabShell,{title:spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:previewErr,focus:pane==="preview",children:spatialOk&&live&&s?$jsxs($Fragment,{children:[$jsx(PanBars,{sp:s.spatial,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar,children:body}),$jsx(SpatialBar,{sp:s.spatial,fps:s.fps,dims:s.dims,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar})]}):body}),panel=$jsx(TabShell,{title:`Knobs${s?.dirty?" \xB7 \u25CF unsaved":""}`,focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create one."})}):rows3.map((row2,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row2.kind==="knob"&&!src2;return $jsx(KnobRow,{id:`knob-${row2.id}`,row:row2,s,r,src:src2,on,dim:dim2,peek:peek5,busy:row2.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSel(ni)},onClick:()=>{if(ni>=0)setSel(ni),setPane("knobs"),act(row2,"click")},onSlide:row2.knob?.kind==="slider"?(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row2.id,row2.knob,v2))):void 0},`${r.name}:${row2.id}`)})}),strip=s?$jsx("box",{flexShrink:0,height:17,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))}})})}):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[wide?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}),strip,$jsx("box",{flexGrow:1})]}):$jsxs("scrollbox",{scrollY:!0,flexGrow:1,contentOptions:{flexDirection:"column"},children:[$jsx("box",{flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{flexShrink:0,height:rows3.length+6,children:panel}),strip]}),$jsx(HintBar,{pairs:hint,suffix:s?.dirty?"\u25CF unsaved":void 0})]})});var import_react96=__toESM(require_react_production(),1);import{readFileSync as readFileSync8}from"fs";import{basename as basename11,dirname as dirname7}from"path";var EikonGallery=import_react96.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),follow=useFollow("gal"),rev2=import_react96.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),rows3=import_react96.useMemo(()=>{let user=hermesPath("eikons"),own=new Map(exports_eikon.list().map((x2)=>[x2.name.toLowerCase(),x2]));return listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():basename11(dirname7(e.path)),mine=own.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,states:e.meta.states.length,url:mine?.sourceUrl??e.meta.source_url,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3)}})},[rev2]),[sel,setSel]=import_react96.useState(0);import_react96.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],active=usePref("eikon"),parsed=import_react96.useMemo(()=>{if(!cur)return;try{return parseEikon(readFileSync8(cur.path,"utf8"))}catch{return}},[cur]),activate=()=>{if(!cur)return;set("eikon",cur.slug),toast.show({variant:"success",message:`Avatar \u2192 ${cur.name}`})},doInstall=async()=>{let src2=await openTextPrompt(dialog,{title:"Install eikon",label:"catalog name \xB7 github.com/u/r \xB7 git URL \xB7 http://\u2026/ \xB7 local dir"});if(!src2)return;toast.show({variant:"info",message:`Installing from ${src2}\u2026`}),await exports_eikon.fetchSource(src2).then((out)=>toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},doNew=()=>dialog.replace($jsx(DialogSelect,{title:"New eikon",filterable:!1,options:[{title:"Blank \u2014 author in Studio",value:"blank"},{title:"Install from\u2026",value:"install",description:"catalog name, git URL, local dir, or http manifest"}],onSelect:(o)=>{if(dialog.clear(),o.value==="blank")return props.onEdit?.("");doInstall()}}),()=>{}),del=async()=>{if(!cur||cur.bundled)return;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body:`Removes ${dirname7(cur.path)} and all its sources. This cannot be undone.`}))return;exports_eikon.remove(cur.slug),toast.show({variant:"info",message:`Deleted ${cur.name}`})};return useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(handleListKey(keys,key2,{count:rows3.length,setSel,...follow.opts,onActivate:activate,onDelete:()=>void del(),onNew:doNew}))return;if(key2.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Gallery (${rows3.length})`,focus:props.focused,grow:2,children:$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:rows3.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):rows3.map((r,i)=>{let on=i===sel,here=r.slug===active;return $jsxs("box",{id:follow.id(i),flexDirection:"row",height:2,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:activate,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx("box",{height:1,children:$jsxs("text",{fg:here?theme.accent:theme.text,children:[here?"\u25CF ":" ",$jsx("strong",{children:r.name}),$jsx("span",{fg:theme.textMuted,children:r.bundled?" (bundled)":""})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[` ${r.author??"\u2014"} \xB7 ${r.states} states \xB7 ${r.w}\xD7${r.h} \xB7 `,$jsx("span",{fg:r.hasSource?theme.success:r.url?theme.textMuted:theme.border,children:r.hasSource?"\u25CF source":r.url?"\u25CB source available":"\u2014 no source"})]})})]})]},r.path)})})}),$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:3,children:$jsx("box",{alignItems:"center",justifyContent:"center",flexGrow:1,children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.activate"),"use"],["e","edit in studio"],[keys.print("list.new"),"new / install"],...cur&&!cur.bundled?[[keys.print("list.delete"),"delete"]]:[]]})]})});var EikonGroup=import_react98.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[EIKON_TAB],[target,setTarget]=import_react98.useState(void 0);import_react98.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let edit2=import_react98.useCallback((name)=>{setTarget(name),props.setSub(0)},[props]),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(Pane4,{visible:props.sub===0,children:$jsx(EikonStudio,{focused:!!props.focused&&props.sub===0,name:target})}),$jsx(Pane4,{visible:props.sub===1,children:$jsx(EikonGallery,{focused:!!props.focused&&props.sub===1,onEdit:edit2})})]})]})}),Pane4=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:children2}):null;var import_react99=__toESM(require_react_production(),1);var FRAME={cw:16,ch:8,tw:20,tv:8},TL=["\u2800\u2880\u28E4\u2824\u2884\u28C0\u2804\u2880\u28E0\u28E4\u28C4\u2864\u2844\u2840\u2800\u2800","\u2800\u28DC\u2841\u28A9\u28C8\u2842\u2880\u28CB\u28ED\u2809\u2808\u2888\u28EE\u28FB\u2851\u28F6","\u2800\u28B8\u2856\u28BF\u280F\u28E4\u28F6\u28FD\u28EB\u28B6\u28E2\u284C\u2839\u28E7\u284F\u283B","\u2800\u2808\u2864\u2892\u28E6\u28BB\u28FF\u28FF\u28FF\u28BF\u28C5\u2847\u28C6\u2849\u2802\u2880","\u2801\u28B8\u284F\u2818\u280B\u289E\u28B3\u28FF\u28FF\u28DF\u284D\u284D\u28E4\u2805\u2800\u28A8","\u2800\u2824\u28AF\u28C6\u28C0\u2819\u28A6\u28FF\u284B\u2880\u28DC\u2807\u28C1\u28D2\u28CA\u28C9","\u2800\u2880\u28F7\u28DD\u28FB\u28F6\u28F6\u2884\u280D\u2818\u2841\u2847\u28E7\u28E0\u28E4\u2862","\u2800\u2800\u2818\u288E\u28BF\u28EF\u2803\u2801\u2864\u28DA\u287C\u2800\u284F\u28F9\u28FF\u2869"],TR=["\u2800\u2800\u2880\u28A0\u28A0\u28E0\u28E4\u28C0\u2840\u2820\u28C0\u2860\u2824\u28E4\u28C0\u2800","\u28F6\u288A\u28DF\u28F5\u2841\u2801\u2809\u28ED\u28D9\u2800\u2890\u28C2\u284D\u2888\u28E3\u2800","\u281F\u28B9\u28FC\u280F\u28A1\u28D4\u28B6\u28DD\u28EF\u28F6\u28E4\u2839\u287F\u28B2\u2847\u2800","\u2840\u2801\u2889\u28F0\u28B8\u28E8\u287F\u28FF\u28FF\u28FF\u285F\u28F4\u2852\u28A4\u2801\u2800","\u2845\u2804\u2828\u28E4\u28A9\u28A9\u28FB\u28FF\u28FF\u285E\u2873\u2819\u2803\u28B9\u2847\u2800","\u28C9\u28D1\u28D2\u28C8\u2838\u28E3\u2840\u2899\u28FF\u2874\u280B\u28C0\u28F0\u287D\u2824\u2880","\u2884\u28E4\u28C4\u28F8\u28B8\u2888\u2803\u2829\u2860\u28F6\u28F6\u28DF\u28EB\u28FE\u2802\u2800","\u288D\u28FF\u289F\u28B9\u2800\u28A7\u28D2\u28A4\u2801\u2808\u28FD\u287F\u2871\u2807\u2800\u2800"],BL=["\u2800\u2800\u28C0\u28FF\u28FF\u285F\u2801\u2800\u283B\u28AC\u28F3\u2800\u28C7\u28F2\u28DF\u28BF","\u2800\u2890\u287A\u28DB\u286F\u28ED\u2837\u280C\u2882\u2880\u2842\u2847\u284F\u2819\u281B\u2827","\u2800\u2816\u287C\u2809\u2809\u28A0\u28F0\u2825\u28AD\u2818\u28DB\u28C4\u288B\u28C9\u28C9\u2859","\u2800\u28B8\u284C\u2880\u28E0\u28F5\u28FF\u28FF\u28FF\u28FF\u28E8\u2803\u2837\u2802\u2810\u288D","\u2800\u2800\u283B\u281D\u283F\u28F4\u28FF\u28FF\u287F\u28FF\u28DF\u28CB\u284F\u2841\u2804\u2818","\u2800\u28B8\u28F0\u28F6\u28C4\u283B\u283F\u28FF\u28F9\u2830\u281F\u2882\u28A0\u285F\u28C6\u28F4","\u2800\u28AA\u2849\u2838\u28FB\u2807\u2800\u285D\u28DB\u2880\u2840\u28D8\u285F\u2877\u28EB\u286F","\u2800\u2819\u283B\u282A\u281C\u2813\u2802\u2808\u281B\u2813\u281B\u2819\u281A\u2808\u2801\u2800"],BR2=["\u287F\u28FB\u28D6\u28F8\u2800\u28DE\u2861\u281F\u2880\u2804\u28BB\u28FF\u28FF\u28C0\u2800\u2800","\u2836\u281B\u280B\u28B9\u28B8\u2890\u2840\u2850\u2821\u283E\u28ED\u28BD\u28DB\u2897\u2842\u2800","\u288B\u28C9\u28C9\u2859\u28E0\u28DB\u2803\u286D\u282C\u28C6\u2844\u2809\u2829\u28A7\u2832\u2800","\u2869\u2802\u2810\u283E\u2818\u28C5\u28FF\u28FF\u28FF\u28FF\u28EE\u28C4\u2840\u28B1\u2847\u2800","\u2803\u2880\u2888\u28B3\u28D9\u28FB\u28FF\u28DF\u28FF\u28FF\u28E6\u283F\u282B\u281F\u2800\u2800","\u28E6\u28F0\u28BB\u2844\u2850\u283B\u2803\u28CF\u28FF\u283F\u281F\u28E0\u28F6\u28C6\u2847\u2800","\u28BD\u28DD\u28AF\u28BB\u28C3\u2880\u2840\u28DB\u28E9\u2800\u2838\u28DF\u2807\u2889\u2855\u2800","\u2801\u2800\u2801\u2813\u280B\u281B\u281A\u281B\u2801\u2810\u281A\u2823\u2807\u281F\u280B\u2800"],T2=["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2844\u28E2\u28F4\u28F6\u2836\u2816\u2832\u28CC\u2818\u2809\u2822\u285B\u28A1\u2834\u2832\u2836\u28F0\u2896\u28B4\u28E4","\u28FE\u28E5\u283F\u2800\u28E0\u28B0\u283F\u28BE\u2850\u283E\u283F\u2887\u2873\u28FF\u28D7\u2804\u2800\u2823\u28D1\u28F5","\u28BE\u285F\u2804\u2810\u28AD\u28CD\u2896\u2844\u2828\u28BB\u28EB\u283D\u287C\u287F\u28BD\u28A5\u2842\u2804\u283B\u287D","\u2813\u287B\u28B6\u28C4\u2848\u2818\u282D\u281A\u280D\u28BB\u2849\u280B\u280B\u282D\u2803\u2803\u2861\u28F6\u28DF\u28BE","\u2801\u2804\u2809\u2809\u281A\u2824\u2824\u282C\u281F\u2830\u2827\u280A\u282F\u2834\u2824\u2813\u281B\u2809\u2810\u2822","\u28DB\u28DB\u285F\u28DB\u285B\u28DB\u28DB\u289B\u28DB\u28DB\u285B\u28DB\u28DB\u289B\u28FB\u28FB\u28DF\u281B\u28FB\u28BB","\u28CA\u28C9\u28C9\u28DB\u28CB\u28D9\u28CB\u28FC\u28F7\u28E5\u28EF\u28FA\u28CB\u28F5\u28F7\u28ED\u28D9\u28D1\u28FB\u28FD"],B2=["\u28FF\u28BF\u28FF\u28FF\u28BF\u28FF\u287F\u287F\u28FF\u28FF\u283F\u28FF\u28BF\u287F\u28FF\u28FF\u287F\u28FF\u287F\u28BF","\u28C3\u28DB\u28C8\u28D3\u28DA\u28DA\u28C3\u28D9\u28DB\u28C9\u28DB\u28DB\u28C1\u28DB\u28D9\u28D9\u28CB\u28D8\u28C9\u28D9","\u2820\u2884\u2884\u28C0\u2864\u28E4\u2810\u28E0\u2884\u28A0\u2844\u2864\u28C4\u2800\u2864\u2884\u28C0\u2840\u2880\u2880","\u28F1\u282C\u282B\u2811\u2881\u28E0\u28A0\u286B\u28E1\u28E0\u28E4\u28C9\u2885\u2884\u28C4\u2809\u283B\u2850\u28A5\u28CC","\u2894\u28C8\u2800\u28B0\u2841\u28B6\u28FF\u28FF\u28DF\u28FF\u28C3\u285B\u2815\u280D\u28E6\u28C3\u2844\u2802\u28F9\u2862","\u287F\u288F\u2884\u2800\u2803\u28EB\u28FF\u289C\u28A9\u28F6\u28E6\u2809\u2876\u28FE\u2856\u281B\u2800\u28E0\u285B\u287F","\u283C\u28BE\u283F\u28F5\u28D6\u28D8\u2834\u2803\u2808\u2886\u2880\u2800\u2873\u2824\u28C2\u28F2\u28FE\u282F\u281A\u280F","\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u280B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800"],L2=["\u2800\u2800\u2890\u289F\u28FE\u283F\u282E\u2836\u2877\u28EA\u283E\u2802\u2857\u28AD\u28BF\u28B9","\u2800\u2800\u28E8\u2855\u2809\u2861\u2824\u28C1\u284C\u282A\u28A7\u2801\u2847\u28F0\u28FF\u28BC","\u2800\u2800\u2839\u2843\u28BE\u28D5\u28F7\u2866\u28D3\u2840\u2849\u2846\u284F\u28F6\u2863\u28FB","\u2800\u28B0\u2876\u28AC\u28ED\u285C\u28FF\u28FF\u28EF\u2888\u2893\u2801\u284F\u28DA\u287E\u28FF","\u2800\u2818\u285B\u288A\u28D9\u2823\u2887\u28AF\u28FF\u2828\u286D\u2841\u2867\u28BC\u28F2\u28FF","\u2800\u2800\u28B1\u2849\u28BF\u2847\u2824\u28DD\u2844\u2800\u2841\u2801\u284F\u28F6\u2896\u28BF","\u2800\u2800\u28B0\u28E7\u2840\u2813\u2813\u2809\u2881\u28F4\u284D\u2800\u2847\u283A\u283D\u28BA","\u2800\u2800\u2828\u283A\u28FD\u28F7\u28E6\u2874\u285A\u2803\u2880\u2800\u2847\u287E\u28FF\u28B9"],R=["\u284F\u287F\u286D\u28BA\u2880\u2837\u289D\u28BE\u2836\u2835\u283F\u28F7\u287B\u2842\u2800\u2800","\u2867\u28FF\u28C6\u28B8\u2800\u287C\u2815\u28A1\u28C0\u2824\u288C\u2809\u28AA\u28C5\u2801\u2800","\u28DF\u289C\u28F6\u28B9\u28B0\u2889\u2880\u28DA\u28B4\u28FE\u28EA\u2877\u2898\u280F\u2800\u2800","\u28FF\u28B7\u285B\u28B9\u2808\u285A\u2841\u28FD\u28FF\u28FF\u28A3\u28ED\u2865\u28B6\u2846\u2800","\u28FF\u28D6\u2867\u28BC\u2888\u28AD\u2805\u28FF\u287D\u2878\u2858\u28CB\u2851\u289B\u2803\u2800","\u287F\u2872\u28F6\u28B9\u2808\u2888\u2800\u28A0\u28EB\u2824\u28B8\u287F\u2889\u2846\u2800\u2800","\u2857\u282F\u2817\u28B8\u2800\u28A9\u28E6\u2848\u2809\u281A\u281A\u2880\u28FC\u2846\u2800\u2800","\u284F\u28FF\u28AF\u28B8\u2800\u2880\u2818\u2893\u28A6\u28B6\u28FE\u28EF\u2817\u2805\u2800\u2800"];function frame(w2,h2){let{cw,ch,tw,tv}=FRAME,mw=w2-2*cw,mh=h2-2*ch,inner={x:cw,y:ch,w:Math.max(0,mw),h:Math.max(0,mh)};if(mw<4||mh<2)return{lines:[],inner};let repH=(p,span2)=>p.map((l2)=>l2.repeat(Math.ceil(span2/tw)).slice(0,span2)),repV=(p,span2)=>Array.from({length:span2},(_2,i)=>p[i%tv]),t2=repH(T2,mw),b2=repH(B2,mw),l=repV(L2,mh),r=repV(R,mh),mid2=" ".repeat(mw),out=[];for(let i=0;i<ch;i++)out.push(TL[i]+t2[i]+TR[i]);for(let i=0;i<mh;i++)out.push(l[i]+mid2+r[i]);for(let i=0;i<ch;i++)out.push(BL[i]+b2[i]+BR2[i]);return{lines:out,inner}}import{readFileSync as readFileSync9}from"fs";import{join as join13}from"path";var FALLBACK=["`@file:path/to/file.py` injects file contents directly into your message.","`/title <name>` names the session \u2014 resume it later from the Sessions tab.","Ctrl+G opens $EDITOR seeded with the composer contents.","Ctrl+Z suspends to the shell; `fg` resumes.","Pasting 5+ lines collapses to a `[Pasted #N \u2026]` placeholder.","Click a user message in the transcript to rewind to that point."],HL=/(\/[a-z][\w-]*|@[\w:./-]+|(?:Ctrl|Alt|Shift)\+\S+|`[^`]+`|"[^"]+")/g;function splitTip(tip2){let out=[],i=0;for(let m2 of tip2.matchAll(HL)){let j2=m2.index;if(j2>i)out.push({t:tip2.slice(i,j2),hl:!1});out.push({t:m2[0].replace(/^`|`$/g,""),hl:!0}),i=j2+m2[0].length}if(i<tip2.length)out.push({t:tip2.slice(i),hl:!1});return out}var cache4=null;function loadTips(){if(cache4)return cache4;try{let body=readFileSync9(join13(hermesAgentRoot(),"hermes_cli","tips.py"),"utf8").split(/^TIPS\s*=\s*\[/m)[1]?.split(/^\]/m)[0]??"",tips=[];for(let line3 of body.split(`
4130
+ `}async function save2(s){let r=rasterizer(s.rasterizer)??pick(s.rasterizer),paths=ensure(s.name),sources={};for(let[role,p]of Object.entries(s.sources)){if(!p)continue;let abs2=p.includes("/")?p:join12(paths.source,p);sources[role]=existsSync14(abs2)?adopt(s.name,abs2,role):p}let seen=new Map,clips2=new Map,blank=[Array.from({length:H},(_2,i)=>(i===H>>1?s.glyph.padStart(W2>>1):"").padEnd(W2))];for(let st of STATES2){let src2=findSource(s.name,st),k2=eff(s,st),key2=`${src2??""}|${JSON.stringify(k2)}`,fs7=seen.get(key2);if(!fs7){if(!src2)fs7=blank;else{let out=await cached2(r,src2,s.spatial,s.fps,k2);if("err"in out)throw Error(out.err);fs7=out.frames}seen.set(key2,fs7)}clips2.set(st,fs7)}let url=header(paths.file)?.source_url;return await Bun.write(paths.file,serialize2(s.name,s.glyph,s.fps,clips2,url)),writeStudio(s.name,{...toStudio(s),sources}),set("eikon",s.name),bump(),paths.file}function remove2(name){if(rmSync3(dir(name),{recursive:!0,force:!0}),get("eikon")===name)set("eikon",void 0);bump()}var peekSource=peek3;async function fetchSource(src2,opts){let out=await install(src2,ROOT(),opts),prev=readStudio(out.name);return writeStudio(out.name,{...prev??toStudio(fresh(out.name,pick())),sources:{...prev?.sources,...out.sources}}),bump(),{name:out.name,sources:out.sources,n:out.n,bytes:out.bytes}}extend({slider:SliderRenderable});var PANES=["knobs","preview","strip"],COL={flexDirection:"column"},mb2=(n)=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,HEAD2=[{id:"rasterizer",kind:"select",label:"rasterizer"},{id:"source",kind:"prompt",label:"source"},{id:"name",kind:"prompt",label:"name"},{id:"-1",kind:"divider",label:""},{id:"fetch",kind:"action",label:"fetch source",show:(s,live,url)=>!live&&!!url},{id:"fork",kind:"action",label:"fork state",show:(_s,live)=>live},{id:"reset",kind:"action",label:"reset knobs",show:(_s,live)=>live},{id:"-2",kind:"divider",label:"",show:(_s,live)=>live}];function buildRows(r,s,live,url){let dyn=live?Object.entries(r.knobs).map(([id,def2])=>({id,kind:"knob",label:def2.label??id,knob:def2})):[];return[...HEAD2.filter((h2)=>h2.show?h2.show(s,live,url):!0),...dyn]}var MINI_W=12;function Mini(props){let theme=useTheme().theme,d2=props.dims??{w:1,h:1},ar=d2.w/d2.h,bw=ar>=1?MINI_W:Math.max(4,Math.round(MINI_W*ar)),bh=ar>=1?Math.max(4,Math.round(MINI_W/ar)):MINI_W,short2=Math.min(bw,bh),cw=Math.max(1,short2*props.sp.zoom),cx=(bw-cw)*props.sp.ox,cy=(bh-cw)*props.sp.oy,on=(x2,y2)=>x2>=cx&&x2<cx+cw&&y2>=cy&&y2<cy+cw,cell=(x2,ty)=>{let up=on(x2,ty*2),dn=on(x2,ty*2+1);return up&&dn?"\u2588":up?"\u2580":dn?"\u2584":"\xB7"};return $jsx("box",{flexDirection:"column",flexShrink:0,backgroundColor:theme.backgroundElement,children:Array.from({length:Math.ceil(bh/2)},(_2,ty)=>$jsx("text",{fg:theme.textMuted,children:Array.from({length:bw},(_3,x2)=>cell(x2,ty)).join("")},ty))})}var SP_ROWS=["pan x","pan y","zoom","fps"];function PanBars(props){let theme=useTheme().theme,z2=props.sp.zoom,slack=1-z2,on=(i)=>props.focused&&props.sel===i,fg2=(i)=>on(i)?theme.accent:theme.textMuted,wheel=(k2)=>(e)=>{let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(k2,-1);if(d2==="down"||d2==="right")props.onWheel(k2,1)},drag=import_react94.useRef(null),grab=(k2,at)=>{drag.current={at,v:props.sp[k2],k:k2}},scrub=(at,L2)=>{let d2=drag.current;if(!d2||slack<=0)return;props.onSet(d2.k,Math.max(0,Math.min(1,+(d2.v+(at-d2.at)/(slack*L2)).toFixed(3))))},drop=()=>{drag.current=null},tw=Math.max(1,Math.round(z2*W2)),tl=Math.min(W2-tw,Math.round(props.sp.ox*slack*W2)),hbar=" ".repeat(tl)+"\u2588".repeat(tw)+" ".repeat(W2-tl-tw),vh=H*2,th=Math.max(1,z2*vh),ty=props.sp.oy*slack*vh,vbar=Array.from({length:H},(_2,y2)=>{let up=y2*2>=ty&&y2*2<ty+th,dn=y2*2+1>=ty&&y2*2+1<ty+th;return up&&dn?"\u2588\u2588":up?"\u2580\u2580":dn?"\u2584\u2584":" "});return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.children,$jsx("box",{width:W2,height:1,backgroundColor:theme.border,onMouseMove:()=>props.onHover(0),onMouseScroll:wheel("ox"),onMouseDown:(e)=>grab("ox",e.x),onMouseDrag:(e)=>scrub(e.x,W2),onMouseUp:drop,onMouseDragEnd:drop,children:$jsx("text",{fg:fg2(0),children:hbar})})]}),$jsx("box",{flexDirection:"column",width:2,height:H,backgroundColor:theme.border,onMouseMove:()=>props.onHover(1),onMouseScroll:wheel("oy"),onMouseDown:(e)=>grab("oy",e.y),onMouseDrag:(e)=>scrub(e.y,H),onMouseUp:drop,onMouseDragEnd:drop,children:vbar.map((g,y2)=>$jsx("text",{fg:fg2(1),children:g},y2))})]})}function SpatialBar(props){let theme=useTheme().theme,rows3=[{label:"zoom",k:"zoom",min:0.1,max:1,v:props.sp.zoom,i:2},{label:"fps",k:"fps",min:4,max:30,v:props.fps,i:3}],wheel=(k2)=>(e)=>{let d2=e.scroll?.direction;if(d2==="up")props.onWheel(k2,-1);if(d2==="down")props.onWheel(k2,1)};return $jsxs("box",{flexDirection:"row",marginTop:1,flexShrink:0,children:[$jsx("box",{flexDirection:"column",gap:1,flexShrink:0,children:rows3.map((d2)=>{let on=props.focused&&d2.i===props.sel;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onHover(d2.i),onMouseScroll:wheel(d2.k),children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:d2.label})}),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:d2.min,max:d2.max,value:d2.v,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>props.onSet(d2.k,d2.k==="fps"?Math.round(v2):+v2.toFixed(3))})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:` ${d2.k==="fps"?d2.v.toFixed(0):d2.v.toFixed(2)}`})})]},d2.label)})}),$jsx("box",{width:2}),$jsx(Mini,{sp:props.sp,dims:props.dims})]})}function valueOf(s,r,row2,src2,peek5,busy){if(row2.id==="rasterizer")return`${r.name} \u25B8`;if(row2.id==="source")return src2?src2.replace(process.env.HOME??"","~"):"(none \u2014 Enter to attach)";if(row2.id==="name")return s.name;if(row2.id==="fork")return s.per[s.state]?"(forked)":"\u25B8 copy base \u2192 "+s.state;if(row2.id==="reset")return"\u25B8 defaults";if(row2.id==="fetch")return busy?"fetching\u2026":peek5?`\u25B8 download to edit (${peek5.n} files, ${mb2(peek5.bytes)})`:"\u25B8 download to edit";if(row2.kind==="knob"&&row2.knob){let k2=exports_eikon_knobs.eff(s,s.state)[row2.id]??row2.knob.default;if(row2.knob.kind==="cycle")return`\u25C2 ${String(k2)} \u25B8`;if(row2.knob.kind==="toggle")return k2?"\u25CF on":"\u25CB off";if(row2.knob.kind==="slider")return Number(k2).toFixed(2)}return""}function KnobRow(props){let theme=useTheme().theme,{row:row2,on,dim:dim2}=props;if(row2.kind==="divider")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(24)})});let slider=row2.knob?.kind==="slider"?row2.knob:void 0;return $jsxs("box",{id:props.id,height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onClick,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:12,children:$jsx("text",{fg:dim2?theme.textMuted:on?theme.text:theme.textMuted,children:row2.label})}),slider?$jsxs($Fragment,{children:[$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:slider.min,max:slider.max,value:Number(exports_eikon_knobs.eff(props.s,props.s.state)[row2.id]??slider.default),foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:props.onSlide})}),$jsx("box",{width:1})]}):null,$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:props.busy&&row2.id==="fetch"?$jsx(Spinner,{color:theme.accent,label:"fetching\u2026"}):$jsx("text",{fg:dim2?theme.textMuted:theme.text,children:valueOf(props.s,props.r,row2,props.src,props.peek,props.busy)})})]})}function Strip(props){let theme=useTheme().theme;return $jsx("box",{flexDirection:"row",gap:1,children:STATES2.map((st)=>{let on=props.s.state===st,own=!!props.s.per[st],has=!!props.s.sources[st],f=props.frames.get(st);return $jsxs("box",{flexDirection:"column",alignItems:"center",onMouseDown:()=>props.onPick(st),children:[$jsx("box",{border:!0,borderStyle:"rounded",borderColor:on&&props.focused?theme.primary:on?theme.accent:theme.border,width:18,height:10,overflow:"hidden",alignItems:"center",justifyContent:"center",children:f?f.map((ln,i)=>$jsx("text",{fg:on?theme.text:theme.textMuted,children:ln},i)):$jsx("text",{fg:theme.textMuted,children:"\xB7"})}),$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.accent:theme.textMuted,children:`${own?"*":" "}${has?"\uD83D\uDCCE":" "}${st}`})})]},st)})})}var BLANK3=Array.from({length:H},()=>" ".repeat(W2)),EikonStudio=import_react94.memo((props)=>{let theme=useTheme().theme,keys=useKeys(),dialog=useDialog(),toast=useToast(),wide=useTerminalDimensions().width>=120,ksb=import_react94.useRef(null),outer=import_react94.useRef(null);import_react94.useSyncExternalStore(exports_eikon.onRegistry,()=>exports_eikon.rasterizers().length);let[s,setS]=import_react94.useState(null),[pane,setPane]=import_react94.useState("knobs"),[sel,setSel]=import_react94.useState(0),[spSel,setSpSel]=import_react94.useState(0),selRef=import_react94.useRef(0);selRef.current=sel;let spRef=import_react94.useRef(0);spRef.current=spSel;let sRef=import_react94.useRef(null);sRef.current=s;let[frames,setFrames]=import_react94.useState([BLANK3]),[tick2,setTick]=import_react94.useState(0),[play,setPlay]=import_react94.useState(!0),[busy,setBusy]=import_react94.useState(!1),[fetching,setFetching]=import_react94.useState(!1),[peek5,setPeek]=import_react94.useState(void 0),[thumbs,setThumbs]=import_react94.useState(new Map),[err,setErr]=import_react94.useState(null),frame=frames[tick2%frames.length]??BLANK3,r=import_react94.useMemo(()=>exports_eikon.pick(s?.rasterizer??get("eikonRasterizer")),[s?.rasterizer]),spatialOk=caps.ffmpeg,open2=import_react94.useCallback((name)=>{resetCache();let seed=exports_eikon.readStudio(name),ra=exports_eikon.pick(seed?.rasterizer??get("eikonRasterizer")),next2=exports_eikon_knobs.fresh(name,ra,seed),src3=exports_eikon.findSource(name,"idle");next2.dims=src3?exports_eikon.probe(src3)??null:null;for(let st of STATES2){let p=exports_eikon.findSource(name,st);if(p)prewarm(p,next2.fps)}setS(next2),setSel(0),setPane("knobs"),setErr(null),setTick(0),setFrames([BLANK3])},[]),tried=import_react94.useRef(!1);import_react94.useEffect(()=>{if(tried.current)return;if(tried.current=!0,props.name)return open2(props.name||exports_eikon_knobs.slug("new"));let n2=get("eikon");if(n2)open2(n2)},[open2,props.name]),import_react94.useEffect(()=>{if(props.name!==void 0)open2(props.name||exports_eikon_knobs.slug("new"))},[props.name,open2]);let src2=import_react94.useMemo(()=>s?exports_eikon.findSource(s.name,s.state):void 0,[s?.name,s?.state,s?.sources]),live=import_react94.useMemo(()=>!!(s&&exports_eikon.findSource(s.name)),[s?.name,s?.sources]),baked2=import_react94.useMemo(()=>{if(live||!s)return;let p=exports_eikon.baked(s.name);if(!p)return;try{return exports_eikon.parseEikon(readFileSync7(p,"utf8"))}catch{return}},[live,s?.name]),url=import_react94.useMemo(()=>{if(!s)return;let p=exports_eikon.baked(s.name);return p?exports_eikon.header(p)?.source_url:void 0},[s?.name]);import_react94.useEffect(()=>{if(setPeek(void 0),!url||live)return;let dead=!1;return exports_eikon.peekSource(url).then((x2)=>{if(!dead)setPeek(x2)}),()=>{dead=!0}},[url,live]);let rows3=import_react94.useMemo(()=>s?buildRows(r,s,live,url):[],[r,s,live,url]),navRows=import_react94.useMemo(()=>rows3.map((x2,i)=>({...x2,i})).filter((x2)=>x2.kind!=="divider"),[rows3]),kScroll=(ni)=>{let row2=navRows[ni];if(row2)ksb.current?.scrollChildIntoView(`knob-${row2.id}`)};import_react94.useEffect(()=>{if(!s)return;if(!src2){let clip=baked2?.states.get(s.state);setFrames(clip?.frames.length?clip.frames:[BLANK3]),setErr(null),setBusy(!1),setTick(0);return}let ctrl=new AbortController;return setBusy(!0),cached2(r,src2,s.spatial,s.fps,exports_eikon_knobs.eff(s,s.state),ctrl.signal).then((out)=>{if(ctrl.signal.aborted)return;if(setBusy(!1),"err"in out){setErr(out.err);return}setErr(null),setFrames(out.frames),setTick((t2)=>t2%out.frames.length)}),()=>ctrl.abort()},[s?.spatial,s?.base,s?.per,s?.state,s?.fps,s?.rasterizer,src2,r,baked2]),import_react94.useEffect(()=>{if(!play||!props.focused||frames.length<=1||busy)return;let fps=live?s?.fps??FPS0:baked2?.states.get(s?.state??"idle")?.fps??FPS0,id=setInterval(()=>setTick((t2)=>t2+1),1000/Math.max(1,fps));return()=>clearInterval(id)},[play,props.focused,frames.length,busy,live,s?.fps,s?.state,baked2]),import_react94.useEffect(()=>{if(!s)return;let dead=!1,t2=setTimeout(()=>{if(dead)return;let jobs=STATES2.map((st)=>{let sp=exports_eikon.findSource(s.name,st);if(!sp){let f=baked2?.states.get(st)?.frames[0];return Promise.resolve([st,f?thumb(f):void 0])}return cached2(r,sp,s.spatial,s.fps,exports_eikon_knobs.eff(s,st)).then((res)=>[st,"err"in res?void 0:thumb(res.frames[0])])});Promise.all(jobs).then((done)=>{if(dead)return;setThumbs(new Map(done))})},400);return()=>{dead=!0,clearTimeout(t2)}},[frames,s?.per,s?.sources,s?.name,s?.fps,r,baked2]);let mutate=(fn)=>setS((p)=>p?fn(p):p),setSpatial=(sp)=>mutate((p)=>({...p,spatial:{...p.spatial,...sp},dirty:!0})),setBar=(k2,v2)=>k2==="fps"?mutate((p)=>({...p,fps:Math.round(v2),dirty:!0})):setSpatial({[k2]:v2}),stepBar=(k2,d2)=>{let cur=sRef.current;if(!cur)return;if(k2==="fps")return setBar("fps",Math.max(4,Math.min(30,cur.fps+d2*2)));if(k2==="zoom")return setSpatial({zoom:Math.max(0.1,Math.min(1,+(cur.spatial.zoom+d2*0.03).toFixed(3)))});return setSpatial({[k2]:Math.max(0,Math.min(1,+(cur.spatial[k2]+d2*0.03).toFixed(3)))})},doSave=import_react94.useCallback(async()=>{if(!s)return;if(!live)return toast.show({variant:"warning",message:"No source \u2014 fetch or attach before saving"});await exports_eikon.save({...s,dirty:!1}).then((f)=>{mutate((p)=>({...p,dirty:!1})),toast.show({variant:"success",message:`Saved \u2192 ${basename10(f)}`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[s,live,toast]),doSelectRasterizer=()=>{let opts=exports_eikon.rasterizers().map((x2)=>{let a=x2.available();return{title:x2.name,value:x2.name,description:Object.keys(x2.knobs).join(" \xB7 "),hint:a===!0?void 0:a}});dialog.replace($jsx(DialogSelect,{title:"Rasterizer",filterable:!1,current:r.name,options:opts,onSelect:(o)=>{dialog.clear();let next2=exports_eikon.rasterizer(o.value);if(!next2)return;let a=next2.available();if(a!==!0)return toast.show({variant:"warning",message:`${o.value}: ${a}`});set("eikonRasterizer",o.value),mutate((p)=>exports_eikon_knobs.swap(p,next2))}}),()=>{})},doPrompt=async(id)=>{if(!s)return;if(id==="source"){let v2=await openTextPrompt(dialog,{title:"Source image",label:`for state '${s.state}' (png/jpg/webp/gif/mp4)`});if(!v2)return;let role=s.state==="idle"&&!s.sources.base?"base":s.state;try{let f=exports_eikon.adopt(s.name,v2,role);mutate((p)=>({...p,sources:{...p.sources,[role]:f},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}return}if(id==="name"){let v2=await openTextPrompt(dialog,{title:"Name",initial:s.name});if(v2)mutate((p)=>({...p,name:exports_eikon_knobs.slug(v2),dirty:!0}))}},doAction=async(id)=>{if(!s)return;if(id==="fork")return mutate(exports_eikon_knobs.fork);if(id==="reset"){if(await openConfirm(dialog,{title:"Reset knobs?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!url||fetching)return;setFetching(!0),await exports_eikon.fetchSource(url,{name:s.name}).then((out)=>{toast.show({variant:"success",message:`Fetched ${out.n} file(s) \xB7 ${mb2(out.bytes)}`}),open2(s.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e)))).finally(()=>setFetching(!1))}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Attach source image\u2026",value:"attach"},{title:s.per[s.state]?"Clear override (back to base)":"Fork knobs from base",value:"fork"}],onSelect:(o)=>{if(dialog.clear(),o.value==="attach")return void doPrompt("source");mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},stepRow=(row2,d2)=>{if(row2.kind!=="knob"||!row2.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row2.id,row2.knob,d2)))},act=(row2,via)=>{if(!row2||!sRef.current)return;if(row2.kind==="select")return doSelectRasterizer();if(row2.kind==="prompt")return void doPrompt(row2.id);if(row2.kind==="action"){if(via==="space"&&row2.id==="reset")return;return void doAction(row2.id)}if(row2.kind==="knob"){if(row2.knob.kind==="slider")return;return stepRow(row2,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row2=navRows[selRef.current];if(row2)stepRow(row2,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;if(await openConfirm(dialog,{title:"Discard unsaved edits?",danger:!0,body:`Reload '${cur.name}' from disk and drop in-memory changes.`}))open2(cur.name);return!0};useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.eventType==="release")return;if(keys.match("eikon.save",key2))return void doSave();if(key2.name==="escape")return void discard();if(key2.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key2.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key2.name==="return")return void doPrompt("source");return}if(pane==="knobs"){if(handleListKey(keys,key2,{count:navRows.length,setSel,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doPrompt("source")}))return;if(key2.name==="left")return adjust(-1);if(key2.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key2))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key2,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key2.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key2.name==="left"||key2.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key2.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key2.name))}return}if(key2.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key2.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key2.name==="return")return doStripMenu()});let onScroll=(e)=>{if(!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,d2==="up"?-1:1),dirty:!0}))},n=frames.length,title=s?`Preview \u2014 ${s.state}${s.per[s.state]?" (forked)":""}`+(n>1?` \xB7 ${play?"\u25B6":"\u23F8"} ${tick2%n+1}/${n}`:"")+(live?"":baked2?" \xB7 (baked)":""):"Preview",previewErr=err??(!s||src2||baked2?null:url?"no source \u2014 Enter on 'fetch source' to download":"no source \u2014 Enter on 'source' to attach"),hint=pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"open"],[keys.print("eikon.save"),"save"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","zoom"],[keys.print("eikon.save"),"save"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),body=$jsxs("box",{position:"relative",flexDirection:"column",width:W2,height:H,flexShrink:0,backgroundColor:theme.background,onMouseScroll:onScroll,onMouseDown:()=>setPlay((p)=>!p),children:[frame.map((ln,i)=>$jsx("text",{fg:err?theme.textMuted:theme.hermAvatar,children:ln},i)),busy&&frames[0]===BLANK3?$jsx("box",{position:"absolute",left:0,top:H>>1,width:W2,justifyContent:"center",children:$jsx(Spinner,{color:theme.textMuted,label:"decoding\u2026"})}):null]}),preview2=$jsx(TabShell,{title:spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:previewErr,focus:pane==="preview",children:spatialOk&&live&&s?$jsxs($Fragment,{children:[$jsx(PanBars,{sp:s.spatial,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar,children:body}),$jsx(SpatialBar,{sp:s.spatial,fps:s.fps,dims:s.dims,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar})]}):body}),panel=$jsx(TabShell,{title:`Knobs${s?.dirty?" \xB7 \u25CF unsaved":""}`,focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create one."})}):$jsx("scrollbox",{ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,children:rows3.map((row2,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row2.kind==="knob"&&!src2;return $jsx(KnobRow,{id:`knob-${row2.id}`,row:row2,s,r,src:src2,on,dim:dim2,peek:peek5,busy:row2.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSel(ni)},onClick:()=>{if(ni>=0)setSel(ni),setPane("knobs"),act(row2,"click")},onSlide:row2.knob?.kind==="slider"?(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row2.id,row2.knob,v2))):void 0},`${r.name}:${row2.id}`)})})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:17,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))}})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:s?.dirty?"\u25CF unsaved":void 0})]})});var import_react96=__toESM(require_react_production(),1);import{readFileSync as readFileSync8}from"fs";import{basename as basename11,dirname as dirname7}from"path";var EikonGallery=import_react96.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),follow=useFollow("gal"),rev2=import_react96.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),rows3=import_react96.useMemo(()=>{let user=hermesPath("eikons"),own=new Map(exports_eikon.list().map((x2)=>[x2.name.toLowerCase(),x2]));return listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():basename11(dirname7(e.path)),mine=own.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,states:e.meta.states.length,url:mine?.sourceUrl??e.meta.source_url,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3)}})},[rev2]),[sel,setSel]=import_react96.useState(0);import_react96.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],active=usePref("eikon"),parsed=import_react96.useMemo(()=>{if(!cur)return;try{return parseEikon(readFileSync8(cur.path,"utf8"))}catch{return}},[cur]),activate=()=>{if(!cur)return;set("eikon",cur.slug),toast.show({variant:"success",message:`Avatar \u2192 ${cur.name}`})},doInstall=async()=>{let src2=await openTextPrompt(dialog,{title:"Install eikon",label:"catalog name \xB7 github.com/u/r \xB7 git URL \xB7 http://\u2026/ \xB7 local dir"});if(!src2)return;toast.show({variant:"info",message:`Installing from ${src2}\u2026`}),await exports_eikon.fetchSource(src2).then((out)=>toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},doNew=()=>dialog.replace($jsx(DialogSelect,{title:"New eikon",filterable:!1,options:[{title:"Blank \u2014 author in Studio",value:"blank"},{title:"Install from\u2026",value:"install",description:"catalog name, git URL, local dir, or http manifest"}],onSelect:(o)=>{if(dialog.clear(),o.value==="blank")return props.onEdit?.("");doInstall()}}),()=>{}),del=async()=>{if(!cur||cur.bundled)return;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body:`Removes ${dirname7(cur.path)} and all its sources. This cannot be undone.`}))return;exports_eikon.remove(cur.slug),toast.show({variant:"info",message:`Deleted ${cur.name}`})};return useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(handleListKey(keys,key2,{count:rows3.length,setSel,...follow.opts,onActivate:activate,onDelete:()=>void del(),onNew:doNew}))return;if(key2.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Gallery (${rows3.length})`,focus:props.focused,grow:2,children:$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:rows3.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):rows3.map((r,i)=>{let on=i===sel,here=r.slug===active;return $jsxs("box",{id:follow.id(i),flexDirection:"row",height:2,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:activate,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx("box",{height:1,children:$jsxs("text",{fg:here?theme.accent:theme.text,children:[here?"\u25CF ":" ",$jsx("strong",{children:r.name}),$jsx("span",{fg:theme.textMuted,children:r.bundled?" (bundled)":""})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[` ${r.author??"\u2014"} \xB7 ${r.states} states \xB7 ${r.w}\xD7${r.h} \xB7 `,$jsx("span",{fg:r.hasSource?theme.success:r.url?theme.textMuted:theme.border,children:r.hasSource?"\u25CF source":r.url?"\u25CB source available":"\u2014 no source"})]})})]})]},r.path)})})}),$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:3,children:$jsx("box",{alignItems:"center",justifyContent:"center",flexGrow:1,children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.activate"),"use"],["e","edit in studio"],[keys.print("list.new"),"new / install"],...cur&&!cur.bundled?[[keys.print("list.delete"),"delete"]]:[]]})]})});var EikonGroup=import_react98.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[EIKON_TAB],[target,setTarget]=import_react98.useState(void 0);import_react98.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let edit2=import_react98.useCallback((name)=>{setTarget(name),props.setSub(0)},[props]),hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} group \xB7 shift+\u2190/\u2192 sub`;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:[$jsx(Pane4,{visible:props.sub===0,children:$jsx(EikonStudio,{focused:!!props.focused&&props.sub===0,name:target})}),$jsx(Pane4,{visible:props.sub===1,children:$jsx(EikonGallery,{focused:!!props.focused&&props.sub===1,onEdit:edit2})})]})]})}),Pane4=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react99=__toESM(require_react_production(),1);var FRAME={cw:16,ch:8,tw:20,tv:8},TL=["\u2800\u2880\u28E4\u2824\u2884\u28C0\u2804\u2880\u28E0\u28E4\u28C4\u2864\u2844\u2840\u2800\u2800","\u2800\u28DC\u2841\u28A9\u28C8\u2842\u2880\u28CB\u28ED\u2809\u2808\u2888\u28EE\u28FB\u2851\u28F6","\u2800\u28B8\u2856\u28BF\u280F\u28E4\u28F6\u28FD\u28EB\u28B6\u28E2\u284C\u2839\u28E7\u284F\u283B","\u2800\u2808\u2864\u2892\u28E6\u28BB\u28FF\u28FF\u28FF\u28BF\u28C5\u2847\u28C6\u2849\u2802\u2880","\u2801\u28B8\u284F\u2818\u280B\u289E\u28B3\u28FF\u28FF\u28DF\u284D\u284D\u28E4\u2805\u2800\u28A8","\u2800\u2824\u28AF\u28C6\u28C0\u2819\u28A6\u28FF\u284B\u2880\u28DC\u2807\u28C1\u28D2\u28CA\u28C9","\u2800\u2880\u28F7\u28DD\u28FB\u28F6\u28F6\u2884\u280D\u2818\u2841\u2847\u28E7\u28E0\u28E4\u2862","\u2800\u2800\u2818\u288E\u28BF\u28EF\u2803\u2801\u2864\u28DA\u287C\u2800\u284F\u28F9\u28FF\u2869"],TR=["\u2800\u2800\u2880\u28A0\u28A0\u28E0\u28E4\u28C0\u2840\u2820\u28C0\u2860\u2824\u28E4\u28C0\u2800","\u28F6\u288A\u28DF\u28F5\u2841\u2801\u2809\u28ED\u28D9\u2800\u2890\u28C2\u284D\u2888\u28E3\u2800","\u281F\u28B9\u28FC\u280F\u28A1\u28D4\u28B6\u28DD\u28EF\u28F6\u28E4\u2839\u287F\u28B2\u2847\u2800","\u2840\u2801\u2889\u28F0\u28B8\u28E8\u287F\u28FF\u28FF\u28FF\u285F\u28F4\u2852\u28A4\u2801\u2800","\u2845\u2804\u2828\u28E4\u28A9\u28A9\u28FB\u28FF\u28FF\u285E\u2873\u2819\u2803\u28B9\u2847\u2800","\u28C9\u28D1\u28D2\u28C8\u2838\u28E3\u2840\u2899\u28FF\u2874\u280B\u28C0\u28F0\u287D\u2824\u2880","\u2884\u28E4\u28C4\u28F8\u28B8\u2888\u2803\u2829\u2860\u28F6\u28F6\u28DF\u28EB\u28FE\u2802\u2800","\u288D\u28FF\u289F\u28B9\u2800\u28A7\u28D2\u28A4\u2801\u2808\u28FD\u287F\u2871\u2807\u2800\u2800"],BL=["\u2800\u2800\u28C0\u28FF\u28FF\u285F\u2801\u2800\u283B\u28AC\u28F3\u2800\u28C7\u28F2\u28DF\u28BF","\u2800\u2890\u287A\u28DB\u286F\u28ED\u2837\u280C\u2882\u2880\u2842\u2847\u284F\u2819\u281B\u2827","\u2800\u2816\u287C\u2809\u2809\u28A0\u28F0\u2825\u28AD\u2818\u28DB\u28C4\u288B\u28C9\u28C9\u2859","\u2800\u28B8\u284C\u2880\u28E0\u28F5\u28FF\u28FF\u28FF\u28FF\u28E8\u2803\u2837\u2802\u2810\u288D","\u2800\u2800\u283B\u281D\u283F\u28F4\u28FF\u28FF\u287F\u28FF\u28DF\u28CB\u284F\u2841\u2804\u2818","\u2800\u28B8\u28F0\u28F6\u28C4\u283B\u283F\u28FF\u28F9\u2830\u281F\u2882\u28A0\u285F\u28C6\u28F4","\u2800\u28AA\u2849\u2838\u28FB\u2807\u2800\u285D\u28DB\u2880\u2840\u28D8\u285F\u2877\u28EB\u286F","\u2800\u2819\u283B\u282A\u281C\u2813\u2802\u2808\u281B\u2813\u281B\u2819\u281A\u2808\u2801\u2800"],BR2=["\u287F\u28FB\u28D6\u28F8\u2800\u28DE\u2861\u281F\u2880\u2804\u28BB\u28FF\u28FF\u28C0\u2800\u2800","\u2836\u281B\u280B\u28B9\u28B8\u2890\u2840\u2850\u2821\u283E\u28ED\u28BD\u28DB\u2897\u2842\u2800","\u288B\u28C9\u28C9\u2859\u28E0\u28DB\u2803\u286D\u282C\u28C6\u2844\u2809\u2829\u28A7\u2832\u2800","\u2869\u2802\u2810\u283E\u2818\u28C5\u28FF\u28FF\u28FF\u28FF\u28EE\u28C4\u2840\u28B1\u2847\u2800","\u2803\u2880\u2888\u28B3\u28D9\u28FB\u28FF\u28DF\u28FF\u28FF\u28E6\u283F\u282B\u281F\u2800\u2800","\u28E6\u28F0\u28BB\u2844\u2850\u283B\u2803\u28CF\u28FF\u283F\u281F\u28E0\u28F6\u28C6\u2847\u2800","\u28BD\u28DD\u28AF\u28BB\u28C3\u2880\u2840\u28DB\u28E9\u2800\u2838\u28DF\u2807\u2889\u2855\u2800","\u2801\u2800\u2801\u2813\u280B\u281B\u281A\u281B\u2801\u2810\u281A\u2823\u2807\u281F\u280B\u2800"],T2=["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2844\u28E2\u28F4\u28F6\u2836\u2816\u2832\u28CC\u2818\u2809\u2822\u285B\u28A1\u2834\u2832\u2836\u28F0\u2896\u28B4\u28E4","\u28FE\u28E5\u283F\u2800\u28E0\u28B0\u283F\u28BE\u2850\u283E\u283F\u2887\u2873\u28FF\u28D7\u2804\u2800\u2823\u28D1\u28F5","\u28BE\u285F\u2804\u2810\u28AD\u28CD\u2896\u2844\u2828\u28BB\u28EB\u283D\u287C\u287F\u28BD\u28A5\u2842\u2804\u283B\u287D","\u2813\u287B\u28B6\u28C4\u2848\u2818\u282D\u281A\u280D\u28BB\u2849\u280B\u280B\u282D\u2803\u2803\u2861\u28F6\u28DF\u28BE","\u2801\u2804\u2809\u2809\u281A\u2824\u2824\u282C\u281F\u2830\u2827\u280A\u282F\u2834\u2824\u2813\u281B\u2809\u2810\u2822","\u28DB\u28DB\u285F\u28DB\u285B\u28DB\u28DB\u289B\u28DB\u28DB\u285B\u28DB\u28DB\u289B\u28FB\u28FB\u28DF\u281B\u28FB\u28BB","\u28CA\u28C9\u28C9\u28DB\u28CB\u28D9\u28CB\u28FC\u28F7\u28E5\u28EF\u28FA\u28CB\u28F5\u28F7\u28ED\u28D9\u28D1\u28FB\u28FD"],B2=["\u28FF\u28BF\u28FF\u28FF\u28BF\u28FF\u287F\u287F\u28FF\u28FF\u283F\u28FF\u28BF\u287F\u28FF\u28FF\u287F\u28FF\u287F\u28BF","\u28C3\u28DB\u28C8\u28D3\u28DA\u28DA\u28C3\u28D9\u28DB\u28C9\u28DB\u28DB\u28C1\u28DB\u28D9\u28D9\u28CB\u28D8\u28C9\u28D9","\u2820\u2884\u2884\u28C0\u2864\u28E4\u2810\u28E0\u2884\u28A0\u2844\u2864\u28C4\u2800\u2864\u2884\u28C0\u2840\u2880\u2880","\u28F1\u282C\u282B\u2811\u2881\u28E0\u28A0\u286B\u28E1\u28E0\u28E4\u28C9\u2885\u2884\u28C4\u2809\u283B\u2850\u28A5\u28CC","\u2894\u28C8\u2800\u28B0\u2841\u28B6\u28FF\u28FF\u28DF\u28FF\u28C3\u285B\u2815\u280D\u28E6\u28C3\u2844\u2802\u28F9\u2862","\u287F\u288F\u2884\u2800\u2803\u28EB\u28FF\u289C\u28A9\u28F6\u28E6\u2809\u2876\u28FE\u2856\u281B\u2800\u28E0\u285B\u287F","\u283C\u28BE\u283F\u28F5\u28D6\u28D8\u2834\u2803\u2808\u2886\u2880\u2800\u2873\u2824\u28C2\u28F2\u28FE\u282F\u281A\u280F","\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u280B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800"],L2=["\u2800\u2800\u2890\u289F\u28FE\u283F\u282E\u2836\u2877\u28EA\u283E\u2802\u2857\u28AD\u28BF\u28B9","\u2800\u2800\u28E8\u2855\u2809\u2861\u2824\u28C1\u284C\u282A\u28A7\u2801\u2847\u28F0\u28FF\u28BC","\u2800\u2800\u2839\u2843\u28BE\u28D5\u28F7\u2866\u28D3\u2840\u2849\u2846\u284F\u28F6\u2863\u28FB","\u2800\u28B0\u2876\u28AC\u28ED\u285C\u28FF\u28FF\u28EF\u2888\u2893\u2801\u284F\u28DA\u287E\u28FF","\u2800\u2818\u285B\u288A\u28D9\u2823\u2887\u28AF\u28FF\u2828\u286D\u2841\u2867\u28BC\u28F2\u28FF","\u2800\u2800\u28B1\u2849\u28BF\u2847\u2824\u28DD\u2844\u2800\u2841\u2801\u284F\u28F6\u2896\u28BF","\u2800\u2800\u28B0\u28E7\u2840\u2813\u2813\u2809\u2881\u28F4\u284D\u2800\u2847\u283A\u283D\u28BA","\u2800\u2800\u2828\u283A\u28FD\u28F7\u28E6\u2874\u285A\u2803\u2880\u2800\u2847\u287E\u28FF\u28B9"],R=["\u284F\u287F\u286D\u28BA\u2880\u2837\u289D\u28BE\u2836\u2835\u283F\u28F7\u287B\u2842\u2800\u2800","\u2867\u28FF\u28C6\u28B8\u2800\u287C\u2815\u28A1\u28C0\u2824\u288C\u2809\u28AA\u28C5\u2801\u2800","\u28DF\u289C\u28F6\u28B9\u28B0\u2889\u2880\u28DA\u28B4\u28FE\u28EA\u2877\u2898\u280F\u2800\u2800","\u28FF\u28B7\u285B\u28B9\u2808\u285A\u2841\u28FD\u28FF\u28FF\u28A3\u28ED\u2865\u28B6\u2846\u2800","\u28FF\u28D6\u2867\u28BC\u2888\u28AD\u2805\u28FF\u287D\u2878\u2858\u28CB\u2851\u289B\u2803\u2800","\u287F\u2872\u28F6\u28B9\u2808\u2888\u2800\u28A0\u28EB\u2824\u28B8\u287F\u2889\u2846\u2800\u2800","\u2857\u282F\u2817\u28B8\u2800\u28A9\u28E6\u2848\u2809\u281A\u281A\u2880\u28FC\u2846\u2800\u2800","\u284F\u28FF\u28AF\u28B8\u2800\u2880\u2818\u2893\u28A6\u28B6\u28FE\u28EF\u2817\u2805\u2800\u2800"];function frame(w2,h2){let{cw,ch,tw,tv}=FRAME,mw=w2-2*cw,mh=h2-2*ch,inner={x:cw,y:ch,w:Math.max(0,mw),h:Math.max(0,mh)};if(mw<4||mh<2)return{lines:[],inner};let repH=(p,span2)=>p.map((l2)=>l2.repeat(Math.ceil(span2/tw)).slice(0,span2)),repV=(p,span2)=>Array.from({length:span2},(_2,i)=>p[i%tv]),t2=repH(T2,mw),b2=repH(B2,mw),l=repV(L2,mh),r=repV(R,mh),mid2=" ".repeat(mw),out=[];for(let i=0;i<ch;i++)out.push(TL[i]+t2[i]+TR[i]);for(let i=0;i<mh;i++)out.push(l[i]+mid2+r[i]);for(let i=0;i<ch;i++)out.push(BL[i]+b2[i]+BR2[i]);return{lines:out,inner}}import{readFileSync as readFileSync9}from"fs";import{join as join13}from"path";var FALLBACK=["`@file:path/to/file.py` injects file contents directly into your message.","`/title <name>` names the session \u2014 resume it later from the Sessions tab.","Ctrl+G opens $EDITOR seeded with the composer contents.","Ctrl+Z suspends to the shell; `fg` resumes.","Pasting 5+ lines collapses to a `[Pasted #N \u2026]` placeholder.","Click a user message in the transcript to rewind to that point."],HL=/(\/[a-z][\w-]*|@[\w:./-]+|(?:Ctrl|Alt|Shift)\+\S+|`[^`]+`|"[^"]+")/g;function splitTip(tip2){let out=[],i=0;for(let m2 of tip2.matchAll(HL)){let j2=m2.index;if(j2>i)out.push({t:tip2.slice(i,j2),hl:!1});out.push({t:m2[0].replace(/^`|`$/g,""),hl:!0}),i=j2+m2[0].length}if(i<tip2.length)out.push({t:tip2.slice(i),hl:!1});return out}var cache4=null;function loadTips(){if(cache4)return cache4;try{let body=readFileSync9(join13(hermesAgentRoot(),"hermes_cli","tips.py"),"utf8").split(/^TIPS\s*=\s*\[/m)[1]?.split(/^\]/m)[0]??"",tips=[];for(let line3 of body.split(`
4131
4131
  `)){let m2=line3.match(/^\s+"((?:[^"\\]|\\.)*)",?\s*$/);if(m2)tips.push(m2[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"))}cache4=tips.length>10?tips:FALLBACK}catch{cache4=FALLBACK}return cache4}function randomTip(prev){let t2=loadTips();if(t2.length<2)return t2[0]??"";let pick2=t2[Math.floor(Math.random()*t2.length)];while(pick2===prev)pick2=t2[Math.floor(Math.random()*t2.length)];return pick2}import{readFileSync as readFileSync10,existsSync as existsSync15}from"fs";import{dirname as dirname8,join as join14}from"path";var pkgVersion=(d2,up=4)=>{let p=join14(d2,"package.json");if(existsSync15(p))return JSON.parse(readFileSync10(p,"utf8")).version;return up>0?pkgVersion(dirname8(d2),up-1):"0.0.0"},VERSION=pkgVersion(import.meta.dirname);function parseLaunch(argv){let splash=!0;for(let i=0;i<argv.length;i++){let a=argv[i];if(a==="--no-splash"){splash=!1;continue}if(a==="-c"||a==="--continue")return{mode:"resume",splash};if(a==="--resume"){let next2=argv[i+1];return next2&&!next2.startsWith("-")?{mode:"resume",sid:next2,splash}:{mode:"resume",splash}}}return{mode:"new",splash}}var HELP=`herm \u2014 OpenTUI client for hermes-agent
4132
4132
 
4133
4133
  Usage: