herm-tui 1.9.0-dev.31 → 1.9.0-dev.33

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 +10 -10
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -4104,8 +4104,8 @@ tell application "System Events" to get value of property list item "CFBundleNam
4104
4104
  `).length,onCopy=()=>{copy2(props.code),toast.show({variant:"success",message:`Copied ${lines3} line${lines3===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":`${lines3} 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);var PATH_KEY=/"(?:path|file_path|filename|target|file)"\s*:\s*"((?:\\.|[^"\\])*)"/,DIFF_HEAD_ARROW=/(?:^|\s)a\/+\S.*?\s*\u2192\s*b\/+(\S.+?)\s*$/m,DIFF_HEAD_NEW=/^\+\+\+ b?\/+(\S.*?)\s*$/m,DIFF_HEAD_OLD=/^--- a?\/+(\S.*?)\s*$/m;function pathFor(t2){let args=t2.args;if(args&&/^\s*\{/.test(args)){let m2=sanitize(args).match(PATH_KEY);if(m2)return m2[1]}let sources=[t2.diff,t2.preview].filter((s)=>!!s);for(let s of sources){let c=sanitize(s),m2=c.match(DIFF_HEAD_ARROW)||c.match(DIFF_HEAD_NEW)||c.match(DIFF_HEAD_OLD);if(m2)return m2[1]}return sanitize(t2.preview??t2.name)}var STRIPS=[/^\s*\u250A.*$/,/^\s*[+-]\d+\s*\/\s*[-+]\d+\s*$/,/^\s*\u2026/,/a\/+\S.*?\s*\u2192\s*b\/+\S/];function sanitizeDiff(s){return sanitize(s).split(`
4105
4105
  `).filter((l)=>!STRIPS.some((re2)=>re2.test(l))).join(`
4106
4106
  `)}var base=(p)=>p.split(/[\\/]/).filter(Boolean).pop()??p,parent=(p)=>{let parts2=p.split(/[\\/]/).filter(Boolean);return parts2.length>=2?parts2[parts2.length-2]:""},trunc2=(s,n)=>s.length<=n?s:"\u2026"+s.slice(-(n-1));function buildTabs(tools){let raw=tools.flatMap((t2)=>{let rawDiff=t2.diff??(isDiff(t2.result)?t2.result:void 0);if(!rawDiff)return[];return[{tool:t2,path:pathFor(t2),diff:sanitizeDiff(rawDiff)}]}),counts=new Map;return raw.forEach((r)=>counts.set(base(r.path),(counts.get(base(r.path))??0)+1)),raw.map(({tool,path:path7,diff})=>{let b2=base(path7),dup=(counts.get(b2)??0)>1&&parent(path7),label=trunc2(dup?`${parent(path7)}/${b2}`:b2,24),lines3=diff.split(`
4107
- `),add=lines3.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines3.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add,del}})}var DiffTabs=import_react37.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react37.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react37.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react38=__toESM(require_react_production(),1);var group="approval";function question(req){return(req.description||"Shell command").trim()}function subject(req){if(req.pattern_keys?.length)return req.pattern_keys.join("|");return req.command.trim()}function mkApproval(req){return{...req,group,question:question(req),subject:subject(req)}}function shouldRemember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);return cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject)}function remember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);if(cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject))return;set("neverPrompts",[...cur,{group:p.group,question:p.question,subject:p.subject}])}var MaskInput=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:props.value,onInput:props.input,onSubmit:props.submit,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(props.value.length)})})]})};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","never","deny"],LABELS={once:"Allow once",session:"Allow this session",never:"Never ask",deny:"Deny"},RESPOND={once:"once",session:"session",never:"always",deny:"deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),[steering,setSteering]=import_react38.useState(!1),[custom,setCustom]=import_react38.useState(""),[note,setNote]=import_react38.useState(""),done=import_react38.useRef(!1),prompt=mkApproval(p.req),send=(c)=>{if(done.current)return;if(done.current=!0,c==="never")remember(prompt);gw.request("approval.respond",{choice:RESPOND[c]}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text3)=>{let body=text3.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react38.useImperativeHandle(ref,()=>({masked:steering,feed:(key3)=>{if(steering){if(key3.name==="escape")return setSteering(!1),!0;return!1}if(key3.name==="s")return setSteering(!0),setNote(""),!0;if(key3.name==="left"||key3.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key3.name==="right"||key3.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key3.name==="return")return send(CHOICES[sel]),!0;if(key3.name==="escape")return send("deny"),!0;let n=digit(key3.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"}),$jsxs("text",{fg:theme.textMuted,children:["\xB7 ",prompt.question]})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["subject: ",prompt.subject]})}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react38.useState(0),[typing,setTyping]=import_react38.useState(choices.length===0),[custom,setCustom]=import_react38.useState(""),done=import_react38.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react38.useImperativeHandle(ref,()=>({masked:typing,feed:(key3)=>{if(typing){if(key3.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key3.name==="escape")return send(""),!0;if(key3.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key3.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key3.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key3.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react38.useState(""),done=import_react38.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react38.useImperativeHandle(ref,()=>({masked:!0,feed:(key3)=>{if(key3.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}),$jsx(MaskInput,{value,input:setValue,submit:()=>go(value)}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync10,statSync as statSync5}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(text3){return text3.split(`
4108
- `).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(existsSync10(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync10(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=statSync5(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key3=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key3);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(key3,rows2),{rows:rows2}}var basename8=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react39.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react39.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react39.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row3,i)=>$jsx("text",{children:row3.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:basename8(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react40=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react40.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react40.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react40.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function mix(a,b2,n=0.5){return RGBA.fromValues(a.r+(b2.r-a.r)*n,a.g+(b2.g-a.g)*n,a.b+(b2.b-a.b)*n,a.a+(b2.a-a.a)*n)}var TOP_RULE={topLeft:"\u2594",topRight:"\u2594",horizontal:"\u2594",bottomLeft:"",bottomRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},BOTTOM_RULE={bottomLeft:"\u2581",bottomRight:"\u2581",horizontal:"\u2581",topLeft:"",topRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""};function useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),rule=import_react41.useMemo(()=>mix(theme.background,theme.backgroundElement),[theme.background,theme.backgroundElement]),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,border:["bottom"],customBorderChars:BOTTOM_RULE,borderColor:rule}),$jsx("box",{backgroundColor:hover?rule:theme.backgroundElement,paddingLeft:1,paddingRight:1,paddingY:1,flexDirection:"column",minHeight:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,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}`)})})}),$jsx("box",{height:1,border:["top"],customBorderChars:TOP_RULE,borderColor:rule})]})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsxs("box",{flexDirection:"row",marginBottom:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:[$jsx("box",{width:3,flexShrink:0,backgroundColor:hover?theme.backgroundElement:void 0}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]})]})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant",firstUser=messages.findIndex((m2)=>m2.role==="user");return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsxs("box",{flexDirection:"column",children:[msg.role==="user"&&i>firstUser?$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"\u2500\u2500\u2500"})}):null,$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})]},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react62=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync11}from"fs";import{homedir as homedir4}from"os";import{join as join11}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join11(homedir4(),".hermes"),entry=()=>{let js=join11(import.meta.dirname,"db.worker.js");return new URL(existsSync11(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn2=()=>{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))),spawn2().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react45=__toESM(require_react_production(),1);var Ctx5=import_react45.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react45.useState([]),gate=import_react45.useRef(!1),gen=import_react45.useRef(0),prev=import_react45.useRef(null),refocus=import_react45.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react45.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react45.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react45.useCallback(()=>gate.current,[]),onError=import_react45.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key3)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key3))clear()});let value=import_react45.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react45.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react45.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,overflow:"hidden",flexDirection:"row",children:[$jsx("box",{flexShrink:0,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.titleRight?$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",justifyContent:"flex-end",children:props.titleRight}):null]}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react47=__toESM(require_react_production(),1);var HintBar=import_react47.memo((props)=>{let theme=useTheme().theme,text3=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:text3})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react48=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text3=p.children,box=import_react48.useRef(null),node=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react48.useState(!1);import_react48.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text3.length>w2),!animate){tn.scrollX=0;return}let id,period=text3.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text3.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,text3,p.speed,p.hold]);let body=wraps?text3+GAP+text3:text3;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,children:body})})})},GAP=" ";var import_react49=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react49.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var import_react50=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react50.memo((p)=>{let theme=useTheme().theme,color=p.color??theme.accent,text3=p.textColor??theme.text,bg2=p.state==="in"?color:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?color:theme.borderSubtle:p.selected?color:text3;return $jsx("box",{id:p.id,height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.onConfirm();if(keys.match("dialog.deny",key3))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="s")return props.onPick("save");if(key3.name==="d")return props.onPick("discard");if(key3.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react52=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react52.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost2=(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_react53=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync13,statSync as statSync6}from"fs";import{dirname as dirname9,basename as basename9}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync,readSync,closeSync,readdirSync as readdirSync6,readFileSync as readFileSync8,existsSync as existsSync12}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=(relative5)=>`${home.path}/${relative5}`,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=(relative5,label)=>({file:hermesPath(relative5),relative:relative5,label:label??relative5.split("/").pop()??relative5});function readSkillFrontmatter(source){try{let fd=openSync(source.file,"r"),buf=Buffer.alloc(2048),n=readSync(fd,buf,0,2048,0);closeSync(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
4107
+ `),add=lines3.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines3.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add,del}})}var DiffTabs=import_react37.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react37.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react37.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react38=__toESM(require_react_production(),1);var group="approval";function question(req){return(req.description||"Shell command").trim()}function subject(req){if(req.pattern_keys?.length)return req.pattern_keys.join("|");return req.command.trim()}function mkApproval(req){return{...req,group,question:question(req),subject:subject(req)}}function shouldRemember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);return cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject)}function remember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);if(cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject))return;set("neverPrompts",[...cur,{group:p.group,question:p.question,subject:p.subject}])}var MaskInput=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:props.value,onInput:props.input,onSubmit:props.submit,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(props.value.length)})})]})};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","never","deny"],LABELS={once:"Allow once",session:"Allow this session",never:"Never ask",deny:"Deny"},RESPOND={once:"once",session:"session",never:"always",deny:"deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),[steering,setSteering]=import_react38.useState(!1),[custom,setCustom]=import_react38.useState(""),[note,setNote]=import_react38.useState(""),done=import_react38.useRef(!1),prompt=mkApproval(p.req),send=(c)=>{if(done.current)return;if(done.current=!0,c==="never")remember(prompt);gw.request("approval.respond",{choice:RESPOND[c]}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text3)=>{let body=text3.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react38.useImperativeHandle(ref,()=>({masked:steering,feed:(key3)=>{if(steering){if(key3.name==="escape")return setSteering(!1),!0;return!1}if(key3.name==="s")return setSteering(!0),setNote(""),!0;if(key3.name==="left"||key3.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key3.name==="right"||key3.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key3.name==="return")return send(CHOICES[sel]),!0;if(key3.name==="escape")return send("deny"),!0;let n=digit(key3.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"}),$jsxs("text",{fg:theme.textMuted,children:["\xB7 ",prompt.question]})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["subject: ",prompt.subject]})}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react38.useState(0),[typing,setTyping]=import_react38.useState(choices.length===0),[custom,setCustom]=import_react38.useState(""),done=import_react38.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react38.useImperativeHandle(ref,()=>({masked:typing,feed:(key3)=>{if(typing){if(key3.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key3.name==="escape")return send(""),!0;if(key3.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key3.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key3.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key3.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react38.useState(""),done=import_react38.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react38.useImperativeHandle(ref,()=>({masked:!0,feed:(key3)=>{if(key3.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}),$jsx(MaskInput,{value,input:setValue,submit:()=>go(value)}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})});function same(a,b2){return Boolean(a&&b2&&b2.toLowerCase().includes(a.toLowerCase()))}function cap3(s,n=160){return s.length<=n?s:s.slice(0,n-1)+"\u2026"}function question2(part){let a=part.answered?.question;if(a)return a;if(part.req.variant==="clarify")return part.req.question;if(part.req.variant==="approval")return mkApproval(part.req).question;if(part.req.variant==="sudo")return"Sudo required";return part.req.env_var?`Secret: ${part.req.env_var}`:"Secret required"}function outcome(part){let a=part.answered;if(part.variant==="clarify"){let q2=cap3(question2(part)),body=cap3(a.label);return same(q2,a.label)?{head:body}:{head:q2,body}}if(part.variant==="approval"){let q2=cap3(question2(part),96);return{head:a.label,body:q2}}if(part.variant==="sudo")return{head:`sudo ${a.label}`};return{head:`${part.req.env_var??"secret"} ${a.label}`}}var Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,text3=outcome(part);return $jsxs("box",{flexDirection:"row",paddingLeft:3,marginBottom:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:fg2,children:glyph})}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:text3.head}),text3.body?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:text3.body}):null]})]})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync10,statSync as statSync5}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(text3){return text3.split(`
4108
+ `).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(existsSync10(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync10(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=statSync5(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key3=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key3);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(key3,rows2),{rows:rows2}}var basename8=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react39.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react39.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react39.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row3,i)=>$jsx("text",{children:row3.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:basename8(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react40=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react40.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react40.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react40.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function mix(a,b2,n=0.5){return RGBA.fromValues(a.r+(b2.r-a.r)*n,a.g+(b2.g-a.g)*n,a.b+(b2.b-a.b)*n,a.a+(b2.a-a.a)*n)}function darken(c,n=0.95){return RGBA.fromValues(c.r*n,c.g*n,c.b*n,c.a)}function lighten(c,n=0.05){return RGBA.fromValues(c.r+(1-c.r)*n,c.g+(1-c.g)*n,c.b+(1-c.b)*n,c.a)}var TOP_RULE={topLeft:"\u2594",topRight:"\u2594",horizontal:"\u2594",bottomLeft:"",bottomRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},BOTTOM_RULE={bottomLeft:"\u2581",bottomRight:"\u2581",horizontal:"\u2581",topLeft:"",topRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""};function useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let ctx=useTheme(),theme=ctx.theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),fill=import_react41.useMemo(()=>ctx.mode==="dark"?mix(theme.background,theme.backgroundElement):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),edge=import_react41.useMemo(()=>ctx.mode==="dark"?darken(theme.background):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,border:["bottom"],customBorderChars:BOTTOM_RULE,borderColor:edge}),$jsx("box",{backgroundColor:hover?fill:theme.backgroundElement,paddingLeft:1,paddingRight:1,paddingY:1,flexDirection:"column",minHeight:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,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}`)})})}),$jsx("box",{height:1,border:["top"],customBorderChars:TOP_RULE,borderColor:edge})]})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),rail2=import_react41.useMemo(()=>ctx.mode==="dark"?lighten(theme.background):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsxs("box",{flexDirection:"row",marginBottom:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:[$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]}),$jsxs("box",{width:3,flexShrink:0,flexDirection:"row",children:[$jsx("box",{width:2}),$jsx("box",{width:1,backgroundColor:hover?rail2:void 0})]})]})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant";return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsx("box",{flexDirection:"column",children:$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react62=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync11}from"fs";import{homedir as homedir4}from"os";import{join as join11}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join11(homedir4(),".hermes"),entry=()=>{let js=join11(import.meta.dirname,"db.worker.js");return new URL(existsSync11(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn2=()=>{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))),spawn2().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react45=__toESM(require_react_production(),1);var Ctx5=import_react45.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react45.useState([]),gate=import_react45.useRef(!1),gen=import_react45.useRef(0),prev=import_react45.useRef(null),refocus=import_react45.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react45.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react45.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react45.useCallback(()=>gate.current,[]),onError=import_react45.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key3)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key3))clear()});let value=import_react45.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react45.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react45.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,overflow:"hidden",flexDirection:"row",children:[$jsx("box",{flexShrink:0,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.titleRight?$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",justifyContent:"flex-end",children:props.titleRight}):null]}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react47=__toESM(require_react_production(),1);var HintBar=import_react47.memo((props)=>{let theme=useTheme().theme,text3=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:text3})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react48=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text3=p.children,box=import_react48.useRef(null),node=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react48.useState(!1);import_react48.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text3.length>w2),!animate){tn.scrollX=0;return}let id,period=text3.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text3.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,text3,p.speed,p.hold]);let body=wraps?text3+GAP+text3:text3;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,children:body})})})},GAP=" ";var import_react49=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react49.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var import_react50=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react50.memo((p)=>{let theme=useTheme().theme,color=p.color??theme.accent,text3=p.textColor??theme.text,bg2=p.state==="in"?color:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?color:theme.borderSubtle:p.selected?color:text3;return $jsx("box",{id:p.id,height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.onConfirm();if(keys.match("dialog.deny",key3))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="s")return props.onPick("save");if(key3.name==="d")return props.onPick("discard");if(key3.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react52=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react52.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost2=(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_react53=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync13,statSync as statSync6}from"fs";import{dirname as dirname9,basename as basename9}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync,readSync,closeSync,readdirSync as readdirSync6,readFileSync as readFileSync8,existsSync as existsSync12}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=(relative5)=>`${home.path}/${relative5}`,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=(relative5,label)=>({file:hermesPath(relative5),relative:relative5,label:label??relative5.split("/").pop()??relative5});function readSkillFrontmatter(source){try{let fd=openSync(source.file,"r"),buf=Buffer.alloc(2048),n=readSync(fd,buf,0,2048,0);closeSync(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
4109
4109
  ---`,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=readdirSync6(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 readdirSync6(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory()).sort((a,b2)=>b2.name.localeCompare(a.name)).flatMap((e)=>{try{let fd=openSync(`${base2}/${e.name}/run.json`,"r"),buf=Buffer.alloc(8192),n=readSync(fd,buf);closeSync(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 readdirSync6(base2,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let j2=JSON.parse(readFileSync8(`${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=openSync(source.file,"r"),buf=Buffer.alloc(4096),n=readSync(fd,buf);closeSync(fd);let body=buf.toString("utf8",0,n).trim(),line=body.split(`
4110
4110
  `).find((l)=>/^[-*\u00B7]/.test(l.trim()));return{source,headline:line?.replace(/^[-*\u00B7]\s*/,"").trim()??"",body}}catch{return null}}async function readConfig(){try{let text3=await Bun.file(hermesPath("config.yaml")).text(),raw=$parse(text3);return{source:makeSource("config.yaml","config.yaml"),model:{default:raw?.model?.default??"unknown",provider:raw?.model?.provider??"auto",base_url:raw?.model?.base_url??"",context_length:raw?.model?.context_length},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 relative5=`memories/${filename}`,content=await Bun.file(hermesPath(relative5)).text(),entryCount=content.split("\xA7").filter((s)=>s.trim()).length;return{source:makeSource(relative5,filename),content,charCount:content.length,charLimit,usagePercent:charLimit>0?Math.round(content.length/charLimit*100):0,entryCount}}catch{return null}}async function readLiveSessions(){try{let file=Bun.file(hermesPath("sessions/sessions.json"));if(!await file.exists())return{};let text3=await file.text();return JSON.parse(text3)}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 readdirSync6(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 text3=await Bun.file(hermesPath("SOUL.md")).text();return{source:makeSource("SOUL.md"),charCount:text3.length,tokenEstimate:count2(text3),content:text3}}catch{return null}}async function readToolsFromLatestSession(){try{let dir=hermesPath("sessions");if(!existsSync12(dir))return null;let glob=new Bun.Glob("session_*.json"),latestPath="",latestTime=0;for await(let path7 of glob.scan({cwd:dir})){let stat2=await Bun.file(hermesPath(`sessions/${path7}`)).stat();if(stat2&&stat2.mtimeMs>latestTime)latestTime=stat2.mtimeMs,latestPath=path7}if(!latestPath)return null;let relative5=`sessions/${latestPath}`,tools=((await Bun.file(hermesPath(relative5)).json()).tools||[]).map((t2)=>({name:t2?.function?.name??"unknown",descriptionLength:(t2?.function?.description??"").length,paramsLength:JSON.stringify(t2?.function?.parameters??{}).length}));return{source:makeSource(relative5,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(),lines3=full.trimEnd().split(`
4111
4111
  `),text3=lines3.length>tailLines?`\u2026(${lines3.length-tailLines} earlier lines)
@@ -4140,7 +4140,7 @@ The child returns whatever partial result it has so far.`,yes:"interrupt",danger
4140
4140
  WHERE task_id = ? AND summary IS NOT NULL AND summary != ''
4141
4141
  ORDER BY id DESC LIMIT 1`).get(id)?.summary??null}catch{return null}};function tailLogOf(s,id,bytes=16384){let path7=`${logsDir(s)}/${id}.log`;if(!existsSync15(path7))return null;try{let size=statSync7(path7).size,want=Math.min(size,bytes),fd=openSync2(path7,"r"),buf=Buffer.alloc(want);readSync2(fd,buf,0,want,size-want),closeSync2(fd);let out=buf.toString("utf-8");if(size>bytes){let nl=out.indexOf(`
4142
4142
  `);if(nl>=0&&nl<out.length-1)out=out.slice(nl+1)}return out}catch{return null}}function assignees(s=slug){let seen=new Set,dir=kp("profiles");if(existsSync15(dir)){for(let e of readdirSync7(dir,{withFileTypes:!0}))if(e.isDirectory())seen.add(e.name)}let conn2=dbOf(s);if(conn2)try{for(let r of conn2.query("SELECT DISTINCT assignee FROM tasks WHERE assignee IS NOT NULL AND status != 'archived'").all())seen.add(r.assignee)}catch{}return[...seen].sort()}function checkFileLength(conn2){try{let row3=conn2.query("PRAGMA database_list").get(),path7=String(row3?.file??row3?.[2]??"");if(!path7)return;let pageRow=conn2.query("PRAGMA page_size").get(),pageSize=Number(Object.values(pageRow??{})[0]);if(!pageSize)return;let fd=openSync2(path7,"r");try{let buf=Buffer.alloc(4);if(readSync2(fd,buf,0,4,28)<4)return;let headerPages=buf.readUInt32BE(0);if(!headerPages)return;let actualPages=Math.floor(fstatSync(fd).size/pageSize);if(actualPages<headerPages)throw Error(`torn-extend detected: page count mismatch on ${path7}: header claims ${headerPages} pages, file has ${actualPages} pages`)}finally{closeSync2(fd)}}catch(err){if(err instanceof Error&&err.message.startsWith("torn-extend detected"))throw err}}function writeTxn(conn2,fn){conn2.exec("BEGIN IMMEDIATE");try{let out=fn();return conn2.exec("COMMIT"),checkFileLength(conn2),out}catch(err){try{conn2.exec("ROLLBACK")}catch{}throw err}}var now=()=>Math.floor(Date.now()/1000);function patchTask(s,id,patch){let conn2=rwOf(s);if(!conn2)return!1;if(!conn2.query("SELECT 1 FROM tasks WHERE id = ?").get(id))return!1;if(patch.priority!==void 0){let p=Math.max(0,Math.min(9,Math.floor(patch.priority)));writeTxn(conn2,()=>{conn2.query("UPDATE tasks SET priority = ? WHERE id = ?").run(p,id),conn2.query("INSERT INTO task_events (task_id, run_id, kind, payload, created_at) VALUES (?, NULL, 'reprioritized', ?, ?)").run(id,JSON.stringify({priority:p}),now())})}if(patch.title!==void 0||patch.body!==void 0){let sets=[],vals=[];if(patch.title!==void 0){let t2=patch.title.trim();if(!t2)throw Error("title cannot be empty");sets.push("title = ?"),vals.push(t2)}if(patch.body!==void 0)sets.push("body = ?"),vals.push(patch.body);vals.push(id),writeTxn(conn2,()=>{conn2.query(`UPDATE tasks SET ${sets.join(", ")} WHERE id = ?`).run(...vals),conn2.query("INSERT INTO task_events (task_id, run_id, kind, payload, created_at) VALUES (?, NULL, 'edited', NULL, ?)").run(id,now())})}return!0}var q3=(s)=>/^[A-Za-z0-9._\/:+=-]+$/.test(s)?s:`'${s.replace(/'/g,"'\\''")}'`;var import_react78=__toESM(require_react_production(),1);function openCreateTask(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form2,{pool:opts.assignees,parent:opts.parent,done}),void 0,{ownCancel:!0})})}var CORE=["title","body","assignee","priority","triage","more"],MORE=["tenant","workspace","maxRuntime","skills"],SELECTY=new Set(["assignee","priority","workspace"]),MAX_RUNTIME_RE=/^\d+[smhd]?$/,SKILL_MATCHES_MAX=6,wsLabel=(w2)=>w2.kind==="scratch"?"scratch":w2.kind==="worktree"?"worktree":`dir @ ${w2.path}`,Form2=(p)=>{let theme=useTheme().theme,gw=useGateway(),body=import_react78.useRef(null),[bodyText,setBodyText]=import_react78.useState(""),[field,setField]=import_react78.useState("title"),[more,setMore]=import_react78.useState(!1),[picker,setPicker]=import_react78.useState(null),[title,setTitle]=import_react78.useState(""),[assignee,setAssignee]=import_react78.useState(null),[priority,setPriority]=import_react78.useState(0),[triage,setTriage]=import_react78.useState(!1),[tenant,setTenant]=import_react78.useState(""),[workspace,setWorkspace]=import_react78.useState({kind:"scratch"}),[maxRuntime,setMaxRuntime]=import_react78.useState(""),[catalog3,setCatalog]=import_react78.useState([]),[skills,setSkills]=import_react78.useState([]),[filter,setFilter]=import_react78.useState(""),[matchIdx,setMatchIdx]=import_react78.useState(0);import_react78.useEffect(()=>{let live=!0;return gw.request("skills.manage",{action:"list"}).then((r)=>{if(!live)return;let raw=r.skills??{},out=[];for(let cat of Object.keys(raw))for(let name of raw[cat]??[])out.push({cat,name});out.sort((a,b2)=>a.name.localeCompare(b2.name)),setCatalog(out)}).catch(()=>{}),()=>{live=!1}},[gw]);let matches=import_react78.useMemo(()=>{if(!filter.trim())return[];let q4=filter.trim().toLowerCase(),picked=new Set(skills),hits=[];for(let s of catalog3){if(picked.has(s.name))continue;if(s.name.toLowerCase().includes(q4)||s.cat.toLowerCase().includes(q4))hits.push(s);if(hits.length>=SKILL_MATCHES_MAX)break}return hits},[catalog3,filter,skills]);import_react78.useEffect(()=>{if(matchIdx>0&&matchIdx>=matches.length)setMatchIdx(Math.max(0,matches.length-1))},[matches.length,matchIdx]);let order=()=>more?[...CORE,...MORE]:CORE,titleOk=title.trim().length>0,runtimeOk=maxRuntime.trim()===""||MAX_RUNTIME_RE.test(maxRuntime.trim()),valid=titleOk&&runtimeOk,submit2=()=>{if(!valid)return;p.done({title:title.trim(),body:(body.current?.plainText??bodyText).trim(),assignee,priority,parent:p.parent?.id??null,triage,tenant:tenant.trim()||null,workspace,maxRuntime:maxRuntime.trim()||null,skills})},moveField=(dir)=>{let o=order(),i=o.indexOf(field),next2=o[(i+dir+o.length)%o.length];setField(next2)},openPicker=()=>{if(field==="assignee")return setPicker({kind:"assignee"});if(field==="priority")return setPicker({kind:"priority"});if(field==="workspace")return setPicker({kind:"workspace"})},commitMatch=()=>{let hit=matches[matchIdx];if(!hit)return!1;return setSkills((s)=>s.includes(hit.name)?s:[...s,hit.name]),setFilter(""),setMatchIdx(0),!0},popSkill=()=>setSkills((s)=>s.slice(0,-1));if(useKeyboard((key3)=>{if(picker){if(key3.name==="escape")setPicker(picker.kind==="dirPath"?{kind:"workspace"}:null);return}if(key3.name==="escape")return p.done(null);if(key3.name==="return"){if(key3.ctrl)return submit2();if(field!=="body")return submit2();return}if(field==="skills"){if(key3.name==="tab"){if(!key3.shift&&commitMatch())return;return moveField(key3.shift?-1:1)}if(key3.name==="backspace"){if(filter.length>0)return setFilter((f)=>f.slice(0,-1));return popSkill()}if(key3.name==="up"){if(matches.length>0)return setMatchIdx((i)=>Math.max(0,i-1));return moveField(-1)}if(key3.name==="down"){if(matches.length>0)return setMatchIdx((i)=>Math.min(matches.length-1,i+1));return moveField(1)}if(key3.raw&&key3.raw.length===1&&/[A-Za-z0-9_\-/ ]/.test(key3.raw))setFilter((f)=>f+key3.raw),setMatchIdx(0);return}if(key3.name==="tab")return moveField(key3.shift?-1:1);if(key3.name==="up"){if(field==="body"){if((body.current?.logicalCursor.row??0)>0)return}return moveField(-1)}if(key3.name==="down"){if(field==="body"){let row3=body.current?.logicalCursor.row??0,last3=(body.current?.lineCount??1)-1;if(row3<last3)return}return moveField(1)}if(field==="more"){if(key3.name==="return"||key3.name==="space")return setMore((m2)=>!m2);return}if(field==="triage"&&key3.name==="space")return setTriage((t2)=>!t2);if(SELECTY.has(field)&&key3.name==="space")return openPicker()}),picker?.kind==="assignee"){let opts=[{title:"(unassigned)",value:""},...p.pool.map((n)=>({title:n,value:n}))];return $jsx(DialogSelect,{title:"Assignee",options:opts,placeholder:"Search profiles\u2026",current:assignee??"",onSelect:(o)=>{setAssignee(o.value||null),setPicker(null)}})}if(picker?.kind==="priority"){let opts=Array.from({length:10},(_2,n)=>({title:n===0?"P0 (none)":`P${n}`,value:String(n),description:n===0?"default":n<=2?"normal":n<=5?"elevated":"high"}));return $jsx(DialogSelect,{title:"Priority",options:opts,filterable:!1,current:String(priority),onSelect:(o)=>{setPriority(Number(o.value)),setPicker(null)}})}if(picker?.kind==="workspace")return $jsx(DialogSelect,{title:"Workspace",options:[{title:"scratch",value:"scratch",description:"isolated temp dir under the board root (default)"},{title:"worktree",value:"worktree",description:"git worktree at .worktrees/<task-id> \u2014 worker runs `git worktree add`"},{title:"dir:\u2026",value:"dir",description:"an exact absolute path (prompts next)"}],filterable:!1,current:workspace.kind,onSelect:(o)=>{if(o.value==="scratch")return setWorkspace({kind:"scratch"}),setPicker(null);if(o.value==="worktree")return setWorkspace({kind:"worktree"}),setPicker(null);return setPicker({kind:"dirPath",value:workspace.kind==="dir"?workspace.path:""})}});if(picker?.kind==="dirPath"){let val=picker.value,ok=val.trim().length>0&&val.trim().startsWith("/");return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Directory path"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"absolute path (required)"})}),$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:val,onInput:(v2)=>setPicker({kind:"dirPath",value:v2}),onSubmit:()=>{if(!ok)return;setWorkspace({kind:"dir",path:val.trim()}),setPicker(null)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement},"dirpath")})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:ok?"Enter confirm \xB7 Esc back":"absolute path required \xB7 Esc back"})})]})}let lbl=(f,text3)=>$jsx("box",{width:13,flexShrink:0,children:$jsxs("text",{fg:field===f?theme.accent:theme.textMuted,children:[field===f?"\u25B8 ":" ",text3]})}),textRow=(f,label2,value,set2,placeholder)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label2),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:set2,onSubmit:submit2,focused:field===f,placeholder,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field===f?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement},`field-${f}`)})]}),valRow=(f,label2,value,hint)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label2),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.text,children:value})}),field===f?$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]}),skillsRows=()=>{let focused=field==="skills",empty=skills.length===0&&!focused;return $jsxs($Fragment,{children:[$jsxs("box",{height:1,flexDirection:"row",children:[lbl("skills","Skills"),$jsxs("box",{flexGrow:1,minWidth:0,height:1,flexDirection:"row",overflow:"hidden",children:[skills.map((n)=>$jsx(FilterChip,{label:n,state:"in",gap:0},n)),empty?$jsx("text",{fg:theme.textMuted,children:"(none \u2014 focus field to pick)"}):$jsxs("box",{flexDirection:"row",marginLeft:skills.length>0?1:0,children:[$jsx("text",{fg:theme.text,children:filter}),focused?$jsx("text",{fg:theme.accent,children:"\u2588"}):null]})]})]}),focused&&matches.length>0?$jsx("box",{flexDirection:"column",children:matches.map((s,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:i===matchIdx?theme.accent:theme.textMuted,children:i===matchIdx?" \u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:i===matchIdx?theme.accent:theme.text,children:s.name}),$jsx("span",{fg:theme.textMuted,children:` ${s.cat}`})]})})]},`${s.cat}/${s.name}`))}):null]})},footer=!valid?!titleOk?"type a title":"fix runtime (e.g. 30m, 2h, 1800)":field==="body"?"Ctrl+Enter create \xB7 Tab leave \xB7 \u2191\u2193 cursor \xB7 Esc cancel":field==="more"?`Space ${more?"collapse":"expand"} \xB7 Ctrl+Enter create \xB7 \u2191\u2193/Tab \xB7 Esc`:field==="skills"?(()=>{if(matches.length>0)return"Tab add \xB7 \u2191\u2193 pick \xB7 Bksp remove \xB7 Enter create \xB7 Esc";if(skills.length>0)return"type to filter \xB7 Bksp remove last \xB7 Enter create \xB7 \u2191\u2193/Tab \xB7 Esc";return"type to filter \xB7 Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc cancel"})():SELECTY.has(field)?"Space pick \xB7 Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc cancel":field==="triage"?"Space toggle \xB7 Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc":"Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc cancel";return $jsxs("box",{flexDirection:"column",width:66,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:p.parent?`New Task \xB7 child of ${p.parent.id}`:"New Task"})})}),p.parent?$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[" ",p.parent.title]})}):null,$jsx("box",{height:1}),textRow("title","Title",title,setTitle,"one-line summary"),$jsxs("box",{flexDirection:"row",children:[lbl("body","Body"),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("textarea",{ref:body,initialValue:bodyText,onContentChange:()=>{if(body.current)setBodyText(body.current.plainText)},focused:field==="body",placeholder:"longer spec \u2014 markdown ok (Enter for newline)",textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field==="body"?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement,minHeight:5,maxHeight:5},"field-body")})]}),valRow("assignee","Assignee",assignee??"(unassigned)","Space pick \u25BE"),valRow("priority","Priority",priority?`P${priority}`:"P0 (none)","Space pick \u25BE"),valRow("triage","Triage",triage?"yes \u2014 park for a specifier":"no","Space toggle"),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsxs("text",{fg:field==="more"?theme.accent:theme.textMuted,children:[field==="more"?"\u25B8 ":" ",more?"More \u25BE":"More \u25B8"]})}),!more?$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:"tenant \xB7 workspace \xB7 runtime \xB7 skills"})}):null]}),more?textRow("tenant","Tenant",tenant,setTenant,"namespace (optional)"):null,more?valRow("workspace","Workspace",wsLabel(workspace),"Space pick \u25BE"):null,more?textRow("maxRuntime","Runtime",maxRuntime,setMaxRuntime,"e.g. 30m, 2h, 1800 (optional)"):null,more?skillsRows():null,$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:footer})})]})};var arr=(v2)=>Array.isArray(v2)?v2:[],str2=(v2)=>typeof v2==="string"?v2:"",num3=(v2)=>typeof v2==="number"&&Number.isFinite(v2)?v2:0,ids=(v2)=>arr(v2).map(str2).filter(Boolean),spawned=(v2)=>arr(v2).flatMap((x2)=>{if(!x2||typeof x2!=="object")return[];let r=x2,task_id=str2(r.task_id);if(!task_id)return[];return[{task_id,assignee:str2(r.assignee),workspace:str2(r.workspace)}]}),capped=(v2)=>arr(v2).flatMap((x2)=>{if(!x2||typeof x2!=="object")return[];let r=x2,task_id=str2(r.task_id);if(!task_id)return[];return[{task_id,assignee:str2(r.assignee),current:num3(r.current)}]}),guarded=(v2)=>arr(v2).flatMap((x2)=>{if(Array.isArray(x2)){let task_id2=str2(x2[0]);if(!task_id2)return[];return[{task_id:task_id2,reason:str2(x2[1])}]}if(!x2||typeof x2!=="object")return[];let r=x2,task_id=str2(r.task_id);if(!task_id)return[];return[{task_id,reason:str2(r.reason)}]}),parseDispatchResult=(out)=>{let raw=JSON.parse(out);return{reclaimed:num3(raw.reclaimed),promoted:num3(raw.promoted),spawned:spawned(raw.spawned),skipped_unassigned:ids(raw.skipped_unassigned),skipped_nonspawnable:ids(raw.skipped_nonspawnable),skipped_per_profile_capped:capped(raw.skipped_per_profile_capped),auto_assigned_default:ids(raw.auto_assigned_default),crashed:ids(raw.crashed),auto_blocked:ids(raw.auto_blocked),timed_out:ids(raw.timed_out),stale:ids(raw.stale),respawn_guarded:guarded(raw.respawn_guarded)}},dispatchFailures=(r)=>[...r.crashed,...r.auto_blocked,...r.timed_out,...r.stale],dispatchGuarded=(r)=>r.respawn_guarded.map((x2)=>x2.task_id),dispatchVariant=(r)=>{let failed=dispatchFailures(r).length,guarded2=dispatchGuarded(r).length,unassigned=r.skipped_unassigned.length,benign=r.skipped_per_profile_capped.length+r.skipped_nonspawnable.length;if(r.spawned.length===0&&(failed>0||unassigned>0))return"error";if(failed>0||guarded2>0||unassigned>0)return"warning";if(benign>0)return"info";return"success"},line2=(label2,xs)=>xs.length?[`${label2}: ${xs.join(", ")}`]:[],caps=(r)=>{let map=r.skipped_per_profile_capped.reduce((m2,x2)=>{let key3=x2.assignee||"unassigned";return m2.set(key3,[...m2.get(key3)??[],x2]),m2},new Map);if(map.size===0)return[];return["Deferred at per-profile cap:",...[...map.entries()].map(([k2,xs])=>` ${k2} (${Math.max(...xs.map((x2)=>x2.current))} running): ${xs.map((x2)=>x2.task_id).join(", ")}`)]},dispatchDetails=(r)=>[...line2("Defaulted to kanban.default_assignee",r.auto_assigned_default),...caps(r),...line2("Unassigned",r.skipped_unassigned),...line2("Non-spawnable lanes",r.skipped_nonspawnable),...line2("Failed/reclaimed \xB7 crashed",r.crashed),...line2("Failed/reclaimed \xB7 auto-blocked",r.auto_blocked),...line2("Failed/reclaimed \xB7 timed out",r.timed_out),...line2("Failed/reclaimed \xB7 stale",r.stale),...line2("Respawn guarded",r.respawn_guarded.map((x2)=>`${x2.task_id}${x2.reason?` (${x2.reason})`:""}`))].join(`
4143
- `);var NOBAR={visible:!1},RULE=["bottom"],HEAD={triage:"triage",todo:"todo",scheduled:"scheduled",ready:"ready",running:"running",blocked:"blocked",done:"done"},EMPTY2={who:new Map,pri:new Map,status:new Map},EMPTY_DIAG=new Map,EMPTY_DIAGS=[],chipId=(c)=>c.kind==="who"?`who:${c.v}`:c.kind==="pri"?`pri:${c.v}`:`st:${c.v}`,chipLabel=(c)=>c.kind==="who"?c.v:c.kind==="pri"?`P${c.v}`:HEAD[c.v],triOf=(c,m2)=>c.kind==="who"?m2.who.get(c.v)??"off":c.kind==="pri"?m2.pri.get(c.v)??"off":m2.status.get(c.v)??"off",recOf=(v2)=>v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:null,assignedByDefault=(d2)=>d2.events.some((e)=>e.kind==="assigned"&&recOf(e.payload)?.source==="kanban.default_assignee");function admits(g,v2){let t2=g.get(v2);if(t2==="ex")return!1;if(t2==="in")return!0;for(let s of g.values())if(s==="in")return!1;return!0}var pass=(t2,m2)=>admits(m2.who,t2.assignee??null)&&admits(m2.pri,t2.priority),indexDiags=(rows3)=>{let out=new Map;for(let r of rows3)if(r.diagnostics.length>0)out.set(r.task_id,sortDiags(r.diagnostics));return out},maskFromPrefs=(raw)=>{let out=new Map;if(!raw)return out;for(let slug2 of Object.keys(raw)){let g=raw[slug2];out.set(slug2,{who:new Map(g.who??[]),pri:new Map(g.pri??[]),status:new Map(g.status??[])})}return out},maskToPrefs=(masks)=>{let out={};for(let[slug2,m2]of masks){let filt=(xs)=>xs.filter(([,t2])=>t2==="in"||t2==="ex"),who=filt([...m2.who]),pri=filt([...m2.pri]),status=filt([...m2.status]);if(who.length||pri.length||status.length)out[slug2]={who,pri,status}}return out},persist=(masks,open2)=>{let cur=load2().kanban??{};set("kanban",{...cur,open:[...open2],masks:maskToPrefs(masks)})},SEV_GLYPH={warning:"\u26A0",error:"!!",critical:"\u203C"},sevColor=(sev,theme)=>sev==="warning"?theme.warning:theme.error,Card=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{id:p.id,height:2,flexDirection:"row",paddingLeft:1,border:RULE,borderStyle:"single",borderColor:theme.borderSubtle,backgroundColor:p.on?theme.backgroundElement:void 0,onMouseDown:p.onPick,onMouseMove:p.onHover,children:$jsxs(Ticker,{active:p.on||p.hov,fg:p.on?theme.accent:theme.text,children:[p.sev?$jsxs($Fragment,{children:[$jsx("span",{fg:sevColor(p.sev,theme),children:SEV_GLYPH[p.sev]})," "]}):null,p.t.title]})})}),Column=import_react80.memo((p)=>{let theme=useTheme().theme,box=import_react80.useRef(null),[hov,setHov]=import_react80.useState(-1),id=(i)=>`kb-${p.slug}-${p.status}-${i}`;import_react80.useEffect(()=>{if(p.on&&p.tasks.length>0)box.current?.scrollChildIntoView(id(p.sel))},[p.on,p.sel,p.tasks.length]);let tint=p.status==="blocked"?theme.warning:p.status==="running"?theme.success:p.status==="scheduled"?theme.textMuted:p.status==="done"?theme.textMuted:theme.primary;return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:18,border:!0,borderColor:p.on?theme.primary:theme.border,onMouseOut:()=>setHov(-1),children:[$jsx("box",{height:1,paddingLeft:1,children:$jsxs("text",{children:[$jsx("span",{fg:tint,children:$jsx("strong",{children:HEAD[p.status]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.tasks.length}`})]})}),$jsx("scrollbox",{id:`kb-col-${p.slug}-${p.status}`,ref:box,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,onMouseScroll:(e)=>e.stopPropagation(),children:$jsx("box",{flexDirection:"column",width:"100%",children:p.tasks.map((t2,i)=>$jsx(Card,{id:id(i),t:t2,on:p.on&&i===p.sel,hov:i===hov,sev:maxSeverity(p.diags.get(t2.id)??[]),onHover:()=>{if(hov!==i)setHov(i)},onPick:()=>p.onPick(i)},t2.id))})})]})}),ErrorBanner=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",marginLeft:2,marginBottom:1,paddingLeft:1,border:!0,borderColor:theme.error,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:$jsxs("strong",{children:["Kanban DB ",p.error.kind]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.error.path}`})]})}),$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.error.message}),p.backups.length>0?$jsx("text",{wrapMode:"word",fg:theme.warning,children:`quarantine backup${p.backups.length===1?"":"s"}: ${p.backups.join(", ")}`}):null]})}),FilterBar=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,flexDirection:"row",flexWrap:"no-wrap",overflow:"hidden",marginBottom:1,children:p.chips.flatMap((c,i)=>{let chip2=$jsx(FilterChip,{label:chipLabel(c),state:triOf(c,p.mask),selected:p.on&&i===p.sel,onMouseDown:()=>p.onPick(i)},chipId(c));if(i===0||p.chips[i-1].kind===c.kind)return[chip2];return[$jsx("box",{height:1,flexShrink:0,marginLeft:1,children:$jsx("text",{fg:theme.borderSubtle,children:"|"})},`sep:${chipId(c)}`),chip2]})})}),FIELDS=["title","body","assignee","priority","status","parents","result","comment"],fieldsFor=(t2)=>FIELDS.filter((f)=>{if(f==="result")return t2.status==="done";return!0}),SidePane=import_react80.memo((p)=>{let{theme,syntaxStyle}=useTheme();if(p.pane.kind==="log"||p.pane.kind==="dispatch")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:p.pane.kind==="log"?p.pane.id:"Dispatch"})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${p.pane.kind==="log"?"worker log (tail)":"details"}`})]})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.pane.text||"(empty)"})})]});let d2=p.pane.d,fields=fieldsFor(d2),cur=p.on?fields[Math.min(p.sel,fields.length-1)]:null,srow=(f,label2,value,hint)=>{let active=cur===f;return $jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:active?theme.text:theme.textMuted,children:value})}),hint?$jsx("box",{flexShrink:0,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]},f)},mrow=(f,label2,content,hint)=>{let active=cur===f;return $jsxs("box",{flexDirection:"column",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),hint?$jsx("box",{flexGrow:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]}),$jsx("box",{paddingLeft:10,flexShrink:0,children:content})]},f)},resultText=d2.result||d2.latest_summary||"",sizeText=(n)=>n===null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`;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:d2.id})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${d2.status} \xB7 ${ago(d2.updated_at)}`})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[srow("title","Title",d2.title,p.on&&cur==="title"?"Enter edit":void 0),mrow("body","Body",d2.body?cur==="body"?$jsx("text",{wrapMode:"word",fg:theme.text,children:d2.body}):$jsx("markdown",{content:d2.body,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="body"?"Enter edit (raw)":void 0),srow("assignee","Assignee",d2.assignee?assignedByDefault(d2)?`${d2.assignee} (default)`:d2.assignee:"\u2014",p.on&&cur==="assignee"?"Enter pick":void 0),srow("priority","Priority",d2.priority?`P${d2.priority}`:"\u2014",p.on&&cur==="priority"?"Enter select":void 0),srow("status","Status",d2.status,p.on&&cur==="status"?"Enter change":void 0),srow("parents","Parents",d2.parents.length?d2.parents.join(", "):"\u2014",p.on&&cur==="parents"?"Enter add/remove":void 0),d2.children.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Children"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.children.join(", ")})})]}):null,d2.workspace_kind?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Workspace"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,children:[d2.workspace_kind,d2.workspace_path?` @ ${d2.workspace_path}`:""]})})]}):null,d2.branch_name?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Branch"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.branch_name})})]}):null,d2.skills.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Skills"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.skills.join(", ")})})]}):null,d2.model_override?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Model"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.model_override})})]}):null,d2.max_retries!==null?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Retries"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.max_retries)})})]}):null,d2.pid?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"PID"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.pid)})})]}):null,d2.last_heartbeat_at&&d2.status==="running"?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Heartbeat"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:ago(d2.last_heartbeat_at)})})]}):null,d2.session_id?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Session"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.session_id})})]}):null,d2.attachments.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Attachments (${d2.attachments.length})`})}),d2.attachments.map((a)=>{let source=a.path?{file:a.path,relative:a.relative_path??a.path,label:a.name}:null;return $jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${a.id} `}),$jsx("span",{fg:theme.text,children:a.name}),$jsx("span",{fg:theme.textMuted,children:` ${sizeText(a.size)} ${ago(a.created_at)}`})]})}),source?$jsx("box",{height:1,overflow:"hidden",children:$jsx(FileLink,{source,children:source.relative})}):$jsx("text",{wrapMode:"word",fg:theme.error,children:`unsafe path omitted: ${a.stored_path}`})]},a.id)})]}):null,d2.error?$jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:"Error"})}),$jsx("box",{paddingLeft:2,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:d2.error})})]}):null,d2.status==="done"?mrow("result","Result",resultText?cur==="result"?$jsx("text",{wrapMode:"word",fg:theme.text,children:resultText}):$jsx("markdown",{content:resultText,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="result"?"Enter edit":void 0):null,p.diags.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"Diagnostics "}),$jsx("span",{fg:sevColor(p.diags[0].severity,theme),children:`(${p.diags.length})`})]})}),p.diags.map((dx,i)=>$jsxs("box",{flexDirection:"column",marginTop:i===0?0:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:sevColor(dx.severity,theme),children:SEV_GLYPH[dx.severity]}),$jsx("span",{fg:theme.text,children:` [${dx.severity}] ${dx.kind}`}),dx.count>1?$jsx("span",{fg:theme.textMuted,children:` \xD7${dx.count}`}):null]})}),$jsxs("box",{paddingLeft:2,flexDirection:"column",children:[$jsx("text",{wrapMode:"word",fg:theme.text,children:dx.title}),dx.detail?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:dx.detail}):null,dx.actions.map((a,j2)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:a.suggested?theme.accent:theme.textMuted,children:a.suggested?"\u2192 ":"\xB7 "}),$jsx("span",{fg:a.suggested?theme.text:theme.textMuted,children:a.label})]})},j2))]})]},`${dx.kind}-${i}`))]}):null,d2.runs.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Runs (${d2.runs.length})`})}),d2.runs.map((r)=>{let outcome=r.outcome||r.status||(r.ended_at?"ended":"active"),elapsed=r.ended_at?`${Math.max(0,r.ended_at-r.started_at)}s`:"active";return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${r.id} `}),$jsx("span",{fg:theme.text,children:outcome}),$jsx("span",{fg:theme.textMuted,children:` @${r.profile??"-"} ${elapsed} ${ago(r.started_at)}`})]})}),r.summary?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:` \u2192 ${r.summary.split(`
4143
+ `);var NOBAR={visible:!1},RULE=["bottom"],HEAD={triage:"triage",todo:"todo",scheduled:"scheduled",ready:"ready",running:"running",blocked:"blocked",done:"done"},EMPTY2={who:new Map,pri:new Map,status:new Map},EMPTY_DIAG=new Map,EMPTY_DIAGS=[],chipId=(c)=>c.kind==="who"?`who:${c.v}`:c.kind==="pri"?`pri:${c.v}`:`st:${c.v}`,chipLabel=(c)=>c.kind==="who"?c.v:c.kind==="pri"?`P${c.v}`:HEAD[c.v],triOf=(c,m2)=>c.kind==="who"?m2.who.get(c.v)??"off":c.kind==="pri"?m2.pri.get(c.v)??"off":m2.status.get(c.v)??"off",recOf=(v2)=>v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:null,assignedByDefault=(d2)=>d2.events.some((e)=>e.kind==="assigned"&&recOf(e.payload)?.source==="kanban.default_assignee");function admits(g,v2){let t2=g.get(v2);if(t2==="ex")return!1;if(t2==="in")return!0;for(let s of g.values())if(s==="in")return!1;return!0}var pass=(t2,m2)=>admits(m2.who,t2.assignee??null)&&admits(m2.pri,t2.priority),indexDiags=(rows3)=>{let out=new Map;for(let r of rows3)if(r.diagnostics.length>0)out.set(r.task_id,sortDiags(r.diagnostics));return out},maskFromPrefs=(raw)=>{let out=new Map;if(!raw)return out;for(let slug2 of Object.keys(raw)){let g=raw[slug2];out.set(slug2,{who:new Map(g.who??[]),pri:new Map(g.pri??[]),status:new Map(g.status??[])})}return out},maskToPrefs=(masks)=>{let out={};for(let[slug2,m2]of masks){let filt=(xs)=>xs.filter(([,t2])=>t2==="in"||t2==="ex"),who=filt([...m2.who]),pri=filt([...m2.pri]),status=filt([...m2.status]);if(who.length||pri.length||status.length)out[slug2]={who,pri,status}}return out},persist=(masks,open2)=>{let cur=load2().kanban??{};set("kanban",{...cur,open:[...open2],masks:maskToPrefs(masks)})},SEV_GLYPH={warning:"\u26A0",error:"!!",critical:"\u203C"},sevColor=(sev,theme)=>sev==="warning"?theme.warning:theme.error,Card=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{id:p.id,height:2,flexDirection:"row",paddingLeft:1,border:RULE,borderStyle:"single",borderColor:theme.borderSubtle,backgroundColor:p.on?theme.backgroundElement:void 0,onMouseDown:p.onPick,onMouseMove:p.onHover,children:$jsxs(Ticker,{active:p.on||p.hov,fg:p.on?theme.accent:theme.text,children:[p.sev?$jsxs($Fragment,{children:[$jsx("span",{fg:sevColor(p.sev,theme),children:SEV_GLYPH[p.sev]})," "]}):null,p.t.title]})})}),Column=import_react80.memo((p)=>{let theme=useTheme().theme,box=import_react80.useRef(null),[hov,setHov]=import_react80.useState(-1),id=(i)=>`kb-${p.slug}-${p.status}-${i}`;import_react80.useEffect(()=>{if(p.on&&p.tasks.length>0)box.current?.scrollChildIntoView(id(p.sel))},[p.on,p.sel,p.tasks.length]);let tint=p.status==="blocked"?theme.warning:p.status==="running"?theme.success:p.status==="scheduled"?theme.textMuted:p.status==="done"?theme.textMuted:theme.primary;return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:18,border:!0,borderColor:p.on?theme.primary:theme.border,onMouseOut:()=>setHov(-1),children:[$jsx("box",{height:1,paddingLeft:1,children:$jsxs("text",{children:[$jsx("span",{fg:tint,children:$jsx("strong",{children:HEAD[p.status]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.tasks.length}`})]})}),$jsx("scrollbox",{id:`kb-col-${p.slug}-${p.status}`,ref:box,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,onMouseScroll:(e)=>e.stopPropagation(),children:$jsx("box",{flexDirection:"column",width:"100%",children:p.tasks.map((t2,i)=>$jsx(Card,{id:id(i),t:t2,on:p.on&&i===p.sel,hov:i===hov,sev:maxSeverity(p.diags.get(t2.id)??[]),onHover:()=>{if(hov!==i)setHov(i)},onPick:()=>p.onPick(i)},t2.id))})})]})}),ErrorBanner=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",marginLeft:2,marginBottom:1,paddingLeft:1,border:!0,borderColor:theme.error,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:$jsxs("strong",{children:["Kanban DB ",p.error.kind]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.error.path}`})]})}),$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.error.message}),p.backups.length>0?$jsx("text",{wrapMode:"word",fg:theme.warning,children:`quarantine backup${p.backups.length===1?"":"s"}: ${p.backups.join(", ")}`}):null]})}),FilterBar=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,flexDirection:"row",flexWrap:"no-wrap",overflow:"hidden",marginBottom:1,children:p.chips.flatMap((c,i)=>{let chip2=$jsx(FilterChip,{label:chipLabel(c),state:triOf(c,p.mask),selected:p.on&&i===p.sel,onMouseDown:()=>p.onPick(i)},chipId(c));if(i===0||p.chips[i-1].kind===c.kind)return[chip2];return[$jsx("box",{height:1,flexShrink:0,marginLeft:1,children:$jsx("text",{fg:theme.borderSubtle,children:"|"})},`sep:${chipId(c)}`),chip2]})})}),FIELDS=["title","body","assignee","priority","status","parents","result","comment"],fieldsFor=(t2)=>FIELDS.filter((f)=>{if(f==="result")return t2.status==="done";return!0}),SidePane=import_react80.memo((p)=>{let{theme,syntaxStyle}=useTheme();if(p.pane.kind==="log"||p.pane.kind==="dispatch")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:p.pane.kind==="log"?p.pane.id:"Dispatch"})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${p.pane.kind==="log"?"worker log (tail)":"details"}`})]})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.pane.text||"(empty)"})})]});let d2=p.pane.d,fields=fieldsFor(d2),cur=p.on?fields[Math.min(p.sel,fields.length-1)]:null,srow=(f,label2,value,hint)=>{let active=cur===f;return $jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:active?theme.text:theme.textMuted,children:value})}),hint?$jsx("box",{flexShrink:0,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]},f)},mrow=(f,label2,content,hint)=>{let active=cur===f;return $jsxs("box",{flexDirection:"column",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),hint?$jsx("box",{flexGrow:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]}),$jsx("box",{paddingLeft:10,flexShrink:0,children:content})]},f)},resultText=d2.result||d2.latest_summary||"",sizeText=(n)=>n===null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`;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:d2.id})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${d2.status} \xB7 ${ago(d2.updated_at)}`})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[srow("title","Title",d2.title,p.on&&cur==="title"?"Enter edit":void 0),mrow("body","Body",d2.body?cur==="body"?$jsx("text",{wrapMode:"word",fg:theme.text,children:d2.body}):$jsx("markdown",{content:d2.body,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="body"?"Enter edit (raw)":void 0),srow("assignee","Assignee",d2.assignee?assignedByDefault(d2)?`${d2.assignee} (default)`:d2.assignee:"\u2014",p.on&&cur==="assignee"?"Enter pick":void 0),srow("priority","Priority",d2.priority?`P${d2.priority}`:"\u2014",p.on&&cur==="priority"?"Enter select":void 0),srow("status","Status",d2.status,p.on&&cur==="status"?"Enter change":void 0),srow("parents","Parents",d2.parents.length?d2.parents.join(", "):"\u2014",p.on&&cur==="parents"?"Enter add/remove":void 0),d2.children.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Children"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.children.join(", ")})})]}):null,d2.workspace_kind?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Workspace"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,children:[d2.workspace_kind,d2.workspace_path?` @ ${d2.workspace_path}`:""]})})]}):null,d2.branch_name?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Branch"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.branch_name})})]}):null,d2.skills.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Skills"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.skills.join(", ")})})]}):null,d2.model_override?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Model"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.model_override})})]}):null,d2.max_retries!==null?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Retries"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.max_retries)})})]}):null,d2.pid?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"PID"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.pid)})})]}):null,d2.last_heartbeat_at&&d2.status==="running"?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Heartbeat"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:ago(d2.last_heartbeat_at)})})]}):null,d2.session_id?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Session"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.session_id})})]}):null,d2.attachments.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Attachments (${d2.attachments.length})`})}),d2.attachments.map((a)=>{let source=a.path?{file:a.path,relative:a.relative_path??a.path,label:a.name}:null;return $jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${a.id} `}),$jsx("span",{fg:theme.text,children:a.name}),$jsx("span",{fg:theme.textMuted,children:` ${sizeText(a.size)} ${ago(a.created_at)}`})]})}),source?$jsx("box",{height:1,overflow:"hidden",children:$jsx(FileLink,{source,children:source.relative})}):$jsx("text",{wrapMode:"word",fg:theme.error,children:`unsafe path omitted: ${a.stored_path}`})]},a.id)})]}):null,d2.error?$jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:"Error"})}),$jsx("box",{paddingLeft:2,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:d2.error})})]}):null,d2.status==="done"?mrow("result","Result",resultText?cur==="result"?$jsx("text",{wrapMode:"word",fg:theme.text,children:resultText}):$jsx("markdown",{content:resultText,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="result"?"Enter edit":void 0):null,p.diags.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"Diagnostics "}),$jsx("span",{fg:sevColor(p.diags[0].severity,theme),children:`(${p.diags.length})`})]})}),p.diags.map((dx,i)=>$jsxs("box",{flexDirection:"column",marginTop:i===0?0:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:sevColor(dx.severity,theme),children:SEV_GLYPH[dx.severity]}),$jsx("span",{fg:theme.text,children:` [${dx.severity}] ${dx.kind}`}),dx.count>1?$jsx("span",{fg:theme.textMuted,children:` \xD7${dx.count}`}):null]})}),$jsxs("box",{paddingLeft:2,flexDirection:"column",children:[$jsx("text",{wrapMode:"word",fg:theme.text,children:dx.title}),dx.detail?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:dx.detail}):null,dx.actions.map((a,j2)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:a.suggested?theme.accent:theme.textMuted,children:a.suggested?"\u2192 ":"\xB7 "}),$jsx("span",{fg:a.suggested?theme.text:theme.textMuted,children:a.label})]})},j2))]})]},`${dx.kind}-${i}`))]}):null,d2.runs.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Runs (${d2.runs.length})`})}),d2.runs.map((r)=>{let outcome2=r.outcome||r.status||(r.ended_at?"ended":"active"),elapsed=r.ended_at?`${Math.max(0,r.ended_at-r.started_at)}s`:"active";return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${r.id} `}),$jsx("span",{fg:theme.text,children:outcome2}),$jsx("span",{fg:theme.textMuted,children:` @${r.profile??"-"} ${elapsed} ${ago(r.started_at)}`})]})}),r.summary?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:` \u2192 ${r.summary.split(`
4144
4144
  `)[0].slice(0,200)}`}):null,r.error?$jsx("text",{wrapMode:"word",fg:theme.error,children:` \u2716 ${r.error.split(`
4145
4145
  `)[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_react80.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),keys=useKeys(),[boards,setBoards]=import_react80.useState(listBoards),[data2,setData]=import_react80.useState(()=>new Map(boards.map((b2)=>[b2.slug,boardStateOf(b2.slug)]))),[diags,setDiags]=import_react80.useState(()=>new Map),[masks,setMasks]=import_react80.useState(()=>maskFromPrefs(load2().kanban?.masks)),[open2,setOpen]=import_react80.useState(()=>{let saved=load2().kanban?.open;if(saved)return new Set(saved);let init=currentBoard();return new Set(listBoards().filter((b2)=>{let state2=boardStateOf(b2.slug);return b2.slug===init||[...state2.columns.values()].some((v2)=>v2.length>0)||!!state2.error}).map((b2)=>b2.slug))}),[at,setAt]=import_react80.useState(currentBoard),[tier,setTier]=import_react80.useState("grid"),[col,setCol]=import_react80.useState(0),[row3,setRow]=import_react80.useState(0),[chip2,setChip]=import_react80.useState(0),[paneSel,setPaneSel]=import_react80.useState(0),[pane,setPane]=import_react80.useState(null),outer=import_react80.useRef(null),load4=import_react80.useCallback(()=>{let bs=listBoards();setBoards(bs),setData(new Map(bs.map((b2)=>[b2.slug,boardStateOf(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_react80.useEffect(load4,[load4]),import_react80.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_react80.useMemo(()=>{let built=boards.map((b2)=>{let state2=data2.get(b2.slug)??boardStateOf(b2.slug),d2=state2.columns,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)),error:state2.error,corruptBackups:state2.corruptBackups}});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(row3,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_react80.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_react80.useEffect(()=>{if(!props.focused||running2===0)return;let t2=setInterval(load4,3000);return()=>clearInterval(t2)},[props.focused,running2,load4]),import_react80.useEffect(()=>{outer.current?.scrollChildIntoView(`kb-sec-${at}`)},[at,open2]);let sh=import_react80.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(),load4(),r.stdout}).catch((e)=>void toast.show({variant:"error",message:trunc5(e.message,120)})),[gw,toast,load4,at]),patchDirect=import_react80.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}),load4()}catch(e){toast.show({variant:"error",message:trunc5(e.message,120)})}},[at,toast,load4]),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_react80.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_react80.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_react80.useCallback((s)=>setOpen((o)=>{let n=new Set(o);return n.has(s)?n.delete(s):n.add(s),n}),[]),newBoard=import_react80.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(),load4(),setAt(v2),setTier("head")):Promise.reject(Error((r.stderr||r.stdout).trim()))).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)}))}),[dialog,gw,toast,load4]),live=import_react80.useRef({task,at,sec:sec3});live.current={task,at,sec:sec3};let create=import_react80.useCallback((parent2)=>openCreateTask(dialog,{assignees:assignees(live.current.at),parent:parent2?{id:parent2.id,title:parent2.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_react80.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_react80.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_react80.useCallback((t2)=>{if(t2.status!=="blocked"&&t2.status!=="scheduled")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not blocked/scheduled`});if(t2.status==="scheduled")return void sh(`unblock ${q3(t2.id)}`,`Released ${t2.id}`);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_react80.useCallback((t2)=>openConfirm(dialog,{title:"Archive task?",danger:!0,yes:"archive",body:`${t2.id} \xB7 ${trunc5(t2.title,60)}
4146
4146
 
@@ -4166,7 +4166,7 @@ high contrast, light subject on dark, black background`,BINDS=[{name:"return",ac
4166
4166
  `).slice(-3).join(" ")||`python exited ${exit}`};let last3=out.trim().split(`
4167
4167
  `).pop();if(!last3)return{err:"no output"};let j2;try{j2=JSON.parse(last3)}catch{return{err:`unparseable: ${last3.slice(0,200)}`}}if(j2.success===!1||j2.error)return{err:String(j2.error??"provider error")};let ref=j2.image??j2.video;if(!ref)return{err:"provider returned no asset"};if(ref.startsWith("/")||ref.startsWith("file://"))return{path:ref.replace(/^file:\/\//,"")};if(/^https?:\/\//.test(ref))return fetchTo(ref,kind2==="image"?".png":".mp4").then((p)=>({path:p})).catch((e)=>({err:`download: ${e instanceof Error?e.message:e}`}));return{err:`unrecognized asset ref: ${ref.slice(0,80)}`}},impl=generate,probeImpl=probe2,current=()=>impl,setImpl=(fn)=>{impl=fn??generate},setProbe=(fn)=>{probeImpl=fn??probe2},probeCached=()=>probeImpl();var import_react102=__toESM(require_react_production(),1);var ORDER4=["name","from"],FROMS=[{id:"blank",label:"blank",hint:"author in Studio"},{id:"file",label:"local file",hint:"png / jpg / webp / gif / mp4"},{id:"install",label:"inspect/install",hint:"catalog name \xB7 github.com/u/r/name \xB7 local dir"}],INSTALL_HINT="catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir";function openNewEikon(dialog,opts={}){return new Promise((resolve4)=>{let chained=!1;dialog.replace($jsx(Form4,{initial:opts.initial,dialog,onChain:()=>{chained=!0},done:(r)=>{chained=!0,dialog.clear(),resolve4(r)}}),()=>{if(!chained)resolve4(null)})})}var Form4=(props)=>{let theme=useTheme().theme,[name,setName]=import_react102.useState(props.initial??""),[from2,setFrom]=import_react102.useState("blank"),[field,setField]=import_react102.useState("name"),slug3=name?exports_eikon_knobs.slug(name):"",ok=slug3.length>0,submit3=async()=>{if(!ok)return;if(from2==="blank")return props.done({name:slug3,from:"blank"});if(props.onChain(),from2==="file"){let file2=await openTextPrompt(props.dialog,{title:"Source file",label:"absolute or ~ path (png / jpg / webp / gif / mp4)"});return props.done(file2?{name:slug3,from:"file",file:file2}:null)}let src3=await openTextPrompt(props.dialog,{title:"Inspect eikon source",label:INSTALL_HINT});if(!src3)return props.done(null);try{let info2=await exports_eikon.inspectSource(src3),ok2=await openConfirm(props.dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use the Library after install to select it."].join(`
4168
4168
  `),yes:"install",no:"cancel"});return props.done(ok2?{name:slug3,from:"install",src:src3}:null)}catch(e){return await openConfirm(props.dialog,{title:"Inspect failed",danger:!0,body:e instanceof Error?e.message:String(e),yes:"ok",no:"cancel"}),props.done(null)}};useKeyboard((key3)=>{if(key3.name==="escape")return props.done(null);if(key3.name==="tab"){let i=ORDER4.indexOf(field);return setField(ORDER4[(i+(key3.shift?-1:1)+ORDER4.length)%ORDER4.length])}if(key3.name==="return")return void submit3();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[A-Za-z0-9 _-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(key3.name==="up"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.max(0,i-1)].id)}if(key3.name==="down"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.min(FROMS.length-1,i+1)].id)}});let bg2=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New eikon"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("name"),children:[$jsx("box",{width:9,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:slug3?` \u2192 ${slug3}`:" type a name"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:bg2("from"),children:$jsx("text",{fg:theme.textMuted,children:"From (\u2191\u2193)"})}),FROMS.map((f)=>{let on=f.id===from2,fg2=on?theme.accent:theme.text;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("from"),children:[$jsx("box",{width:2,children:$jsx("text",{fg:fg2,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:fg2,children:f.label})}),$jsx("text",{fg:theme.textMuted,children:f.hint})]},f.id)}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:ok?"Enter create \xB7 Tab next field \xB7 Esc cancel":"type a name"})})]})};extend({slider:SliderRenderable});var PANES=["knobs","preview","strip"],HELP_H=4,COL={flexDirection:"column"},mb2=(n)=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,HEAD2=[{id:"open",kind:"select",label:"eikon"},{id:"rasterizer",kind:"select",label:"rasterizer"},{id:"source",kind:"prompt",label:"source"},{id:"-1",kind:"divider",label:""},{id:"fetch",kind:"action",label:"download source",show:(_s,status)=>status.downloadable},{id:"knobsfor",kind:"action",label:"tune",show:(_s,status)=>!!status.path},{id:"reset",kind:"action",label:"reset",show:(_s,status)=>!!status.path},{id:"revert",kind:"action",label:"revert",show:(s)=>s.dirty},{id:"-2",kind:"divider",label:"",show:(_s,status)=>!!status.path},{id:"h-input",kind:"header",label:"input",show:(_s,status)=>!!status.path},{id:"contrast",kind:"tone",label:"contrast",show:(_s,status)=>!!status.path,knob:{kind:"slider",min:0.25,max:4,step:0.05,default:1,hint:"Spread pixel values around their mean. \xD71 = source as-is; higher sharpens, lower flattens. Applied to the image before rasterizing."}},{id:"invert",kind:"tone",label:"invert",show:(_s,status)=>!!status.path,knob:{kind:"toggle",default:!0,hint:"Swap light\u2194dark in the source pixels. On for a light subject on a dark terminal background \u2014 turn off if the subject is darker than its surround."}},{id:"flip",kind:"tone",label:"flip",show:(_s,status)=>!!status.path,knob:{kind:"cycle",options:["none","h","v","hv"],default:"none",hint:"Mirror the source horizontally, vertically, or both before rasterizing."}},{id:"-3",kind:"divider",label:"",show:(_s,status)=>!!status.path}],HELP={open:"Which eikon you're editing. Enter to switch, create a new one, or install from elsewhere.",rasterizer:"The engine that turns your source image/video into text art. Each rasterizer exposes its own look-and-feel settings below the divider.",source:"Pick, generate, or clear source.",fetch:"Download published source for local editing.",knobsfor:"\u2190\u2192 toggles whether the settings below apply to every state or just the one selected in the strip.",reset:"Restore every setting below to this rasterizer's defaults and drop per-state overrides.",submit:"Submit this local eikon after backend preflight.",revert:"Throw away unsaved edits and reload this eikon from disk."},FLIPS=["none","h","v","hv"];function helpOf(row3){if(!row3)return"";if(row3.id==="source")return $jsx($Fragment,{children:$jsx("span",{children:HELP.source})});let head=HELP[row3.id];if(head)return head;if(!row3.knob)return"";if(row3.knob.hint)return row3.knob.hint;if(row3.knob.kind==="cycle")return`\u2190\u2192 or Enter cycles: ${row3.knob.options.join(" \xB7 ")}.`;if(row3.knob.kind==="toggle")return"Space or Enter toggles on/off.";return`\u2190\u2192 or drag adjusts (${row3.knob.min}\u2013${row3.knob.max}); scroll while selected also works.`}function buildRows(r,s,status){let dyn=status.path?Object.entries(r.knobs).map(([id,def2])=>({id,kind:"knob",label:def2.label??id,knob:def2})):[],head=HEAD2.filter((h2)=>h2.show?h2.show(s,status):!0);return dyn.length?[...head,{id:"h-r",kind:"header",label:r.name},...dyn]:head}var MINI_W=12;function Mini(props){let theme=useTheme().theme,d2=props.dims??{w:1,h:1},ar=d2.w/d2.h,bw=ar>=1?MINI_W:Math.max(4,Math.round(MINI_W*ar)),bh=ar>=1?Math.max(4,Math.round(MINI_W/ar)):MINI_W,short2=Math.min(bw,bh),cw=Math.max(1,short2*props.sp.zoom),cx=(bw-cw)*props.sp.ox,cy=(bh-cw)*props.sp.oy,on=(x2,y2)=>x2>=cx&&x2<cx+cw&&y2>=cy&&y2<cy+cw,cell=(x2,ty)=>{let up=on(x2,ty*2),dn=on(x2,ty*2+1);return up&&dn?"\u2588":up?"\u2580":dn?"\u2584":"\xB7"};return $jsx("box",{flexDirection:"column",flexShrink:0,backgroundColor:theme.backgroundElement,children:Array.from({length:Math.ceil(bh/2)},(_2,ty)=>$jsx("text",{fg:theme.textMuted,children:Array.from({length:bw},(_3,x2)=>cell(x2,ty)).join("")},ty))})}var SP_ROWS=["pan x","pan y","zoom","fps"];function PanBars(props){let theme=useTheme().theme,z2=props.sp.zoom,slack=1-z2,on=(i)=>props.focused&&props.sel===i,fg2=(i)=>on(i)?theme.accent:theme.textMuted,wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(k2,-1);if(d2==="down"||d2==="right")props.onWheel(k2,1)},drag=import_react104.useRef(null),grab=(k2,at)=>{drag.current={at,v:props.sp[k2],k:k2}},scrub=(at,L2)=>{let d2=drag.current;if(!d2||slack<=0)return;props.onSet(d2.k,Math.max(0,Math.min(1,+(d2.v+(at-d2.at)/(slack*L2)).toFixed(3))))},drop=()=>{drag.current=null},tw=Math.max(1,Math.round(z2*W2)),tl=Math.min(W2-tw,Math.round(props.sp.ox*slack*W2)),hbar=" ".repeat(tl)+"\u2588".repeat(tw)+" ".repeat(W2-tl-tw),vh=H*2,th=Math.max(1,z2*vh),ty=props.sp.oy*slack*vh,vbar=Array.from({length:H},(_2,y2)=>{let up=y2*2>=ty&&y2*2<ty+th,dn=y2*2+1>=ty&&y2*2+1<ty+th;return up&&dn?"\u2588\u2588":up?"\u2580\u2580":dn?"\u2584\u2584":" "});return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.children,$jsx("box",{width:W2,height:1,backgroundColor:theme.border,onMouseMove:()=>props.onHover(0),onMouseScroll:wheel("ox"),onMouseDown:(e)=>grab("ox",e.x),onMouseDrag:(e)=>scrub(e.x,W2),onMouseUp:drop,onMouseDragEnd:drop,children:$jsx("text",{fg:fg2(0),children:hbar})})]}),$jsx("box",{flexDirection:"column",width:2,height:H,backgroundColor:theme.border,onMouseMove:()=>props.onHover(1),onMouseScroll:wheel("oy"),onMouseDown:(e)=>grab("oy",e.y),onMouseDrag:(e)=>scrub(e.y,H),onMouseUp:drop,onMouseDragEnd:drop,children:vbar.map((g,y2)=>$jsx("text",{fg:fg2(1),children:g},y2))})]})}function SpatialBar(props){let theme=useTheme().theme,rows3=[{label:"zoom",k:"zoom",min:0.1,max:1,v:props.sp.zoom,i:2},{label:"fps",k:"fps",min:4,max:30,v:props.fps,i:3}],wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up")props.onWheel(k2,-1);if(d2==="down")props.onWheel(k2,1)};return $jsxs("box",{flexDirection:"row",marginTop:1,flexShrink:0,children:[$jsx("box",{flexDirection:"column",gap:1,flexShrink:0,children:rows3.map((d2)=>{let on=props.focused&&d2.i===props.sel;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onHover(d2.i),onMouseScroll:wheel(d2.k),children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:d2.label})}),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:d2.min,max:d2.max,value:d2.v,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>props.onSet(d2.k,d2.k==="fps"?Math.round(v2):+v2.toFixed(3))})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:` ${d2.k==="fps"?d2.v.toFixed(0):d2.v.toFixed(2)}`})})]},d2.label)})}),$jsx("box",{width:2}),$jsx(Mini,{sp:props.sp,dims:props.dims})]})}function valueOf(s,r,row3,theme,status,peek5,busy){if(row3.id==="open")return`${s.name} \u25B8`;if(row3.id==="rasterizer"){let a=r.available();if(a===!0)return`${r.name} \u25B8`;return $jsxs($Fragment,{children:[$jsx("span",{children:`${r.name} \u25B8`}),$jsx("span",{fg:theme.warning,children:` \u26A0 ${a}`})]})}if(row3.id==="source"){if(!status?.path){if(status?.kind==="downloadable")return"Download source";if(status?.kind==="baked")return"Baked only";return"Missing source"}let d2=s.dims,sz=status.size===void 0?"?":mb2(status.size);return d2?`${basename13(status.path)} \xB7 ${d2.w}\xD7${d2.h} \xB7 ${sz}`:`${basename13(status.path)} \xB7 ${sz}`}if(row3.id==="knobsfor")return`\u25C2 ${!!s.per[s.state]?`${s.state} only`:"all states"} \u25B8`;if(row3.id==="reset")return"\u25B8 defaults";if(row3.id==="revert")return"\u25B8 reload from disk";if(row3.kind==="tone"){if(row3.id==="contrast")return`\xD7${s.tone.contrast.toFixed(2)}`;if(row3.id==="invert")return s.tone.invert?"\u25CF on":"\u25CB off";if(row3.id==="flip")return`\u25C2 ${s.tone.flip} \u25B8`}if(row3.id==="fetch")return busy?"downloading\u2026":peek5?`\u25B8 ${peek5.n} files \xB7 ${mb2(peek5.bytes)}`:"\u25B8 local editable source";if(row3.kind==="knob"&&row3.knob){let k2=exports_eikon_knobs.eff(s,s.state)[row3.id]??row3.knob.default;if(row3.knob.kind==="cycle")return`\u25C2 ${String(k2)} \u25B8`;if(row3.knob.kind==="toggle")return k2?"\u25CF on":"\u25CB off";if(row3.knob.kind==="slider")return Number(k2).toFixed(2)}return""}function KnobRow(props){let theme=useTheme().theme,{row:row3,on,dim:dim2}=props,slider=row3.knob?.kind==="slider"?row3.knob:void 0,sval=!slider?0:row3.kind==="tone"?props.s.tone.contrast:Number(exports_eikon_knobs.eff(props.s,props.s.state)[row3.id]??slider.default),pushed=import_react104.useRef(sval);pushed.current=sval;let slide=(v2)=>{if(v2!==pushed.current)props.onSlide?.(v2)};if(row3.kind==="divider")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(24)})});if(row3.kind==="header")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.textMuted,children:$jsx("u",{children:row3.label})})});let scroll=(e)=>{if(!on||!slider||!props.onWheel)return;e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(-1);if(d2==="down"||d2==="right")props.onWheel(1)};return $jsxs("box",{id:props.id,height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onClick,onMouseScroll:scroll,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:dim2?theme.textMuted:on?theme.text:theme.textMuted,children:row3.label})}),slider?$jsxs($Fragment,{children:[$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:slider.min,max:slider.max,value:sval,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:slide})}),$jsx("box",{width:1})]}):null,$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:props.busy&&row3.id==="fetch"?$jsx(Spinner,{color:theme.accent,label:"downloading\u2026"}):$jsx("text",{fg:dim2?theme.textMuted:theme.text,children:valueOf(props.s,props.r,row3,theme,props.status,props.peek,props.busy)})})]})}function Strip(props){let theme=useTheme().theme,glyph=useSpinnerGlyph(props.pending.size>0);return $jsx("box",{flexDirection:"row",gap:1,children:STATES2.map((st)=>{let on=props.s.state===st,own=!!props.s.per[st],status=props.stats.get(st),mark2=status.kind==="missing"?"missing":status.kind==="downloadable"?"download":status.role===st?"own src":own?"forked":"",f=props.frames.get(st),gen=props.pending.has(st),empty=!f&&!gen;return $jsxs("box",{flexDirection:"column",alignItems:"center",onMouseDown:()=>{if(props.onPick(st),empty)props.onEmpty?.(st)},children:[$jsx("box",{border:!0,borderStyle:"rounded",borderColor:on&&props.focused?theme.primary:on?theme.accent:theme.border,width:18,height:10,overflow:"hidden",alignItems:"center",justifyContent:"center",children:gen?$jsx("text",{fg:theme.accent,children:`${glyph} gen`}):f?f.map((ln,i)=>$jsx("text",{fg:on?theme.text:theme.textMuted,children:ln},i)):$jsx("text",{fg:theme.textMuted,children:"+"})}),$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.accent:theme.textMuted,children:st})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:mark2})})]},st)})})}var BLANK3=Array.from({length:H},()=>" ".repeat(W2)),genCaps=null,probeGen=()=>{if(genCaps)return genCaps;let p=exports_eikon_gen.probeCached();return p.catch(()=>{genCaps=null}),genCaps=p};var EikonStudio=import_react104.memo((props)=>{let theme=useTheme().theme,keys=useKeys(),dialog=useDialog(),gw=useGateway(),toast=useToast(),wide=useTerminalDimensions().width>=120,ksb=import_react104.useRef(null),outer=import_react104.useRef(null);import_react104.useSyncExternalStore(exports_eikon.onRegistry,()=>exports_eikon.rasterizers().length);let[s,setS]=import_react104.useState(null),[pane,setPane]=import_react104.useState("knobs"),[sel,setSel]=import_react104.useState(0),[spSel,setSpSel]=import_react104.useState(0),selRef=import_react104.useRef(0);selRef.current=sel;let spRef=import_react104.useRef(0);spRef.current=spSel;let sRef=import_react104.useRef(null);sRef.current=s;let[frames,setFrames]=import_react104.useState([BLANK3]),[tick3,setTick]=import_react104.useState(0),[play,setPlay]=import_react104.useState(!0),[busy,setBusy]=import_react104.useState(!1),[fetching,setFetching]=import_react104.useState(!1),[peek5,setPeek]=import_react104.useState(void 0),[thumbs,setThumbs]=import_react104.useState(new Map),[err,setErr]=import_react104.useState(null),[saving,setSaving]=import_react104.useState(!1),[pending3,setPending]=import_react104.useState(new Set),[genOk,setGenOk]=import_react104.useState(null),frame=frames[tick3%frames.length]??BLANK3,stampRef=import_react104.useRef(""),rev2=import_react104.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),r=import_react104.useMemo(()=>exports_eikon.pick(s?.rasterizer??get2("eikonRasterizer")),[s?.rasterizer]),spatialOk=caps2.ffmpeg,open2=import_react104.useCallback((name)=>{resetCache(),stampRef.current=exports_eikon.sourceStamp(name);let seed=exports_eikon.readStudio(name),ra=exports_eikon.pick(seed?.rasterizer??get2("eikonRasterizer")),next2=exports_eikon_knobs.fresh(name,ra,seed),src4=exports_eikon.findSource(name,"idle");next2.dims=src4?exports_eikon.probe(src4)??null:null;for(let st of STATES2){let p=exports_eikon.findSource(name,st);if(p)prewarm(p,next2.fps)}setS(next2),selRow.current=void 0,setSel(0),setPane("knobs"),setErr(null),setTick(0),setFrames([BLANK3])},[]),tried=import_react104.useRef(!1);import_react104.useEffect(()=>{if(tried.current)return;if(tried.current=!0,props.name)return open2(props.name||exports_eikon_knobs.slug("new"));let n2=get2("eikon");if(n2)open2(n2)},[open2,props.name]);let dialogRef=import_react104.useRef(dialog);dialogRef.current=dialog,import_react104.useEffect(()=>{if(props.name===void 0)return;let next2=props.name||exports_eikon_knobs.slug("new"),cur=sRef.current;if(cur?.name===next2)return;if(!cur?.dirty)return open2(next2);let dead=!1;return openConfirm(dialogRef.current,{title:"Discard unsaved edits?",danger:!0,body:`Switch to '${next2}' and drop in-memory changes to '${cur.name}'.`}).then((ok)=>{if(!dead&&ok)open2(next2)}),()=>{dead=!0}},[props.name,open2]),import_react104.useEffect(()=>{let dead=!1;return probeGen().then((c)=>{if(!dead)setGenOk(c)}).catch(()=>{}),()=>{dead=!0}},[]);let stats=import_react104.useMemo(()=>{if(!s)return new Map;return new Map(STATES2.map((st)=>[st,exports_eikon.sourceStatus(s.name,st,{sources:s.sources})]))},[s?.name,s?.sources,rev2]),status=s?stats.get(s.state):void 0,src3=status?.path,live=!!src3,baked2=import_react104.useMemo(()=>{if(live||!s)return;let p=exports_eikon.baked(s.name);if(!p)return;try{return exports_eikon.parseEikonFile(p)}catch{return}},[live,s?.name]),url2=status?.sourceUrl;import_react104.useEffect(()=>{if(setPeek(void 0),!url2||!status?.downloadable)return;let dead=!1;return exports_eikon.peekSource(url2).then((x2)=>{if(!dead)setPeek(x2)}),()=>{dead=!0}},[url2,status?.downloadable]),import_react104.useEffect(()=>{if(!s)return;let stamp2=exports_eikon.sourceStamp(s.name);if(!stampRef.current){stampRef.current=stamp2;return}if(stamp2===stampRef.current)return;if(stampRef.current=stamp2,s.dirty){toast.show({variant:"info",message:"Source changed on disk",duration:3000});return}open2(s.name)},[rev2,s?.name,s?.dirty,open2,toast]);let rows3=import_react104.useMemo(()=>s&&status?buildRows(r,s,status):[],[r,s,status]),navRows=import_react104.useMemo(()=>rows3.map((x2,i)=>({...x2,i})).filter((x2)=>x2.kind!=="divider"&&x2.kind!=="header"),[rows3]),selRow=import_react104.useRef(void 0),rid=(x2)=>`${x2.kind}:${x2.id}`,setSelBy=import_react104.useCallback((arg)=>{setSel((prev)=>{let next2=typeof arg==="function"?arg(prev):arg,row3=navRows[next2];return selRow.current=row3?rid(row3):void 0,next2})},[navRows]),prevRows=import_react104.useRef(navRows);import_react104.useEffect(()=>{if(prevRows.current===navRows)return;prevRows.current=navRows;let id=selRow.current;if(!id)return;let ni=navRows.findIndex((x2)=>rid(x2)===id);if(ni>=0&&ni!==selRef.current)setSel(ni)},[navRows]);let kScroll=(ni)=>{let row3=navRows[ni];if(row3)ksb.current?.scrollChildIntoView(`knob-${row3.kind}-${row3.id}`)};import_react104.useEffect(()=>{if(!s)return;if(!src3){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,src3,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,s.state),ctrl.signal).then((out)=>{if(ctrl.signal.aborted)return;if(setBusy(!1),"err"in out){setErr(out.err);return}setErr(null),setFrames(out.frames),setTick((t2)=>t2%out.frames.length)}),()=>ctrl.abort()},[s?.spatial,s?.tone,s?.base,s?.per,s?.state,s?.fps,s?.rasterizer,src3,r,baked2]),import_react104.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_react104.useEffect(()=>{if(!s)return;let dead=!1,t2=setTimeout(()=>{if(dead)return;let jobs=STATES2.map((st)=>{let sp=stats.get(st)?.path;if(!sp){let f=baked2?.states.get(st)?.frames[0];return Promise.resolve([st,f?thumb(f):void 0])}return cached2(r,sp,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,st)).then((res)=>[st,"err"in res?void 0:thumb(res.frames[0])])});Promise.all(jobs).then((done)=>{if(dead)return;setThumbs(new Map(done))})},400);return()=>{dead=!0,clearTimeout(t2)}},[frames,s?.per,s?.sources,s?.name,s?.fps,r,baked2,stats]);let mutate=(fn)=>setS((p)=>p?fn(p):p),setSpatial=(sp)=>mutate((p)=>({...p,spatial:{...p.spatial,...sp},dirty:!0})),setBar=(k2,v2)=>k2==="fps"?mutate((p)=>({...p,fps:Math.round(v2),dirty:!0})):setSpatial({[k2]:v2}),stepBar=(k2,d2)=>{let cur=sRef.current;if(!cur)return;if(k2==="fps")return setBar("fps",Math.max(4,Math.min(30,cur.fps+d2*2)));if(k2==="zoom")return setSpatial({zoom:Math.max(0.1,Math.min(1,+(cur.spatial.zoom+d2*0.03).toFixed(3)))});return setSpatial({[k2]:Math.max(0,Math.min(1,+(cur.spatial[k2]+d2*0.03).toFixed(3)))})},doSave=import_react104.useCallback(async()=>{if(!s)return!1;if(!s.dirty)return toast.show({variant:"info",message:"Nothing to save"}),!0;if(!live)return toast.show({variant:"warning",message:"No source \u2014 download or attach before saving"}),!1;setSaving(!0);try{let f=await exports_eikon.save({...s,dirty:!1});return mutate((p)=>({...p,dirty:!1})),toast.show({variant:"success",message:`Saved \u2192 ${basename13(f)}`}),!0}catch(e){return toast.error(e instanceof Error?e:Error(String(e))),!1}finally{setSaving(!1)}},[s,live,toast]),doSaveUse=import_react104.useCallback(async()=>{if(!s)return;if(!await doSave())return;exports_eikon.useInstalled(s.name),toast.show({variant:"success",message:`Avatar \u2192 ${s.name}`})},[doSave,s,toast]),doSelectRasterizer=()=>{let opts=exports_eikon.rasterizers().map((x2)=>{let a=x2.available();return{title:x2.name,value:x2.name,description:Object.keys(x2.knobs).join(" \xB7 "),hint:a===!0?void 0:a}});dialog.replace($jsx(DialogSelect,{title:"Rasterizer",filterable:!1,current:r.name,options:opts,onSelect:(o)=>{dialog.clear();let next2=exports_eikon.rasterizer(o.value);if(!next2)return;let a=next2.available();if(a!==!0)return toast.show({variant:"warning",message:`${o.value}: ${a}`});set("eikonRasterizer",o.value),mutate((p)=>exports_eikon_knobs.swap(p,next2))}}),()=>{})},runGenerate=async(st,kind2)=>{if(!s)return;let seed=stats.get("idle")?.path;setPending((prev)=>{let n2=new Set(prev);return n2.add(st),n2});let out=await openGenerate(dialog,exports_eikon_gen.current(),{state:st,kind:kind2,seed,lastPrompt:s.prompts?.[st]});if(!out){setPending((prev)=>{let n2=new Set(prev);return n2.delete(st),n2});return}let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,out.path,role);mutate((p)=>({...p,sources:{...p.sources,[role]:f},prompts:{...p.prompts,[st]:out.prompt},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}finally{setPending((prev)=>{let n2=new Set(prev);return n2.delete(st),n2})}},download=async()=>{if(!s||fetching)return;setFetching(!0),await exports_eikon.downloadSource(s.name).then((out)=>{if(toast.show({variant:"success",message:`Downloaded ${out.n} file(s) \xB7 ${mb2(out.bytes)}`}),sRef.current?.dirty)mutate((prev)=>({...prev,sources:{...out.sources,...prev.sources}}));else open2(s.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e)))).finally(()=>setFetching(!1))},doSource=(forSt)=>{if(!s)return;let st=forSt??s.state,info2=stats.get(st)??exports_eikon.sourceStatus(s.name,st,{sources:s.sources}),own=info2.role===st||st==="idle"&&info2.role==="base"||s.sources[st]!==void 0,loc=exports_eikon.localSources(s.name),opts=[...info2.downloadable?[{title:"Download source",value:"download"}]:[],...loc.map((x2)=>({title:x2.file,value:`pick:${x2.file}`,hint:x2.role??"source"})),...genOk?.image?[{title:"Generate image\u2026",value:"gen-image"}]:[],...genOk?.video?[{title:"Generate video\u2026",value:"gen-video"}]:[],{title:"Local file\u2026",value:"local"},...st!=="idle"&&own?[{title:"Same as base",value:"same"}]:[],...own?[{title:"Remove",value:"remove"}]:[]];dialog.replace($jsx(DialogSelect,{title:`Source for '${st}'`,filterable:!1,options:opts,onSelect:async(o)=>{if(o.value==="download"){dialog.clear(),await download();return}if(o.value.startsWith("pick:")){dialog.clear();let file2=o.value.slice(5),role=st==="idle"&&loc.find((x2)=>x2.file===file2)?.role==="base"?"base":st;mutate((prev)=>({...prev,sources:{...prev.sources,[role]:file2},dirty:!0}));return}if(o.value==="local"){let p=await openPathPrompt(dialog,gw,{title:`Source for '${st}'`,label:"png/jpg/webp/gif/mp4/webm/mov \xB7 Tab completes",filter:/\.(png|jpe?g|webp|gif|mp4|webm|mov)$/i});if(!p)return;let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,p,role);mutate((prev)=>({...prev,sources:{...prev.sources,[role]:f},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}return}if(o.value==="gen-image")return void runGenerate(st,"image");if(o.value==="gen-video")return void runGenerate(st,"video");dialog.clear(),mutate((prev)=>({...prev,sources:{...prev.sources,[st==="idle"?"base":st]:null},dirty:!0}))}}),()=>{})},doPrompt=async(id)=>{if(!s)return;if(id==="source")return doSource()},switchTo=import_react104.useCallback(async(name)=>{let cur=sRef.current;if(cur?.name===name)return;if(cur?.dirty){if(!await openConfirm(dialog,{title:"Discard unsaved edits?",danger:!0,body:`Open '${name}' and drop in-memory changes to '${cur.name}'.`}))return}open2(name)},[dialog,open2]),apply=import_react104.useCallback(async(res)=>{if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),switchTo(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return switchTo(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[switchTo,toast]),doNew=import_react104.useCallback(async()=>{let res=await openNewEikon(dialog,{});await apply(res)},[dialog,apply]),eikonOptions=import_react104.useCallback(()=>{let installed=exports_eikon.list().map((e)=>({title:e.name,value:e.name,category:"installed",hint:e.hasSource?"\u25CF source":e.sourceUrl?"\u25CB source available":"\u2014"})),seen=new Set(installed.map((o)=>o.value)),bundled=listEikons([BUNDLED_EIKON_DIR,hermesPath("eikons")]).filter((e)=>e.path.startsWith(BUNDLED_EIKON_DIR)).map((e)=>{let slug3=e.meta.name.toLowerCase();return{title:e.meta.name,value:slug3,category:"bundled",hint:`${e.meta.width}\xD7${e.meta.height}`}}).filter((o)=>!seen.has(o.value)),raw2=exports_eikon.raw().filter((n2)=>!seen.has(n2)).map((n2)=>({title:n2,value:n2,category:"installed",hint:"(unsaved)"}));return[...installed,...raw2,...bundled]},[]),doInstall=import_react104.useCallback(async()=>{let src4=await openTextPrompt(dialog,{title:"Inspect eikon source",label:"catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir"});if(!src4)return;let info2;try{info2=await exports_eikon.inspectSource(src4)}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}if(!await openConfirm(dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use Ctrl+U or Library after install to select it."].join(`
4169
- `),yes:"install",no:"cancel"}))return;toast.show({variant:"info",message:`Installing from ${src4}\u2026`}),await exports_eikon.installPackage(src4).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,switchTo,toast]),doOpen=import_react104.useCallback(()=>{let cur=sRef.current,opts=[...eikonOptions(),{title:"+ New\u2026",value:"__new",category:""},{title:"+ Install\u2026",value:"__install",category:""}];dialog.replace($jsx(DialogSelect,{title:"Open eikon",current:cur?.name,options:opts,onSelect:(o)=>{if(dialog.clear(),o.value==="__new")return void doNew();if(o.value==="__install")return void doInstall();switchTo(o.value)}}),()=>{})},[dialog,eikonOptions,switchTo,doNew,doInstall]),doSubmit=import_react104.useCallback(async()=>{let cur=sRef.current;if(!cur)return;let path7=submitPath(cur.name);if(publishedInfo(path7)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}if(cur.dirty||!existsSync20(path7)){let pick2=await openSaveDiscard(dialog,{title:"Save before submit?",body:`'${cur.name}' has unsaved changes. Save to submit the current preview, discard to submit the last saved artifact, or keep editing.`});if(pick2==="save"){if(get2("eikon")===cur.name){if(!await openConfirm(dialog,{title:`Save active '${cur.name}' before submit?`,danger:!0,body:"Saving changes the active avatar's backing artifact. Submit itself will not change active selection.",yes:"save",no:"cancel"}))return}if(!await doSave())return}else if(pick2==="discard")open2(cur.name);else return}if(!existsSync20(path7)){toast.show({variant:"warning",message:"Save this eikon before submitting"});return}await openEikonSubmit(dialog,{name:cur.name,path:path7,submit:submit2})},[dialog,doSave,open2,toast]),doAction=async(id)=>{if(!s)return;if(id==="knobsfor")return mutate((p)=>p.per[p.state]?exports_eikon_knobs.unfork(p):exports_eikon_knobs.fork(p));if(id==="submit"){doSubmit();return}if(id==="revert"){discard();return}if(id==="reset"){if(await openConfirm(dialog,{title:"Reset settings?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!status?.downloadable||fetching)return;await download()}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Source\u2026",value:"source"},{title:s.per[s.state]?"Clear override (back to base)":"Tune this state only",value:"fork"}],onSelect:(o)=>{if(o.value==="source"){doSource();return}dialog.clear(),mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},setTone=(t2)=>mutate((p)=>({...p,tone:{...p.tone,...t2},dirty:!0})),stepRow=(row3,d2)=>{if(row3.kind==="tone"){if(row3.id==="contrast"){let def2=row3.knob,cur=sRef.current?.tone.contrast??1;return setTone({contrast:+Math.max(def2.min,Math.min(def2.max,cur+d2*def2.step)).toFixed(2)})}if(row3.id==="invert")return setTone({invert:!sRef.current?.tone.invert});if(row3.id==="flip"){let cur=sRef.current?.tone.flip??"none",i=FLIPS.indexOf(cur);return setTone({flip:FLIPS[(i+d2+FLIPS.length)%FLIPS.length]})}return}if(row3.kind!=="knob"||!row3.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row3.id,row3.knob,d2)))},act=(row3,via)=>{if(!row3||!sRef.current)return;if(row3.kind==="select"){if(row3.id==="open")return doOpen();return doSelectRasterizer()}if(row3.kind==="prompt")return void doPrompt(row3.id);if(row3.kind==="action"){if(via==="space"&&row3.id==="reset")return;return void doAction(row3.id)}if(row3.kind==="tone"||row3.kind==="knob"){if(row3.knob.kind==="slider")return;return stepRow(row3,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row3=navRows[selRef.current];if(!row3)return;if(row3.id==="knobsfor")return void doAction("knobsfor");stepRow(row3,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;let pick2=await openSaveDiscard(dialog,{title:"Unsaved edits",body:`'${cur.name}' has unsaved changes. Save them, discard them, or keep editing?`});if(pick2==="save"){if(await doSave())open2(cur.name);return!0}if(pick2==="discard")open2(cur.name);return!0},refresh=import_react104.useCallback(()=>{let cur=sRef.current;if(!cur)return;if(stampRef.current=exports_eikon.sourceStamp(cur.name),cur.dirty){toast.show({variant:"info",message:"Reload skipped: unsaved edits",duration:3000});return}open2(cur.name),toast.show({variant:"info",message:"Reloaded",duration:1000})},[open2,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(key3.eventType==="release")return;if(key3.name==="u"&&key3.ctrl&&sRef.current)return void doSaveUse();if(key3.name==="u"&&sRef.current)return void doSubmit();if(keys.match("eikon.save",key3)){if(!saving)doSave();return}if(key3.name==="escape")return void discard();if(key3.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key3.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key3.name==="return")return void doNew();return}if(pane==="knobs"){if(handleListKey(keys,key3,{count:navRows.length,setSel:setSelBy,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doNew(),onRefresh:refresh}))return;if(key3.name==="left")return adjust(-1);if(key3.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key3))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key3,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key3.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key3.name==="left"||key3.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key3.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key3.name))}return}if(key3.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key3.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key3.name==="return")return doStripMenu()});let onScroll=(e)=>{if(e.stopPropagation(),!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;let sign=d2==="up"?-1:1;if(e.modifiers.ctrl)return mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,sign),dirty:!0}));if(e.modifiers.shift)return mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,sign,0),dirty:!0}));mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,0,sign),dirty:!0}))},n=frames.length,title=s?`Preview \u2014 ${s.state}${s.per[s.state]?" (forked)":""}`+(n>1?` \xB7 ${play?"\u25B6":"\u23F8"} ${tick3%n+1}/${n}`:"")+(live?"":baked2?" \xB7 (baked)":""):"Preview",previewErr=err??(!s||src3||baked2?null:url2?"no source \u2014 Enter on 'download source'":"no source \u2014 Enter on 'source'"),hint=!s?[["Enter","new eikon"],["Shift+\u2192","library"]]:pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"edit"],[keys.print("list.refresh"),"reload"],[keys.print("list.new"),"new"],["u","submit"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","pan"],["Ctrl+wheel","zoom"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),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=$jsxs(TabShell,{title:spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:previewErr,focus:pane==="preview",children:[!live&&baked2?$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"Baked \u2014 download or attach source to edit."})}):null,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]}),help=helpOf(navRows[sel]),panel=$jsx(TabShell,{title:s?`Settings \u2014 ${s.name}`:"Settings",focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create or pick one."})}):$jsxs($Fragment,{children:[$jsx("scrollbox",{id:"studio-knob-scroll",ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,onMouseScroll:(e)=>e.stopPropagation(),children:rows3.map((row3,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row3.kind==="knob"&&!src3;return $jsx(KnobRow,{id:`knob-${row3.kind}-${row3.id}`,row:row3,s,r,status,on,dim:dim2,peek:peek5,busy:row3.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSelBy(ni)},onClick:()=>{if(ni>=0)setSelBy(ni),setPane("knobs"),act(row3,"click")},onWheel:(d2)=>stepRow(row3,d2),onSlide:row3.knob?.kind!=="slider"?void 0:row3.kind==="tone"?(v2)=>setTone({contrast:+v2.toFixed(2)}):(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row3.id,row3.knob,v2)))},`${row3.kind}:${r.name}:${row3.id}`)})}),$jsx("box",{flexShrink:0,height:HELP_H,marginTop:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:help})})]})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:18,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,stats,pending:pending3,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))},onEmpty:(st)=>doSource(st)})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+HELP_H+1+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:saving?"\u25CF saving\u2026":s?.dirty?"\u25CF unsaved":void 0})]})});var import_react106=__toESM(require_react_production(),1);import{existsSync as existsSync21,readFileSync as readFileSync15}from"fs";import{basename as basename14,dirname as dirname14,join as join18}from"path";var EIKON_CARD=50,titleWidth=(title,rows3)=>Math.max(title.length,...rows3.map((r)=>r.name.length+4))+7,cardWidth=(lines3)=>Math.max(EIKON_CARD,...lines3.map((line4)=>line4.length+2)),EikonTitleList=(props)=>{let theme=useTheme().theme;return $jsx("box",{width:props.width,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:props.title,focus:props.focus,grow:1,children:$jsx("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:$jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"row",height:1,paddingRight:3,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,children:[r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})})]},r.key)})})})})})},EikonCardGrid=(props)=>{let theme=useTheme().theme;if(props.rows.length===0)return $jsx("box",{padding:1,children:props.empty??$jsx("text",{fg:theme.textMuted,children:"No eikons found."})});return $jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"row",flexWrap:"wrap",width:"100%",flexShrink:0,children:props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"column",height:r.lines.length+2,width:cardWidth(r.lines),flexShrink:0,paddingX:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{height:r.lines.length,overflow:"hidden",flexDirection:"column",children:r.lines.map((line4,j2)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:line4||" "})},j2))}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:[on?"\u25B8 ":" ",r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.author??"unknown"," \xB7 ",r.status]})})]},r.key)})})})};var PREVIEW2=54,EikonGallery=import_react106.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),rev2=import_react106.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),dims=useTerminalDimensions(),rows3=import_react106.useMemo(()=>{let user=hermesPath("eikons"),own=exports_eikon.list(),map=new Map(own.map((x2)=>[x2.name.toLowerCase(),x2])),meta=own.map((x2)=>({inst:x2,ids:ids2(x2.manifest,x2.name,x2.sourceUrl)}));return[...listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():dirname14(e.path)===user?basename14(e.path,".eikon"):basename14(dirname14(e.path)),man=manifest4(dirname14(e.path)),keys2=ids2(man,slug3),mine=meta.find((x2)=>x2.ids.some((k2)=>keys2.includes(k2)))?.inst??map.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,url:mine?.sourceUrl,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3),lifecycle:mine?.lifecycle,...man?{manifest:man}:{}}}).filter((r)=>!(r.bundled&&r.lifecycle)).reduce((map2,row3)=>{let prev=map2.get(row3.slug);if(!prev||dirname14(prev.path)===user&&dirname14(row3.path)!==user)map2.set(row3.slug,row3);return map2},new Map).values()]},[rev2]),active=usePref("eikon"),path7=import_react106.useMemo(()=>active?exports_eikon.baked(active):void 0,[active,rev2]),current2=(row3)=>path7===row3.path,[sel,setSel]=import_react106.useState(0),[pane,setPane]=import_react106.useState("list"),[act,setAct]=import_react106.useState(0),galleryFollow=useFollow("gal",(i)=>rows3[i]?.slug??i),gridFollow=useFollow("lib-grid",(i)=>rows3[i]?.slug??i);import_react106.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],parsed=import_react106.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]),activate=(row3=cur)=>{if(!row3)return;if(row3.bundled)set("eikon",row3.slug);else exports_eikon.useInstalled(row3.slug);toast.show({variant:"success",message:`Avatar \u2192 ${row3.name}`})},doNew=import_react106.useCallback(async()=>{let res=await openNewEikon(dialog,{});if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),props.onEdit?.(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return props.onEdit?.(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,toast,props]),updateLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;try{let out=await exports_eikon.update(cur.slug);if("type"in out){if(!await openConfirm(dialog,{title:`Update active '${cur.name}'?`,danger:!0,body:`${out.message} The active avatar's backing package will change even though the selected name stays '${cur.slug}'.`,yes:"update active",no:"cancel"}))return;let done=await exports_eikon.update(cur.slug,{confirmActive:!0});if("type"in done)return toast.show({variant:"warning",message:done.message})}toast.show({variant:"success",message:`Updated ${cur.name}`})}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}},[cur,dialog,toast]),submitLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;let path8=submitPath(cur.slug);if(publishedInfo(path8)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path8,submit:props.submit??submit2})},[cur,dialog,props.submit,toast]),del=async()=>{if(!cur||cur.bundled)return;let here=current2(cur),base2=dirname14(cur.path)===hermesPath("eikons")?`Removes legacy flat file ${basename14(cur.path)}.`:`Removes ${dirname14(cur.path)} and all its sources.`,body=here?`${base2} This is the active avatar; deleting it will clear the active avatar selection.`:base2;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body}))return;let removed=exports_eikon.remove(cur.slug,{confirmActive:here});if(removed)return toast.show({variant:"warning",message:removed.message});toast.show({variant:"info",message:`Deleted ${cur.name}`})},actions=import_react106.useMemo(()=>{if(!cur)return[];return[{key:"Enter",label:current2(cur)?"Use as active avatar (active)":"Use as active avatar",run:()=>activate()},...props.onEdit?[{key:"e",label:"Edit in Studio",run:()=>props.onEdit?.(cur.slug)}]:[],...!cur.bundled?[{key:"u",label:"Update local package",run:()=>void updateLocal()},{key:"s",label:"Share to catalog",run:()=>void submitLocal()},{key:"d",label:"Delete local eikon",run:()=>void del(),danger:!0}]:[]]},[cur,path7,props.onEdit,updateLocal,submitLocal]);import_react106.useEffect(()=>{if(act>=actions.length)setAct(Math.max(0,actions.length-1))},[act,actions.length]);let cards=import_react106.useMemo(()=>rows3.map((r)=>{let p=(()=>{try{return parseEikonFile(r.path)}catch{return}})(),lines3=p?.resolve("state.idle")?.frames[0]??p?.states.get("idle")?.frames[0]??["(no preview)"];return{key:r.path,name:r.name,active:current2(r),author:r.author,status:current2(r)?"active":r.bundled?"bundled/system":"installed",lines:lines3}}),[rows3,path7]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;let plain=!key3.shift&&!key3.ctrl&&!key3.meta;if(key3.name==="tab")return setPane((p)=>p==="list"?"actions":"list");if(pane==="actions"){if(key3.name==="escape"||plain&&key3.name==="left"){setPane("list");return}if(plain&&key3.name==="up"){setAct((i)=>Math.max(0,i-1));return}if(plain&&key3.name==="down"){setAct((i)=>Math.min(actions.length-1,i+1));return}if(keys.match("list.activate",key3)||keys.match("list.toggle",key3)){actions[act]?.run();return}return}if(handleListKey(keys,key3,{count:rows3.length,setSel,page:galleryFollow.opts.page,scrollTo:(n)=>galleryFollow.ref.current?.scrollChildIntoView(galleryFollow.id(n)),onActivate:()=>activate(),onDelete:()=>void del(),onNew:doNew,onRefresh:()=>{exports_eikon.notifyRevision(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}))return;if(key3.name==="u"&&cur&&!cur.bundled)return void updateLocal();if(key3.name==="s"&&cur&&!cur.bundled)return void submitLocal();if(key3.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)});let listW=Math.max(13,...rows3.map((r)=>r.name.length+4))+7,showGrid=dims.width-listW-PREVIEW2>=EIKON_CARD;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minHeight:0,children:[$jsx(EikonTitleList,{title:`Library (${rows3.length})`,rows:rows3.map((r)=>({key:r.path,name:r.name,active:current2(r)})),sel,focus:props.focused&&pane==="list",follow:galleryFollow,width:listW,onSel:setSel,onUse:(i)=>activate(rows3[i])}),showGrid?$jsx(TabShell,{title:"Grid",grow:1,children:$jsx(EikonCardGrid,{rows:cards,sel,follow:gridFollow,onSel:setSel,onUse:(i)=>activate(rows3[i])})}):null,$jsx("box",{width:PREVIEW2,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:1,children:$jsxs("box",{flexDirection:"column",flexGrow:1,padding:1,alignItems:"center",children:[$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})}),cur?$jsxs("box",{flexDirection:"column",width:48,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:cur.name})}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",cur.author??"\u2014"]}),$jsxs("text",{fg:theme.textMuted,children:["Status: ",current2(cur)?"active":cur.bundled?"bundled/system":"installed"]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Source: ",gallerySource(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Trust: ",galleryTrust(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Package: ",packageId(cur)]}),$jsx("text",{fg:theme.textMuted,children:sourceBadge(cur)}),$jsx("box",{height:1}),$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Actions"})}),actions.map((a,i)=>$jsx("box",{height:1,overflow:"hidden",paddingRight:1,backgroundColor:pane==="actions"&&i===act?theme.backgroundElement:void 0,onMouseDown:()=>{setPane("actions"),setAct(i),a.run()},children:$jsxs("text",{fg:a.danger?theme.error:theme.text,wrapMode:"none",children:[pane==="actions"&&i===act?"\u25B8 ":" ",a.label," [",a.key,"]"]})},a.label))]}):null]})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="list"?"actions":"library"],[keys.print("list.activate"),pane==="actions"?"run action":"use"],["\u2191\u2193",pane==="actions"?"action":"select"],[keys.print("list.new"),"new / install"],[keys.print("list.refresh"),"reload"],...cur&&props.onEdit?[["e","edit in Studio"]]:[]]})]})}),galleryTrust=(row3)=>{let t2=row3.lifecycle?.trust;if(t2==="verified")return"Verified";if(t2==="mismatch")return"Mismatch";if(t2==="unverified")return"Unverified";return row3.bundled?"Bundled":"Legacy local"},gallerySource=(row3)=>{let src3=row3.lifecycle?.source;if(src3)return src3.identity??src3.repo??src3.origin??src3.kind;if(row3.bundled)return"bundled/system";return"local"},packageId=(row3)=>typeof row3.manifest?.id==="string"?row3.manifest.id:row3.bundled?"bundled/system":"\u2014",manifest4=(dir2)=>{let file2=join18(dir2,"manifest.json");if(!existsSync21(file2))return;try{let raw2=JSON.parse(readFileSync15(file2,"utf8"));return raw2&&typeof raw2==="object"&&!Array.isArray(raw2)?raw2:void 0}catch{return}},sourceBadge=(row3)=>row3.hasSource?"\u25CF source":row3.url||row3.bundled?"\u25CB source available":"\u2014 no source",key3=(value)=>{try{let url2=new URL(value);if(url2.protocol==="http:"||url2.protocol==="https:"||url2.protocol==="file:")return url2.href.replace(/\/?$/,"/").toLowerCase()}catch{}return value.toLowerCase()},ids2=(man,name,url2)=>{let origin2=man?.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:void 0;return[...new Set([typeof man?.id==="string"?man.id:void 0,typeof origin2?.sourceKey==="string"?origin2.sourceKey:void 0,typeof origin2?.identityKey==="string"?origin2.identityKey:void 0,typeof origin2?.packageUrl==="string"?origin2.packageUrl:void 0,typeof origin2?.source==="string"?origin2.source:void 0,url2,name].filter((x2)=>!!x2).map(key3))]};var import_react109=__toESM(require_react_production(),1);var import_react108=__toESM(require_react_production(),1);var fmt3=(n)=>n==null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(1)} KiB`:`${(n/1024/1024).toFixed(1)} MiB`,choices=(row3,sizes)=>{if(row3.installState==="incompatible"||row3.installState==="mismatch")return[{label:"Delist from Registry",hint:"opens an automatic GitHub delist request for the original submitter",value:"delist"}];if(!row3.installed)return[{label:"Eikon only",hint:fmt3(sizes?.eikon),value:"install"},{label:"Eikon + Source",hint:`${fmt3((sizes?.eikon??0)+(sizes?.source??0))} \xB7 Source files needed to edit Eikon in Studio`,value:"source"},{label:"Delist from Registry",hint:"opens an automatic GitHub delist request for the original submitter",value:"delist"}];return[...!row3.active?[{label:"Use",hint:"set as active avatar",value:"use"}]:[],...row3.sourceDownloadable?[{label:"Download Source",hint:"needed to edit in Studio",value:"download"}]:[],...row3.removable?[{label:"Delete",value:"delete"}]:[],{label:"Delist from Registry",hint:"opens an automatic GitHub delist request for the original submitter",value:"delist"}]},Action=(props)=>{let theme=useTheme().theme,opts=choices(props.row,props.sizes),[sel,setSel]=import_react108.useState(0),desc=opts.some((o)=>!!o.hint);return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.row.entry.name})}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.row.entry.description??"No description."}),$jsx("box",{height:1}),opts.length>0?$jsx("select",{focused:!0,width:62,height:Math.min(12,Math.max(1,opts.length*(desc?2:1))),options:opts.map((o)=>({name:o.label,description:o.hint??"",value:o.value})),selectedIndex:Math.min(sel,opts.length-1),showDescription:desc,showScrollIndicator:opts.length>6,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"},{name:"return",action:"select-current"}],onChange:(i)=>setSel(i),onSelect:(i)=>{let opt=opts[i];if(opt)props.onPick(opt.value)}}):$jsx("text",{fg:theme.textMuted,children:props.row.reason??"No available actions."}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"[\u2191\u2193] move [Space/Enter] confirm [Esc] cancel"})]})};function openEikonMarketplaceAction(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Action,{...opts,onPick:done}),()=>resolve4(null))})}init_perf();import{existsSync as existsSync22,readFileSync as readFileSync16,readdirSync as readdirSync9,writeFileSync as writeFileSync8}from"fs";import{createHash as createHash7}from"crypto";import{basename as basename15,dirname as dirname15,extname as extname4,join as join19}from"path";import{Buffer as Buffer6}from"buffer";var REPO2=process.env.EIKON_REPO??"liftaris/eikon",HOST="eikon.liftaris.dev",enc2=new TextEncoder;async function gh2(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?enc2.encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code2]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code2!==0)throw Error(err.trim()||out.trim()||`gh ${args[0]} failed`);return out.trim()}function json(text3){return JSON.parse(text3)}function clean4(value){return value.replace(/[^A-Za-z0-9_.-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function pkg(entry2){let parts2=entry2.id.includes("/")?entry2.id.split("/"):["liftaris",entry2.name];return{ns:parts2[0]||"liftaris",name:parts2[1]||entry2.name}}function dirs(entry2){let p=pkg(entry2);return[`eikons/${entry2.name}/`,`packages/${p.ns}/${p.name}/`]}function touches(entry2,path7){return dirs(entry2).some((dir2)=>path7.startsWith(dir2))}function official(entry2){try{return new URL(entry2.packageUrl).hostname===HOST&&[entry2.sourceKey,entry2.identityKey].some((key4)=>key4?.startsWith(`registry:${HOST}:`))}catch{return!1}}async function user(run){return run(["api","user","-q",".login"])}async function prs(entry2,repo2,run){let exact=(xs)=>xs.filter((pr)=>pr.title===`eikons: submit ${entry2.name}`&&pr.headRefName===`submit/${entry2.name}`),at=(pr)=>Number.isFinite(Date.parse(pr.mergedAt??""))?Date.parse(pr.mergedAt??""):0,sort=(xs)=>xs.toSorted((a,b2)=>at(a)-at(b2)||a.number-b2.number),first=exact(json(await run(["pr","list","-R",repo2,"--state","merged","--search",`"eikons: submit ${entry2.name}" in:title`,"--json","number,title,headRefName,url,mergedAt,author","--limit","100"])));if(first.length)return sort(first);return sort(exact(json(await run(["pr","list","-R",repo2,"--state","merged","--json","number,title,headRefName,url,mergedAt,author","--limit","100"]))))}async function files(repo2,pr,run){return(await run(["api","--paginate","-X","GET",`repos/${repo2}/pulls/${pr}/files`,"--jq",".[].filename"])).split(/\r?\n/).filter(Boolean).map((path7)=>({path:path7}))}async function found(entry2,repo2,run){for(let pr of await prs(entry2,repo2,run)){let title=pr.title===`eikons: submit ${entry2.name}`,head=pr.headRefName===`submit/${entry2.name}`;if(!title||!head)continue;if((await files(repo2,pr.number,run)).some((f)=>touches(entry2,f.path??f.filename??"")))return pr}return}async function info2(entry2,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2;if(!official(entry2))return{eligible:!1,reason:"Registry delist is only available for official Eikon catalog entries"};let login;try{login=await user(run)}catch(err){return{eligible:!1,reason:err instanceof Error?err.message:String(err)}}let pr=await found(entry2,repo2,run),author=pr?.author?.login;if(!pr||!author)return{eligible:!1,user:login,reason:"No merged GitHub submission found"};if(author!==login)return{eligible:!1,user:login,author,pr:pr.number,url:pr.url,reason:`Submitted by @${author}`};return{eligible:!0,user:login,author,pr:pr.number,url:pr.url}}async function exists(run,repo2,branch2,path7){try{let raw2=await run(["api","-X","GET",`repos/${repo2}/contents/${path7}`,"-f",`ref=${branch2}`]);return json(raw2).sha}catch{return}}async function put2(run,repo2,branch2,path7,text3,msg){let sha2=await exists(run,repo2,branch2,path7);await run(["api","-X","PUT",`repos/${repo2}/contents/${path7}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,content:Buffer6.from(text3).toString("base64"),...sha2?{sha:sha2}:{}}))}async function del(run,repo2,branch2,path7,sha2,msg){await run(["api","-X","DELETE",`repos/${repo2}/contents/${path7}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,sha:sha2}))}async function main2(run,repo2){let sha2=await run(["api",`repos/${repo2}/git/ref/heads/main`,"-q",".object.sha"]),tree2=await run(["api",`repos/${repo2}/git/commits/${sha2}`,"-q",".tree.sha"]);return{sha:sha2,tree:tree2}}async function tree2(run,repo2,sha2){return json(await run(["api","-X","GET",`repos/${repo2}/git/trees/${sha2}`,"-f","recursive=1"])).tree??[]}async function index2(run,repo2){let raw2=json(await run(["api","-X","GET",`repos/${repo2}/contents/eikons/index.json`,"-f","ref=main"]));return Buffer6.from((raw2.content??"").replace(/\s/g,""),"base64").toString("utf8")}async function reset3(run,repo2,name,sha2){try{await run(["api","-X","POST",`repos/${repo2}/git/refs`,"-f",`ref=refs/heads/${name}`,"-f",`sha=${sha2}`])}catch{await run(["api","-X","PATCH",`repos/${repo2}/git/refs/heads/${name}`,"--input","-"],JSON.stringify({sha:sha2,force:!0}))}}async function pr(run,repo2,user2,branch2,name,body){try{return await run(["pr","create","-R",repo2,"-H",`${user2}:${branch2}`,"-B","main","-t",`eikons: delist ${name}`,"-b",body])}catch{let raw2=await run(["api","-X","GET",`repos/${repo2}/pulls`,"-f","state=open","-f",`head=${user2}:${branch2}`]),hit2=json(raw2)[0]?.url;if(hit2)return hit2;throw Error("GitHub PR creation failed")}}async function submit3(entry2,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2,own=await info2(entry2,{repo:repo2,run});if(!own.eligible||!own.user)throw Error(own.reason??"not authorized to delist this eikon");await run(["repo","fork",repo2,"--clone=false"]).catch(()=>"");let fork2=`${own.user}/${repo2.split("/")[1]}`,branch2=`delist/${clean4(entry2.name)}`,base2=await main2(run,repo2);await reset3(run,fork2,branch2,base2.sha);let msg=`eikons: delist ${entry2.name}`,next2=json(await index2(run,repo2)).filter((e)=>e.name!==entry2.name&&e.id!==entry2.id);await put2(run,fork2,branch2,"eikons/index.json",`${JSON.stringify(next2,null,2)}
4169
+ `),yes:"install",no:"cancel"}))return;toast.show({variant:"info",message:`Installing from ${src4}\u2026`}),await exports_eikon.installPackage(src4).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,switchTo,toast]),doOpen=import_react104.useCallback(()=>{let cur=sRef.current,opts=[...eikonOptions(),{title:"+ New\u2026",value:"__new",category:""},{title:"+ Install\u2026",value:"__install",category:""}];dialog.replace($jsx(DialogSelect,{title:"Open eikon",current:cur?.name,options:opts,onSelect:(o)=>{if(dialog.clear(),o.value==="__new")return void doNew();if(o.value==="__install")return void doInstall();switchTo(o.value)}}),()=>{})},[dialog,eikonOptions,switchTo,doNew,doInstall]),doSubmit=import_react104.useCallback(async()=>{let cur=sRef.current;if(!cur)return;let path7=submitPath(cur.name);if(publishedInfo(path7)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}if(cur.dirty||!existsSync20(path7)){let pick2=await openSaveDiscard(dialog,{title:"Save before submit?",body:`'${cur.name}' has unsaved changes. Save to submit the current preview, discard to submit the last saved artifact, or keep editing.`});if(pick2==="save"){if(get2("eikon")===cur.name){if(!await openConfirm(dialog,{title:`Save active '${cur.name}' before submit?`,danger:!0,body:"Saving changes the active avatar's backing artifact. Submit itself will not change active selection.",yes:"save",no:"cancel"}))return}if(!await doSave())return}else if(pick2==="discard")open2(cur.name);else return}if(!existsSync20(path7)){toast.show({variant:"warning",message:"Save this eikon before submitting"});return}await openEikonSubmit(dialog,{name:cur.name,path:path7,submit:submit2})},[dialog,doSave,open2,toast]),doAction=async(id)=>{if(!s)return;if(id==="knobsfor")return mutate((p)=>p.per[p.state]?exports_eikon_knobs.unfork(p):exports_eikon_knobs.fork(p));if(id==="submit"){doSubmit();return}if(id==="revert"){discard();return}if(id==="reset"){if(await openConfirm(dialog,{title:"Reset settings?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!status?.downloadable||fetching)return;await download()}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Source\u2026",value:"source"},{title:s.per[s.state]?"Clear override (back to base)":"Tune this state only",value:"fork"}],onSelect:(o)=>{if(o.value==="source"){doSource();return}dialog.clear(),mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},setTone=(t2)=>mutate((p)=>({...p,tone:{...p.tone,...t2},dirty:!0})),stepRow=(row3,d2)=>{if(row3.kind==="tone"){if(row3.id==="contrast"){let def2=row3.knob,cur=sRef.current?.tone.contrast??1;return setTone({contrast:+Math.max(def2.min,Math.min(def2.max,cur+d2*def2.step)).toFixed(2)})}if(row3.id==="invert")return setTone({invert:!sRef.current?.tone.invert});if(row3.id==="flip"){let cur=sRef.current?.tone.flip??"none",i=FLIPS.indexOf(cur);return setTone({flip:FLIPS[(i+d2+FLIPS.length)%FLIPS.length]})}return}if(row3.kind!=="knob"||!row3.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row3.id,row3.knob,d2)))},act=(row3,via)=>{if(!row3||!sRef.current)return;if(row3.kind==="select"){if(row3.id==="open")return doOpen();return doSelectRasterizer()}if(row3.kind==="prompt")return void doPrompt(row3.id);if(row3.kind==="action"){if(via==="space"&&row3.id==="reset")return;return void doAction(row3.id)}if(row3.kind==="tone"||row3.kind==="knob"){if(row3.knob.kind==="slider")return;return stepRow(row3,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row3=navRows[selRef.current];if(!row3)return;if(row3.id==="knobsfor")return void doAction("knobsfor");stepRow(row3,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;let pick2=await openSaveDiscard(dialog,{title:"Unsaved edits",body:`'${cur.name}' has unsaved changes. Save them, discard them, or keep editing?`});if(pick2==="save"){if(await doSave())open2(cur.name);return!0}if(pick2==="discard")open2(cur.name);return!0},refresh=import_react104.useCallback(()=>{let cur=sRef.current;if(!cur)return;if(stampRef.current=exports_eikon.sourceStamp(cur.name),cur.dirty){toast.show({variant:"info",message:"Reload skipped: unsaved edits",duration:3000});return}open2(cur.name),toast.show({variant:"info",message:"Reloaded",duration:1000})},[open2,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(key3.eventType==="release")return;if(key3.name==="u"&&key3.ctrl&&sRef.current)return void doSaveUse();if(key3.name==="u"&&sRef.current)return void doSubmit();if(keys.match("eikon.save",key3)){if(!saving)doSave();return}if(key3.name==="escape")return void discard();if(key3.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key3.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key3.name==="return")return void doNew();return}if(pane==="knobs"){if(handleListKey(keys,key3,{count:navRows.length,setSel:setSelBy,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doNew(),onRefresh:refresh}))return;if(key3.name==="left")return adjust(-1);if(key3.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key3))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key3,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key3.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key3.name==="left"||key3.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key3.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key3.name))}return}if(key3.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key3.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key3.name==="return")return doStripMenu()});let onScroll=(e)=>{if(e.stopPropagation(),!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;let sign=d2==="up"?-1:1;if(e.modifiers.ctrl)return mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,sign),dirty:!0}));if(e.modifiers.shift)return mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,sign,0),dirty:!0}));mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,0,sign),dirty:!0}))},n=frames.length,title=s?`Preview \u2014 ${s.state}${s.per[s.state]?" (forked)":""}`+(n>1?` \xB7 ${play?"\u25B6":"\u23F8"} ${tick3%n+1}/${n}`:"")+(live?"":baked2?" \xB7 (baked)":""):"Preview",previewErr=err??(!s||src3||baked2?null:url2?"no source \u2014 Enter on 'download source'":"no source \u2014 Enter on 'source'"),hint=!s?[["Enter","new eikon"],["Shift+\u2192","library"]]:pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"edit"],[keys.print("list.refresh"),"reload"],[keys.print("list.new"),"new"],["u","submit"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","pan"],["Ctrl+wheel","zoom"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),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=$jsxs(TabShell,{title:spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:previewErr,focus:pane==="preview",children:[!live&&baked2?$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"Baked \u2014 download or attach source to edit."})}):null,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]}),help=helpOf(navRows[sel]),panel=$jsx(TabShell,{title:s?`Settings \u2014 ${s.name}`:"Settings",focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create or pick one."})}):$jsxs($Fragment,{children:[$jsx("scrollbox",{id:"studio-knob-scroll",ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,onMouseScroll:(e)=>e.stopPropagation(),children:rows3.map((row3,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row3.kind==="knob"&&!src3;return $jsx(KnobRow,{id:`knob-${row3.kind}-${row3.id}`,row:row3,s,r,status,on,dim:dim2,peek:peek5,busy:row3.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSelBy(ni)},onClick:()=>{if(ni>=0)setSelBy(ni),setPane("knobs"),act(row3,"click")},onWheel:(d2)=>stepRow(row3,d2),onSlide:row3.knob?.kind!=="slider"?void 0:row3.kind==="tone"?(v2)=>setTone({contrast:+v2.toFixed(2)}):(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row3.id,row3.knob,v2)))},`${row3.kind}:${r.name}:${row3.id}`)})}),$jsx("box",{flexShrink:0,height:HELP_H,marginTop:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:help})})]})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:18,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,stats,pending:pending3,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))},onEmpty:(st)=>doSource(st)})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+HELP_H+1+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:saving?"\u25CF saving\u2026":s?.dirty?"\u25CF unsaved":void 0})]})});var import_react106=__toESM(require_react_production(),1);import{existsSync as existsSync21,readFileSync as readFileSync15}from"fs";import{basename as basename14,dirname as dirname14,join as join18}from"path";var EIKON_CARD=50,titleWidth=(title,rows3)=>Math.max(title.length,...rows3.map((r)=>r.name.length+4))+7,cardWidth=(lines3)=>Math.max(EIKON_CARD,...lines3.map((line4)=>line4.length+2)),EikonTitleList=(props)=>{let theme=useTheme().theme;return $jsx("box",{width:props.width,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:props.title,focus:props.focus,grow:1,children:$jsx("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:$jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"row",height:1,paddingRight:3,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,children:[r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})})]},r.key)})})})})})},EikonCardGrid=(props)=>{let theme=useTheme().theme;if(props.rows.length===0)return $jsx("box",{padding:1,children:props.empty??$jsx("text",{fg:theme.textMuted,children:"No eikons found."})});return $jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"row",flexWrap:"wrap",width:"100%",flexShrink:0,children:props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"column",height:r.lines.length+2,width:cardWidth(r.lines),flexShrink:0,paddingX:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{height:r.lines.length,overflow:"hidden",flexDirection:"column",children:r.lines.map((line4,j2)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:line4||" "})},j2))}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:[on?"\u25B8 ":" ",r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.author??"unknown"," \xB7 ",r.status]})})]},r.key)})})})};var PREVIEW2=54,EikonGallery=import_react106.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),rev2=import_react106.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),dims=useTerminalDimensions(),rows3=import_react106.useMemo(()=>{let user=hermesPath("eikons"),own=exports_eikon.list(),map=new Map(own.map((x2)=>[x2.name.toLowerCase(),x2])),meta=own.map((x2)=>({inst:x2,ids:ids2(x2.manifest,x2.name,x2.sourceUrl)}));return[...listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():dirname14(e.path)===user?basename14(e.path,".eikon"):basename14(dirname14(e.path)),man=manifest4(dirname14(e.path)),keys2=ids2(man,slug3),mine=meta.find((x2)=>x2.ids.some((k2)=>keys2.includes(k2)))?.inst??map.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,url:mine?.sourceUrl,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3),lifecycle:mine?.lifecycle,...man?{manifest:man}:{}}}).filter((r)=>!(r.bundled&&r.lifecycle)).reduce((map2,row3)=>{let prev=map2.get(row3.slug);if(!prev||dirname14(prev.path)===user&&dirname14(row3.path)!==user)map2.set(row3.slug,row3);return map2},new Map).values()]},[rev2]),active=usePref("eikon"),path7=import_react106.useMemo(()=>active?exports_eikon.baked(active):void 0,[active,rev2]),current2=(row3)=>path7===row3.path,[sel,setSel]=import_react106.useState(0),[pane,setPane]=import_react106.useState("list"),[act,setAct]=import_react106.useState(0),galleryFollow=useFollow("gal",(i)=>rows3[i]?.slug??i),gridFollow=useFollow("lib-grid",(i)=>rows3[i]?.slug??i);import_react106.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],parsed=import_react106.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]),activate=(row3=cur)=>{if(!row3)return;if(row3.bundled)set("eikon",row3.slug);else exports_eikon.useInstalled(row3.slug);toast.show({variant:"success",message:`Avatar \u2192 ${row3.name}`})},doNew=import_react106.useCallback(async()=>{let res=await openNewEikon(dialog,{});if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),props.onEdit?.(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return props.onEdit?.(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,toast,props]),updateLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;try{let out=await exports_eikon.update(cur.slug);if("type"in out){if(!await openConfirm(dialog,{title:`Update active '${cur.name}'?`,danger:!0,body:`${out.message} The active avatar's backing package will change even though the selected name stays '${cur.slug}'.`,yes:"update active",no:"cancel"}))return;let done=await exports_eikon.update(cur.slug,{confirmActive:!0});if("type"in done)return toast.show({variant:"warning",message:done.message})}toast.show({variant:"success",message:`Updated ${cur.name}`})}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}},[cur,dialog,toast]),submitLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;let path8=submitPath(cur.slug);if(publishedInfo(path8)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path8,submit:props.submit??submit2})},[cur,dialog,props.submit,toast]),del=async()=>{if(!cur||cur.bundled)return;let here=current2(cur),base2=dirname14(cur.path)===hermesPath("eikons")?`Removes legacy flat file ${basename14(cur.path)}.`:`Removes ${dirname14(cur.path)} and all its sources.`,body=here?`${base2} This is the active avatar; deleting it will clear the active avatar selection.`:base2;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body}))return;let removed=exports_eikon.remove(cur.slug,{confirmActive:here});if(removed)return toast.show({variant:"warning",message:removed.message});toast.show({variant:"info",message:`Deleted ${cur.name}`})},actions=import_react106.useMemo(()=>{if(!cur)return[];return[{key:"Enter",label:current2(cur)?"Use as active avatar (active)":"Use as active avatar",run:()=>activate()},...props.onEdit?[{key:"e",label:"Edit in Studio",run:()=>props.onEdit?.(cur.slug)}]:[],...!cur.bundled?[{key:"u",label:"Update local package",run:()=>void updateLocal()},{key:"s",label:"Share to catalog",run:()=>void submitLocal()},{key:"d",label:"Delete local eikon",run:()=>void del(),danger:!0}]:[]]},[cur,path7,props.onEdit,updateLocal,submitLocal]);import_react106.useEffect(()=>{if(act>=actions.length)setAct(Math.max(0,actions.length-1))},[act,actions.length]);let cards=import_react106.useMemo(()=>rows3.map((r)=>{let p=(()=>{try{return parseEikonFile(r.path)}catch{return}})(),lines3=p?.resolve("state.idle")?.frames[0]??p?.states.get("idle")?.frames[0]??["(no preview)"];return{key:r.path,name:r.name,active:current2(r),author:r.author,status:current2(r)?"active":r.bundled?"bundled/system":"installed",lines:lines3}}),[rows3,path7]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;let plain=!key3.shift&&!key3.ctrl&&!key3.meta;if(key3.name==="tab")return setPane((p)=>p==="list"?"actions":"list");if(pane==="actions"){if(key3.name==="escape"||plain&&key3.name==="left"){setPane("list");return}if(plain&&key3.name==="up"){setAct((i)=>Math.max(0,i-1));return}if(plain&&key3.name==="down"){setAct((i)=>Math.min(actions.length-1,i+1));return}if(keys.match("list.activate",key3)||keys.match("list.toggle",key3)){actions[act]?.run();return}return}if(handleListKey(keys,key3,{count:rows3.length,setSel,page:galleryFollow.opts.page,scrollTo:(n)=>galleryFollow.ref.current?.scrollChildIntoView(galleryFollow.id(n)),onActivate:()=>activate(),onDelete:()=>void del(),onNew:doNew,onRefresh:()=>{exports_eikon.notifyRevision(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}))return;if(key3.name==="u"&&cur&&!cur.bundled)return void updateLocal();if(key3.name==="s"&&cur&&!cur.bundled)return void submitLocal();if(key3.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)});let listW=Math.max(13,...rows3.map((r)=>r.name.length+4))+7,showGrid=dims.width-listW-PREVIEW2>=EIKON_CARD;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minHeight:0,children:[$jsx(EikonTitleList,{title:`Library (${rows3.length})`,rows:rows3.map((r)=>({key:r.path,name:r.name,active:current2(r)})),sel,focus:props.focused&&pane==="list",follow:galleryFollow,width:listW,onSel:setSel,onUse:(i)=>activate(rows3[i])}),showGrid?$jsx(TabShell,{title:"Grid",grow:1,children:$jsx(EikonCardGrid,{rows:cards,sel,follow:gridFollow,onSel:setSel,onUse:(i)=>activate(rows3[i])})}):null,$jsx("box",{width:PREVIEW2,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:1,children:$jsxs("box",{flexDirection:"column",flexGrow:1,padding:1,alignItems:"center",children:[$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})}),cur?$jsxs("box",{flexDirection:"column",width:48,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:cur.name})}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",cur.author??"\u2014"]}),$jsxs("text",{fg:theme.textMuted,children:["Status: ",current2(cur)?"active":cur.bundled?"bundled/system":"installed"]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Source: ",gallerySource(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Trust: ",galleryTrust(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Package: ",packageId(cur)]}),$jsx("text",{fg:theme.textMuted,children:sourceBadge(cur)}),$jsx("box",{height:1}),$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Actions"})}),actions.map((a,i)=>$jsx("box",{height:1,overflow:"hidden",paddingRight:1,backgroundColor:pane==="actions"&&i===act?theme.backgroundElement:void 0,onMouseDown:()=>{setPane("actions"),setAct(i),a.run()},children:$jsxs("text",{fg:a.danger?theme.error:theme.text,wrapMode:"none",children:[pane==="actions"&&i===act?"\u25B8 ":" ",a.label," [",a.key,"]"]})},a.label))]}):null]})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="list"?"actions":"library"],[keys.print("list.activate"),pane==="actions"?"run action":"use"],["\u2191\u2193",pane==="actions"?"action":"select"],[keys.print("list.new"),"new / install"],[keys.print("list.refresh"),"reload"],...cur&&props.onEdit?[["e","edit in Studio"]]:[]]})]})}),galleryTrust=(row3)=>{let t2=row3.lifecycle?.trust;if(t2==="verified")return"Verified";if(t2==="mismatch")return"Mismatch";if(t2==="unverified")return"Unverified";return row3.bundled?"Bundled":"Legacy local"},gallerySource=(row3)=>{let src3=row3.lifecycle?.source;if(src3)return src3.identity??src3.repo??src3.origin??src3.kind;if(row3.bundled)return"bundled/system";return"local"},packageId=(row3)=>typeof row3.manifest?.id==="string"?row3.manifest.id:row3.bundled?"bundled/system":"\u2014",manifest4=(dir2)=>{let file2=join18(dir2,"manifest.json");if(!existsSync21(file2))return;try{let raw2=JSON.parse(readFileSync15(file2,"utf8"));return raw2&&typeof raw2==="object"&&!Array.isArray(raw2)?raw2:void 0}catch{return}},sourceBadge=(row3)=>row3.hasSource?"\u25CF source":row3.url||row3.bundled?"\u25CB source available":"\u2014 no source",key3=(value)=>{try{let url2=new URL(value);if(url2.protocol==="http:"||url2.protocol==="https:"||url2.protocol==="file:")return url2.href.replace(/\/?$/,"/").toLowerCase()}catch{}return value.toLowerCase()},ids2=(man,name,url2)=>{let origin2=man?.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:void 0;return[...new Set([typeof man?.id==="string"?man.id:void 0,typeof origin2?.sourceKey==="string"?origin2.sourceKey:void 0,typeof origin2?.identityKey==="string"?origin2.identityKey:void 0,typeof origin2?.packageUrl==="string"?origin2.packageUrl:void 0,typeof origin2?.source==="string"?origin2.source:void 0,url2,name].filter((x2)=>!!x2).map(key3))]};var import_react109=__toESM(require_react_production(),1);var import_react108=__toESM(require_react_production(),1);var fmt3=(n)=>n==null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(1)} KiB`:`${(n/1024/1024).toFixed(1)} MiB`,choices=(row3,sizes)=>{if(row3.installState==="incompatible"||row3.installState==="mismatch")return[{label:"Delist from Registry",value:"delist"}];if(!row3.installed)return[{label:"Eikon only",hint:fmt3(sizes?.eikon),value:"install"},{label:"Eikon + Source",hint:`${fmt3((sizes?.eikon??0)+(sizes?.source??0))} \xB7 Source files needed to edit Eikon in Studio`,value:"source"},{label:"Delist from Registry",value:"delist"}];return[...!row3.active?[{label:"Use",hint:"set as active avatar",value:"use"}]:[],...row3.sourceDownloadable?[{label:"Download Source",hint:"needed to edit in Studio",value:"download"}]:[],...row3.removable?[{label:"Uninstall",value:"delete"}]:[],{label:"Delist from Registry",value:"delist"}]},Action=(props)=>{let theme=useTheme().theme,opts=choices(props.row,props.sizes),[sel,setSel]=import_react108.useState(0),desc=opts.some((o)=>!!o.hint);return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.row.entry.name})}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.row.entry.description??"No description."}),$jsx("box",{height:1}),opts.length>0?$jsx("select",{focused:!0,width:62,height:Math.min(12,Math.max(1,opts.length*(desc?2:1))),options:opts.map((o)=>({name:o.label,description:o.hint??"",value:o.value})),selectedIndex:Math.min(sel,opts.length-1),showDescription:desc,showScrollIndicator:opts.length>6,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"},{name:"return",action:"select-current"}],onChange:(i)=>setSel(i),onSelect:(i)=>{let opt=opts[i];if(opt)props.onPick(opt.value)}}):$jsx("text",{fg:theme.textMuted,children:props.row.reason??"No available actions."}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"[\u2191\u2193] move [Space/Enter] confirm [Esc] cancel"})]})};function openEikonMarketplaceAction(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Action,{...opts,onPick:done}),()=>resolve4(null))})}init_perf();import{existsSync as existsSync22,readFileSync as readFileSync16,readdirSync as readdirSync9,writeFileSync as writeFileSync8}from"fs";import{createHash as createHash7}from"crypto";import{basename as basename15,dirname as dirname15,extname as extname4,join as join19}from"path";import{Buffer as Buffer6}from"buffer";var REPO2=process.env.EIKON_REPO??"liftaris/eikon",HOST="eikon.liftaris.dev",enc2=new TextEncoder;async function gh2(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?enc2.encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code2]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code2!==0)throw Error(err.trim()||out.trim()||`gh ${args[0]} failed`);return out.trim()}function json(text3){return JSON.parse(text3)}function clean4(value){return value.replace(/[^A-Za-z0-9_.-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function pkg(entry2){let parts2=entry2.id.includes("/")?entry2.id.split("/"):["liftaris",entry2.name];return{ns:parts2[0]||"liftaris",name:parts2[1]||entry2.name}}function dirs(entry2){let p=pkg(entry2);return[`eikons/${entry2.name}/`,`packages/${p.ns}/${p.name}/`]}function touches(entry2,path7){return dirs(entry2).some((dir2)=>path7.startsWith(dir2))}function official(entry2){try{return new URL(entry2.packageUrl).hostname===HOST&&[entry2.sourceKey,entry2.identityKey].some((key4)=>key4?.startsWith(`registry:${HOST}:`))}catch{return!1}}async function user(run){return run(["api","user","-q",".login"])}async function prs(entry2,repo2,run){let exact=(xs)=>xs.filter((pr)=>pr.title===`eikons: submit ${entry2.name}`&&pr.headRefName===`submit/${entry2.name}`),at=(pr)=>Number.isFinite(Date.parse(pr.mergedAt??""))?Date.parse(pr.mergedAt??""):0,sort=(xs)=>xs.toSorted((a,b2)=>at(a)-at(b2)||a.number-b2.number),first=exact(json(await run(["pr","list","-R",repo2,"--state","merged","--search",`"eikons: submit ${entry2.name}" in:title`,"--json","number,title,headRefName,url,mergedAt,author","--limit","100"])));if(first.length)return sort(first);return sort(exact(json(await run(["pr","list","-R",repo2,"--state","merged","--json","number,title,headRefName,url,mergedAt,author","--limit","100"]))))}async function files(repo2,pr,run){return(await run(["api","--paginate","-X","GET",`repos/${repo2}/pulls/${pr}/files`,"--jq",".[].filename"])).split(/\r?\n/).filter(Boolean).map((path7)=>({path:path7}))}async function found(entry2,repo2,run){for(let pr of await prs(entry2,repo2,run)){let title=pr.title===`eikons: submit ${entry2.name}`,head=pr.headRefName===`submit/${entry2.name}`;if(!title||!head)continue;if((await files(repo2,pr.number,run)).some((f)=>touches(entry2,f.path??f.filename??"")))return pr}return}async function info2(entry2,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2;if(!official(entry2))return{eligible:!1,reason:"Registry delist is only available for official Eikon catalog entries"};let login;try{login=await user(run)}catch(err){return{eligible:!1,reason:err instanceof Error?err.message:String(err)}}let pr=await found(entry2,repo2,run),author=pr?.author?.login;if(!pr||!author)return{eligible:!1,user:login,reason:"No merged GitHub submission found"};if(author!==login)return{eligible:!1,user:login,author,pr:pr.number,url:pr.url,reason:`Submitted by @${author}`};return{eligible:!0,user:login,author,pr:pr.number,url:pr.url}}async function exists(run,repo2,branch2,path7){try{let raw2=await run(["api","-X","GET",`repos/${repo2}/contents/${path7}`,"-f",`ref=${branch2}`]);return json(raw2).sha}catch{return}}async function put2(run,repo2,branch2,path7,text3,msg){let sha2=await exists(run,repo2,branch2,path7);await run(["api","-X","PUT",`repos/${repo2}/contents/${path7}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,content:Buffer6.from(text3).toString("base64"),...sha2?{sha:sha2}:{}}))}async function del(run,repo2,branch2,path7,sha2,msg){await run(["api","-X","DELETE",`repos/${repo2}/contents/${path7}`,"--input","-"],JSON.stringify({message:msg,branch:branch2,sha:sha2}))}async function main2(run,repo2){let sha2=await run(["api",`repos/${repo2}/git/ref/heads/main`,"-q",".object.sha"]),tree2=await run(["api",`repos/${repo2}/git/commits/${sha2}`,"-q",".tree.sha"]);return{sha:sha2,tree:tree2}}async function tree2(run,repo2,sha2){return json(await run(["api","-X","GET",`repos/${repo2}/git/trees/${sha2}`,"-f","recursive=1"])).tree??[]}async function index2(run,repo2){let raw2=json(await run(["api","-X","GET",`repos/${repo2}/contents/eikons/index.json`,"-f","ref=main"]));return Buffer6.from((raw2.content??"").replace(/\s/g,""),"base64").toString("utf8")}async function reset3(run,repo2,name,sha2){try{await run(["api","-X","POST",`repos/${repo2}/git/refs`,"-f",`ref=refs/heads/${name}`,"-f",`sha=${sha2}`])}catch{await run(["api","-X","PATCH",`repos/${repo2}/git/refs/heads/${name}`,"--input","-"],JSON.stringify({sha:sha2,force:!0}))}}async function pr(run,repo2,user2,branch2,name,body){try{return await run(["pr","create","-R",repo2,"-H",`${user2}:${branch2}`,"-B","main","-t",`eikons: delist ${name}`,"-b",body])}catch{let raw2=await run(["api","-X","GET",`repos/${repo2}/pulls`,"-f","state=open","-f",`head=${user2}:${branch2}`]),hit2=json(raw2)[0]?.url;if(hit2)return hit2;throw Error("GitHub PR creation failed")}}async function submit3(entry2,opts={}){let run=opts.run??gh2,repo2=opts.repo??REPO2,own=await info2(entry2,{repo:repo2,run});if(!own.eligible||!own.user)throw Error(own.reason??"not authorized to delist this eikon");await run(["repo","fork",repo2,"--clone=false"]).catch(()=>"");let fork2=`${own.user}/${repo2.split("/")[1]}`,branch2=`delist/${clean4(entry2.name)}`,base2=await main2(run,repo2);await reset3(run,fork2,branch2,base2.sha);let msg=`eikons: delist ${entry2.name}`,next2=json(await index2(run,repo2)).filter((e)=>e.name!==entry2.name&&e.id!==entry2.id);await put2(run,fork2,branch2,"eikons/index.json",`${JSON.stringify(next2,null,2)}
4170
4170
  `,msg);for(let item of await tree2(run,repo2,base2.tree)){if(!item.path||item.type!=="blob"||!item.sha||!touches(entry2,item.path))continue;let sha2=await exists(run,fork2,branch2,item.path)??item.sha;await del(run,fork2,branch2,item.path,sha2,msg)}return{url:await pr(run,repo2,own.user,branch2,entry2.name,`Requests delisting \`${entry2.name}\` from the Eikon registry.`),info:own}}var DEFAULT_TIMEOUT=5000,DEFAULT_CACHE_LIMIT=24,OFFICIAL_CATALOG="https://eikon.liftaris.dev/eikons",dec=new TextDecoder;function hash2(data2){return`sha256:${createHash7("sha256").update(data2).digest("hex")}`}function keyIdentity(s){try{let u3=new URL(s);if(u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")return u3.href.replace(/\/?$/,"/")}catch{}return s}function manifestBaseKey(s){try{let u3=new URL(s);if((u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")&&u3.pathname.endsWith("/manifest.json"))return new URL(".",u3).href}catch{}return}function registryKey(man,source2){if(man?.kind!=="eikon.package"||typeof man.id!=="string")return;let sourceKey=man.origin?.sourceKey??man.origin?.identityKey;if(sourceKey)return keyIdentity(sourceKey);try{let host=source2?new URL(source2).host:void 0;if(!host)return;return`registry:${host}:${man.id}${typeof man.version==="string"&&man.version?`@${man.version}`:""}`}catch{return}}function entryKeys(entry2){return[...new Set([entry2.identityKey,entry2.sourceKey].filter(Boolean).map(keyIdentity))]}function keysFor(inst){let keys=new Set,man=inst.manifest,origin2=typeof man?.origin?.source==="string"?man.origin.source:void 0,head=exports_eikon.header(inst.file),src3=typeof head?.source_url==="string"?head.source_url:inst.sourceUrl,registry2=registryKey(man,origin2);if(registry2)keys.add(registry2);if(origin2){keys.add(keyIdentity(origin2));let base2=manifestBaseKey(origin2);if(base2)keys.add(keyIdentity(base2))}if(src3){keys.add(keyIdentity(src3));let base2=manifestBaseKey(src3);if(base2)keys.add(keyIdentity(base2))}return[...keys]}function read(path7){try{let man=JSON.parse(readFileSync16(path7,"utf8"));return obj(man)?man:void 0}catch{return}}function chosen(active,name){return active===name||active==="default"&&name==="nous"}function media(dir2){return existsSync22(dir2)&&readdirSync9(dir2).length>0}function text3(value){return typeof value==="string"&&value?value:void 0}function life(name,man){let origin2=obj(man.origin)?man.origin:{},display3=obj(man.display)?man.display:{},src3=text3(origin2.source),identity2=text3(origin2.identityKey)??text3(origin2.sourceKey)??text3(origin2.packageUrl)??text3(origin2.repo)??src3,title=text3(display3.title)??text3(man.title),author=text3(display3.author)??text3(man.author);return{name,...title?{title}:{},...author?{author}:{},...text3(man.version)?{version:text3(man.version)}:{},source:{kind:text3(origin2.kind)??"default-catalog",...identity2?{identity:identity2}:{},...src3?{origin:src3}:{},...text3(origin2.repo)?{repo:text3(origin2.repo)}:{},...text3(origin2.selector)?{selector:text3(origin2.selector)}:{},...text3(origin2.catalogRoot)?{catalogRoot:text3(origin2.catalogRoot)}:{},...text3(origin2.sha)?{sha:text3(origin2.sha)}:{},...text3(origin2.packageUrl)?{packageUrl:text3(origin2.packageUrl)}:{}},trust:text3(origin2.trust)??"verified",active:chosen(get2("eikon"),name),removable:!1,updateable:Boolean(src3??text3(origin2.packageUrl)),updateAvailable:!1,dirty:!1,...text3(man.poster)?{poster:text3(man.poster)}:{},...obj(man.compatibility)?{compatibility:man.compatibility}:{},...text3(origin2.at)?{installedAt:text3(origin2.at)}:{}}}function bundled(xs){let names=new Set(xs.map((x2)=>x2.name.toLowerCase()));return listEikons([BUNDLED_EIKON_DIR]).flatMap((e)=>{let man=read(join19(dirname15(e.path),"manifest.json"));if(man?.kind!=="eikon.package")return[];let name=text3(man.name)??e.meta.name.toLowerCase();if(names.has(name.toLowerCase()))return[];let inst={name,file:e.path,source:exports_eikon.sourceDir(name),hasSource:media(exports_eikon.sourceDir(name)),sourceUrl:text3(man.origin?.source)??text3(man.origin?.packageUrl),manifest:man,lifecycle:life(name,man)};return[{...inst,manifest:man,identityKeys:keysFor(inst)}]})}function cacheKey(entry2){return[entry2.identityKey||entry2.sourceKey||entry2.id,entry2.runtimeUrl,entry2.trust?.runtimeDigest,entry2.trust?.runtimeSize].filter(Boolean).join("|")}function blob(url2){return/\/blobs\/sha256\/[^/?#]+/.test(url2)}function artifact(entry2){return entry2}function obj(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}function rawManifest(entry2){let raw2=entry2.raw;return obj(raw2.manifest)?raw2.manifest:void 0}function role(file2){if(file2.role==="source.base")return"base";if(file2.role?.startsWith("source."))return file2.role.slice(7);if(!file2.path)return;return basename15(file2.path,extname4(file2.path)).toLowerCase()||"base"}function sourceEntries2(man,strict=!1){if(!man)return[];try{let xs=entries(man).map(([r,rel2])=>[r,rel2]);if(xs.length)return xs;return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}catch(err){if(strict)throw err}return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}function sourceDescriptors3(man){return sourceEntries2(man).length>0}function sourceAvailable2(entry2,inst){return sourceDescriptors3(inst?.manifest)||sourceDescriptors3(rawManifest(entry2))}function trust(entry2){return entry2.trust}function boundTrust(entry2,raw2){let t2=trust(entry2),man=t2.manifestDigest,run=t2.runtimeDigest;if(!man&&!run)return"unverified";if(man&&hash2(raw2)!==man)throw Error(`catalog trust mismatch: manifest digest for ${entry2.name}`);let pkg2=JSON.parse(dec.decode(raw2)),rel2=pkg2.entrypoints?.default,got=rel2?pkg2.files?.find((f)=>f.path===rel2)?.digest:void 0;if(run&&got!==run)throw Error(`catalog trust mismatch: runtime digest for ${entry2.name}`);return man&&run?"verified":"unverified"}function spec2(man,rel2){return man.files?.find((f)=>f.path===rel2)}async function sourceBytes(man,base2,rel2,opts){let file2=spec2(man,rel2);if(!file2?.digest||typeof file2.size!=="number")throw Error(`source descriptor missing digest or size: ${rel2}`);let raw2=await downloadBytes(new URL(rel2,base2).href,opts);if(raw2.length!==file2.size)throw Error(`source size mismatch: ${rel2}`);if(hash2(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}function target(input){return typeof input==="string"?input:input instanceof URL?input.href:input.url}function verifiedCatalogTrust(entry2){let t2=trust(entry2);return typeof t2.manifestDigest==="string"&&t2.manifestDigest.length>0&&typeof t2.runtimeDigest==="string"&&t2.runtimeDigest.length>0}function installed(){let xs=exports_eikon.list().map((inst)=>({...inst,manifest:inst.manifest,identityKeys:keysFor(inst)}));return[...xs,...bundled(xs)]}function match2(entry2,xs){let keys=entryKeys(entry2),exact=xs.find((x2)=>x2.identityKeys.some((k2)=>keys.includes(k2)));if(exact)return{inst:exact,legacy:!1};let named=xs.find((x2)=>x2.name===entry2.name&&x2.identityKeys.length===0);if(named)return{inst:named,legacy:!0};return}function row3(entry2,xs){let usable=match2(entry2,xs),active=usable?chosen(get2("eikon"),usable.inst.name):!1,installed2=Boolean(usable),conflict=!usable&&chosen(get2("eikon"),entry2.name),blocked=entry2.compatibility?.available===!1,mismatch=usable?.inst.lifecycle.trust==="mismatch",installState=mismatch?"mismatch":blocked?"incompatible":active?"active":conflict?"active-name-conflict":!usable?"available":usable.legacy?"legacy-name-match":"installed",lifecycle2=usable?.inst.lifecycle??{name:entry2.name,title:entry2.title,author:entry2.author,version:entry2.version,source:{kind:"default-catalog",identity:entry2.sourceKey,packageUrl:entry2.packageUrl},trust:verifiedCatalogTrust(entry2)?"verified":"unverified",active:!1,removable:!1,updateable:!1,updateAvailable:!1,dirty:!1,...entry2.poster?{poster:entry2.poster}:{},compatibility:entry2.compatibility},available=sourceAvailable2(entry2,usable?.inst);return{entry:entry2,installed:installed2,active,installState,...usable?.inst.file?{installedPath:usable.inst.file,installedName:usable.inst.name}:{},...usable?.inst.manifest?{installedManifest:usable.inst.manifest}:{},lifecycle:lifecycle2,trust:lifecycle2.trust,updateable:lifecycle2.updateable,updateAvailable:lifecycle2.updateAvailable,removable:lifecycle2.removable,sourceIdentity:lifecycle2.source.identity,sourcePresent:usable?.inst.hasSource??!1,sourceAvailable:available,sourceDownloadable:Boolean(usable&&!usable.inst.hasSource&&available),reason:blocked?entry2.compatibility?.reason??"incompatible":mismatch?"trust mismatch":conflict?"install would replace the active avatar backing package":void 0,action:active?"active":installed2?"use":"install"}}function sizes(man){let files2=Array.isArray(man.files)?man.files:[],eikon=files2.filter((f)=>f.role==="runtime"||f.path===man.entrypoints?.default).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0),source2=files2.filter((f)=>typeof f.role==="string"&&f.role.startsWith("source")).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0);return{...eikon>0?{eikon}:{},...source2>0?{source:source2}:{}}}function abortErr(){return new DOMException("aborted","AbortError")}class MarketplaceService{catalog;fetcher;timeoutMs;previewCacheLimit;concurrency;allowPrivate;official;delistRepo;delistRun;activeLoads=0;queue=[];cache=new Map;inFlight=new Map;constructor(catalog3,opts={}){this.catalog=catalog3,this.fetcher=opts.fetcher??fetch,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT,this.previewCacheLimit=opts.previewCacheLimit??DEFAULT_CACHE_LIMIT,this.concurrency=Math.max(1,Math.floor(opts.concurrency??4)),this.allowPrivate=opts.allowPrivate===!0,this.official=keyIdentity(publicCatalogUrl(opts.catalog??OFFICIAL_CATALOG,void 0,opts))===keyIdentity(OFFICIAL_CATALOG),this.delistRepo=opts.delistRepo,this.delistRun=opts.delistRun}rows(query=""){let entries2=searchCatalog(this.catalog.entries,query),xs=installed();return entries2.map((e)=>row3(e,xs))}entry(id){let key4=keyIdentity(id);return this.catalog.entries.find((e)=>keyIdentity(e.identityKey)===key4||keyIdentity(e.sourceKey)===key4||e.id===id||e.name===id)}dl(signal,fetcher=this.fetcher){return{allowPrivate:this.allowPrivate,fetcher:(input,init)=>fetcher(input,signal?{...init,signal}:init)}}runtime(entry2,signal){return async(input)=>{let url2=target(input),bound=keyIdentity(url2)===keyIdentity(entry2.runtimeUrl)&&(!!entry2.trust?.runtimeDigest||blob(url2)),raw2=await downloadBytes(url2,{...this.dl(signal),rejectContentEncoding:bound}),buf=raw2.buffer.slice(raw2.byteOffset,raw2.byteOffset+raw2.byteLength);return new Response(buf,{headers:{"content-length":String(raw2.length)}})}}cached(url2,raw2){let key4=keyIdentity(url2);return async(input,init)=>{if(keyIdentity(target(input))===key4)return new Response(raw2.slice(),{headers:{"content-length":String(raw2.length)}});return this.fetcher(input,init)}}async preview(id,opts={}){if(opts.signal?.aborted)throw abortErr();let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);let key4=cacheKey(entry2),hit2=this.cache.get(key4);if(hit2!==void 0)return hit2;let active=this.inFlight.get(key4);if(active)return active;let p=this.enqueue(()=>this.loadPreview(entry2,opts)).finally(()=>this.inFlight.delete(key4));return this.inFlight.set(key4,p),p}async packageSizes(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);return sizes(JSON.parse(dec.decode(await downloadBytes(entry2.packageUrl,this.dl()))))}async delistInfo(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);if(!this.official)return{eligible:!1,reason:"Registry delist is only available from the official Eikon catalog"};return info2(entry2,{repo:this.delistRepo,run:this.delistRun})}async delist(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);if(!this.official)throw Error("Registry delist is only available from the official Eikon catalog");return submit3(entry2,{repo:this.delistRepo,run:this.delistRun})}async install(id,opts={}){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);if(entry2.compatibility?.available===!1)throw Error(entry2.compatibility.reason??"eikon is incompatible");if(!match2(entry2,installed())&&chosen(get2("eikon"),entry2.name)&&!opts.confirmActive)throw Error(`Installing '${entry2.name}' will replace the active avatar's backing package. Pass confirmActive to install it.`);let raw2=await downloadBytes(entry2.packageUrl,this.dl()),state2=boundTrust(entry2,raw2),out=await exports_eikon.fetchSource(entry2.packageUrl,{name:entry2.name,media:opts.media===!0,downloader:this.dl(void 0,this.cached(entry2.packageUrl,raw2))}),ef=exports_eikon.file(out.name);if(!existsSync22(ef)){let art=await loadRuntimeArtifact(entry2,this.runtime(entry2),{allowPrivate:this.allowPrivate});await Bun.write(ef,art.bytes),exports_eikon.notifyRevision()}let mf=join19(exports_eikon.dir(out.name),"manifest.json"),man=JSON.parse(readFileSync16(mf,"utf8")),origin2=man.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:{};return writeFileSync8(mf,JSON.stringify({...man,origin:{...origin2,sourceKey:entry2.sourceKey,identityKey:entry2.identityKey,packageUrl:entry2.packageUrl,trust:state2}},null,2)+`
4171
4171
  `),out}async downloadSource(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);let usable=match2(entry2,installed());if(!usable)throw Error(`marketplace: "${entry2.name}" is not installed`);if(!sourceAvailable2(entry2,usable.inst))throw Error(`marketplace: no source media published for "${entry2.name}"`);let raw2=await downloadBytes(entry2.packageUrl,this.dl());boundTrust(entry2,raw2);let man=JSON.parse(dec.decode(raw2)),xs=sourceEntries2(man,!0);if(xs.length===0)throw Error(`marketplace: no source media published for "${entry2.name}"`);let base2=new URL(".",entry2.packageUrl).href,dir2=exports_eikon.ensure(usable.inst.name).source,pairs=await Promise.all(xs.map(async([r,rel2])=>{let data2=await sourceBytes(man,base2,rel2,this.dl());return[r,exports_eikon.sourceName(man,r,rel2),data2]})),sources={};return await Promise.all(pairs.map(async([r,fname,data2])=>{await Bun.write(join19(dir2,fname),data2),sources[r]=fname})),exports_eikon.attachSources(usable.inst.name,sources),{name:usable.inst.name,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}enqueue(run){return new Promise((resolve4,reject)=>{this.queue.push({run,resolve:resolve4,reject}),this.pump()})}pump(){if(this.activeLoads>=this.concurrency)return;let job=this.queue.shift();if(!job)return;this.activeLoads+=1,job.run().then(job.resolve,job.reject).finally(()=>{this.activeLoads-=1,this.pump()})}async loadPreview(entry2,opts){let ctl=new AbortController,timeout=setTimeout(()=>ctl.abort(),opts.timeoutMs??this.timeoutMs),off=()=>ctl.abort();opts.signal?.addEventListener("abort",off,{once:!0});try{let item=artifact(entry2),text4=(await loadRuntimeArtifact(item,this.runtime(item,ctl.signal),{signal:ctl.signal,allowPrivate:this.allowPrivate})).text;this.cache.set(cacheKey(entry2),text4);while(this.cache.size>this.previewCacheLimit)this.cache.delete(this.cache.keys().next().value);return text4}finally{clearTimeout(timeout),opts.signal?.removeEventListener("abort",off)}}}async function load4(opts={}){let query=opts.query??"";try{if(opts.catalog)publicCatalogUrl(opts.catalog,void 0,opts);let cat=await loadCatalog(opts.catalog,opts.fetcher??fetch,opts),service=new MarketplaceService(cat,opts),rows3=service.rows(query);return{status:rows3.length>0?"ready":"empty",query,rows:rows3,selected:rows3[0],service}}catch(err){return{status:"error",query,rows:[],error:err instanceof Error?err.message:String(err)}}}var NO_MARKET={status:"empty",query:"",rows:[]},DETAIL=54;function localCatalog(raw2){if(!raw2)return!1;try{let url2=new URL(raw2),host=url2.hostname.toLowerCase().replace(/^\[|\]$/g,"");return url2.protocol==="file:"||host==="localhost"||host==="127.0.0.1"||host==="0.0.0.0"||host==="::1"||host.endsWith(".localhost")}catch{return!1}}var filterRows=(rows3,query)=>{let q5=query.trim().toLowerCase();if(!q5)return rows3;return rows3.filter((r)=>[r.entry.name,r.entry.author,r.entry.description,r.entry.id].some((x2)=>typeof x2==="string"&&x2.toLowerCase().includes(q5)))},EikonMarketplace=import_react109.memo((props)=>{let toast=useToast(),dialog=useDialog(),keys=useKeys(),theme=useTheme().theme,rev2=import_react109.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),[sel,setSel]=import_react109.useState(0),[searching,setSearching]=import_react109.useState(!1),[query,setQuery]=import_react109.useState(""),[state2,setState2]=import_react109.useState(NO_MARKET),[loading,setLoading]=import_react109.useState(!1),[installing,setInstalling]=import_react109.useState(!1),[acting,setActing]=import_react109.useState(!1),[previewState,setPreviewState]=import_react109.useState("idle"),[preview2,setPreview]=import_react109.useState(void 0),[pane,setPane]=import_react109.useState("grid"),previewSeq=import_react109.useRef(0),loadSeq=import_react109.useRef(0),actingRef=import_react109.useRef(!1),follow=useFollow("market",(i)=>state2.rows[i]?.entry.identityKey??i),listFollow=useFollow("market-list",(i)=>state2.rows[i]?.entry.identityKey??i),dims=useTerminalDimensions();import_react109.useEffect(()=>{if(sel>=state2.rows.length)setSel(Math.max(0,state2.rows.length-1))},[state2.rows.length,sel]);let selected=state2.rows[sel];import_react109.useEffect(()=>{if(!selected||!state2.service){setPreview(void 0);return}let id=++previewSeq.current,key4=selected.entry.identityKey;count("market:preview:load"),state2.service.preview(key4).then((text4)=>{if(previewSeq.current!==id)return;let e=parseEikon(text4),st=e.states.has(previewState)?previewState:"idle";setPreview({eikon:e,state:st,states:[...e.states.keys()]}),count("market:preview:ready")}).catch(()=>{if(previewSeq.current!==id)return;setPreview(void 0),count("market:preview:error")})},[selected,state2.service,previewState]),import_react109.useEffect(()=>()=>{previewSeq.current++,setPreview(void 0)},[]);let loadMarket=import_react109.useCallback((q5=query)=>{let id=++loadSeq.current;setLoading(!0);let end=mark("market:list:load"),catalog3=process.env.EIKON_URL;load4({catalog:catalog3,allowPrivate:localCatalog(catalog3),query:q5}).then((next2)=>{if(loadSeq.current!==id)return;count("market:list:rows",next2.rows.length);let rows3=next2.service?filterRows(next2.service.rows(""),q5):filterRows(next2.rows,q5);setState2({...next2,status:rows3.length>0?"ready":"empty",rows:rows3,selected:rows3[0]}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))}).finally(()=>{if(end(),loadSeq.current===id)setLoading(!1)})},[query]),refreshMarket=import_react109.useCallback((svc,q5=query)=>{let rows3=filterRows(svc.rows(""),q5);setState2({status:rows3.length>0?"ready":"empty",query:q5,rows:rows3,selected:rows3[0],service:svc}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))},[query]);import_react109.useEffect(()=>{loadMarket(query)},[query,rev2,loadMarket]);let cycle3=import_react109.useCallback((by)=>{let states=preview2?.states,cur=preview2?.state;if(!states?.length||!cur)return;let at=Math.max(0,states.indexOf(cur));setPreviewState(states[(at+by+states.length)%states.length])},[preview2]),removeSelected=import_react109.useCallback(async(idx)=>{let row4=state2.rows[idx??sel],svc=state2.service,name=row4?.installedName??row4?.entry.name;if(!row4||!svc||!name||!row4.removable)return toast.show({variant:"warning",message:"This eikon is not removable"});let active=row4.active;if(!await openConfirm(dialog,{title:`Remove '${name}'?`,danger:!0,body:active?`Remove the local package for '${name}'. This is the active avatar; removal will clear the active avatar selection.`:`Remove the local package for '${name}'. This does not change the active avatar.`,yes:"remove",no:"cancel"}))return;let out=exports_eikon.remove(name,{confirmActive:active});if(out)return toast.show({variant:"warning",message:out.message});toast.show({variant:"info",message:`Removed '${name}'`}),refreshMarket(svc,query)},[dialog,query,refreshMarket,sel,state2.rows,state2.service,toast]),delistSelected=import_react109.useCallback(async(row4,svc)=>{let own;try{own=await svc.delistInfo(row4.entry.identityKey)}catch(err){toast.show({variant:"error",title:"Delist check failed",message:err instanceof Error?err.message:String(err),duration:6000});return}if(!own.eligible){toast.show({variant:"warning",title:"Delist unavailable",message:own.reason??"Only the original GitHub submitter can delist this eikon",duration:6000});return}if(!await openConfirm(dialog,{title:`Delist '${row4.entry.name}'?`,danger:!0,body:`This will open a GitHub delist request in liftaris/eikon for '${row4.entry.name}'. The registry will remove it automatically after authorship is verified.`,yes:"delist",no:"cancel"}))return;try{let out=await svc.delist(row4.entry.identityKey);toast.show({variant:"success",title:"Delist requested",message:`${row4.entry.name} will be removed automatically once GitHub verifies the request. ${out.url}`,duration:8000})}catch(err){toast.show({variant:"error",title:"Delist failed",message:err instanceof Error?err.message:String(err),duration:6000})}},[dialog,toast]),primary=import_react109.useCallback((idx)=>{let row4=state2.rows[idx??sel],svc=state2.service;if(!row4||!svc||actingRef.current||acting)return;(async()=>{actingRef.current=!0,setActing(!0);try{let sizes2=!row4.installed?await svc.packageSizes(row4.entry.identityKey).catch(()=>{return}):void 0,pick2=await openEikonMarketplaceAction(dialog,{row:row4,sizes:sizes2});if(!pick2)return;if(pick2==="use"){let name=row4.installedName??row4.entry.name;exports_eikon.useInstalled(name),toast.show({variant:"success",message:`Avatar \u2192 ${name}`}),refreshMarket(svc,query);return}if(pick2==="delete")return removeSelected(idx);if(pick2==="delist")return delistSelected(row4,svc);setInstalling(!0);try{if(!(row4.installState==="active-name-conflict"?await openConfirm(dialog,{title:`Replace active '${row4.entry.name}'?`,danger:!0,body:`Installing this catalog package will replace the active avatar's backing package for '${row4.entry.name}' because another package with the same installed name is active.`,yes:"replace active",no:"cancel"}):!0))return;let out=pick2==="download"?await svc.downloadSource(row4.entry.identityKey):await svc.install(row4.entry.identityKey,{media:pick2==="source",confirmActive:row4.installState==="active-name-conflict"});toast.show({variant:"success",message:pick2==="download"?`Downloaded source for '${out.name}'`:`Installed '${out.name}' (${out.n} files)`}),refreshMarket(svc,query)}catch(err){toast.show({variant:"error",title:pick2==="download"?"Source download failed":"Install failed",message:err instanceof Error?err.message:String(err),duration:6000}),refreshMarket(svc,query)}finally{setInstalling(!1)}}finally{actingRef.current=!1,setActing(!1)}})()},[dialog,state2.rows,state2.service,sel,acting,toast,refreshMarket,query,removeSelected,delistSelected]);useKeyboard((key4)=>{if(!props.focused||dialog.open())return;if(searching){if(key4.name==="escape"||key4.name==="esc"){setSearching(!1);return}if(key4.name==="backspace"){setQuery((q5)=>q5.slice(0,-1)),setSel(0);return}let seq=typeof key4.sequence==="string"?key4.sequence:"",ch=key4.raw&&key4.raw.length===1?key4.raw:seq.length===1?seq:key4.name.length===1&&!key4.ctrl&&!key4.meta?key4.name:"";if(ch>=" "){setQuery((q5)=>q5+ch),setSel(0);return}return}let plain=!key4.shift&&!key4.ctrl&&!key4.meta;if(key4.name==="tab")return setPane((p)=>p==="grid"?"detail":"grid");if(pane==="detail"){if(key4.name==="escape"||plain&&key4.name==="left"){setPane("grid");return}if(plain&&key4.name==="right"){cycle3(1);return}if(keys.match("list.activate",key4)){primary();return}if(keys.match("list.toggle",key4)){cycle3(1);return}if(keys.match("list.search",key4)){setPane("grid"),setSearching(!0);return}if(keys.match("list.refresh",key4)){loadMarket(query);return}return}let move=(by)=>setSel((p)=>{let n=Math.max(0,Math.min(state2.rows.length-1,p+by));return follow.opts.scrollTo?.(n),listFollow.opts.scrollTo?.(n),n});if(plain&&key4.name==="left"){move(-1);return}if(plain&&key4.name==="right"){move(1);return}if(plain&&key4.name==="up"){move(-1);return}if(plain&&key4.name==="down"){move(1);return}if(handleListKey(keys,key4,{count:state2.rows.length,setSel,page:listFollow.opts.page,scrollTo:(n)=>{follow.opts.scrollTo?.(n),listFollow.opts.scrollTo?.(n)},onActivate:primary,onToggle:()=>cycle3(1),onSearch:()=>setSearching(!0),onRefresh:()=>loadMarket(query),onDelete:()=>void removeSelected()}))return}),count("market:render");let titles=state2.rows.map((r)=>({key:r.entry.identityKey,name:r.entry.name,active:r.active})),cards=state2.rows.map((r)=>({key:r.entry.identityKey,name:r.entry.name,active:r.active,author:r.entry.author,status:stateLabel(r,!0),lines:posterLines(r.entry.poster)})),listW=titleWidth(`Catalog (${state2.rows.length})`,titles),showGrid=dims.width-listW-DETAIL>=EIKON_CARD;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(EikonTitleList,{title:`Catalog (${state2.rows.length})${searching?` Search: ${query}`:""}`,rows:titles,sel,focus:props.focused&&pane==="grid",follow:listFollow,width:listW,onSel:setSel,onUse:primary}),showGrid?$jsx(TabShell,{title:"Posters",grow:1,children:state2.error?$jsx("box",{padding:1,children:$jsxs("text",{fg:theme.error,wrapMode:"word",children:["Catalog unavailable: ",state2.error]})}):loading&&state2.rows.length===0?$jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:"Loading shared eikons\u2026"})}):$jsx(EikonCardGrid,{rows:cards,sel,follow,empty:$jsx("text",{fg:theme.textMuted,children:"No catalog eikons match. Press / to change search."}),onSel:setSel,onUse:primary})}):null,$jsx("box",{width:DETAIL,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:selected?`Details \u2014 ${selected.entry.name}`:"Details",focus:props.focused&&pane==="detail",grow:1,children:$jsx(MarketplaceDetail,{row:selected,loading,installing,onUse:()=>primary(),onFocus:()=>setPane("detail"),onState:setPreviewState,preview:preview2})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="grid"?"details":"catalog"],[keys.print("list.activate"),"actions"],[pane==="detail"?"\u2192/Space":"\u2191\u2193\u2190\u2192/Pg",pane==="detail"?"state":"select"],[keys.print("list.search"),searching?"typing search":"search"],[keys.print("list.refresh"),"reload"],["d","delete in modal"],["Space","preview"]]})]})}),posterLines=(poster2)=>{let lines3=poster2?poster2.split(`
4172
4172
  `):[];return lines3.length?lines3:["(no poster)"]},MarketplaceDetail=(props)=>{let theme=useTheme().theme,r=props.row;if(!r)return $jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:props.loading?"Loading shared eikons\u2026":"No catalog entry selected."})});let previewState=props.preview?.state??"idle",states=props.preview?.states??[previewState];return $jsxs("box",{flexDirection:"column",padding:1,onMouseDown:props.onFocus,children:[props.preview?$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:$jsx(AnimatedAvatar,{state:props.preview.state,eikon:props.preview.eikon},`${r.entry.identityKey}:${props.preview.state}`)}):null,$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:$jsxs("strong",{children:[r.active?"\u25CF ":"",r.entry.name]})})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.entry.author??"unknown"]})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:r.entry.description??"No description."})}),$jsx("box",{flexDirection:"row",flexWrap:"wrap",flexShrink:0,children:states.map((s,i)=>$jsx(FilterChip,{label:s,state:s===previewState?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.textMuted,onMouseDown:()=>props.onState(s)},s))}),$jsx(DetailRow2,{label:"Status",value:stateLabel(r),block:!0}),$jsx(DetailRow2,{label:"Trust",value:trustLabel(r),block:!0}),$jsx(DetailRow2,{label:"Source",value:sourceText(r),block:!0}),$jsx(DetailRow2,{label:"Compat",value:compatText(r)}),$jsx(DetailRow2,{label:"Digest",value:digest2(r)??"unknown",block:!0})]})},DetailRow2=(props)=>{let theme=useTheme().theme;if(props.block)return $jsx("box",{flexDirection:"column",minHeight:props.label==="Status"?2:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:[props.label,": ",props.value]})});return $jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[props.label,": ",props.value]})})},shortDigest=(value)=>{if(!value)return;let[algo,hash3]=value.includes(":")?value.split(":",2):[void 0,value];if(!hash3||hash3.length<=16)return value;return algo?`${algo}:${hash3.slice(0,12)}\u2026`:`${hash3.slice(0,12)}\u2026`},digest2=(row4)=>{let t2=row4.entry.trust;return shortDigest(t2.manifestDigest??t2.runtimeDigest??t2.digest)},trustLabel=(row4)=>{let t2=row4.trust==="mismatch"?"Mismatch":row4.trust==="verified"?"Verified":row4.trust==="unverified"?"Unverified":"Trust unknown";return row4.reason&&row4.trust==="mismatch"?`${t2}: ${row4.reason}`:t2},sourceText=(row4)=>row4.sourceIdentity??row4.lifecycle.source.packageUrl??row4.entry.sourceKey??row4.entry.packageUrl,compatText=(row4)=>row4.installState==="incompatible"?`Blocked: ${row4.reason??"requires newer Herm/eikon"}`:row4.installState==="active-name-conflict"?`Requires confirmation: ${row4.reason}`:"Compatible",stateLabel=(row4,short2=!1)=>{let base2=row4.installState==="active-name-conflict"?"active name conflict":row4.active?"active":row4.installed?"installed":"not installed";if(short2)return base2;let src3=row4.sourcePresent?" \xB7 source present":row4.sourceDownloadable?" \xB7 source downloadable":row4.sourceAvailable?" \xB7 source available":"",rm=row4.removable?" \xB7 removable":row4.installed?" \xB7 not removable":"";return`${base2}${src3}${rm}`};var EikonGroup=import_react111.memo((props)=>{let labels=SUB_TABS[EIKON_TAB],[target2,setTarget]=import_react111.useState(void 0);import_react111.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let edit2=import_react111.useCallback((name)=>{setTarget(name),props.setSub(2)},[props]),hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:[$jsx(Pane4,{visible:props.sub===0,children:$jsx(EikonGallery,{focused:!!props.focused&&props.sub===0,onEdit:edit2})}),$jsx(Pane4,{visible:props.sub===1,children:$jsx(EikonMarketplace,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane4,{visible:props.sub===2,children:$jsx(EikonStudio,{focused:!!props.focused&&props.sub===2,name:target2})})]})]})}),Pane4=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react112=__toESM(require_react_production(),1);var FRAME={cw:16,ch:8,tw:20,tv:8},TL=["\u2800\u2880\u28E4\u2824\u2884\u28C0\u2804\u2880\u28E0\u28E4\u28C4\u2864\u2844\u2840\u2800\u2800","\u2800\u28DC\u2841\u28A9\u28C8\u2842\u2880\u28CB\u28ED\u2809\u2808\u2888\u28EE\u28FB\u2851\u28F6","\u2800\u28B8\u2856\u28BF\u280F\u28E4\u28F6\u28FD\u28EB\u28B6\u28E2\u284C\u2839\u28E7\u284F\u283B","\u2800\u2808\u2864\u2892\u28E6\u28BB\u28FF\u28FF\u28FF\u28BF\u28C5\u2847\u28C6\u2849\u2802\u2880","\u2801\u28B8\u284F\u2818\u280B\u289E\u28B3\u28FF\u28FF\u28DF\u284D\u284D\u28E4\u2805\u2800\u28A8","\u2800\u2824\u28AF\u28C6\u28C0\u2819\u28A6\u28FF\u284B\u2880\u28DC\u2807\u28C1\u28D2\u28CA\u28C9","\u2800\u2880\u28F7\u28DD\u28FB\u28F6\u28F6\u2884\u280D\u2818\u2841\u2847\u28E7\u28E0\u28E4\u2862","\u2800\u2800\u2818\u288E\u28BF\u28EF\u2803\u2801\u2864\u28DA\u287C\u2800\u284F\u28F9\u28FF\u2869"],TR=["\u2800\u2800\u2880\u28A0\u28A0\u28E0\u28E4\u28C0\u2840\u2820\u28C0\u2860\u2824\u28E4\u28C0\u2800","\u28F6\u288A\u28DF\u28F5\u2841\u2801\u2809\u28ED\u28D9\u2800\u2890\u28C2\u284D\u2888\u28E3\u2800","\u281F\u28B9\u28FC\u280F\u28A1\u28D4\u28B6\u28DD\u28EF\u28F6\u28E4\u2839\u287F\u28B2\u2847\u2800","\u2840\u2801\u2889\u28F0\u28B8\u28E8\u287F\u28FF\u28FF\u28FF\u285F\u28F4\u2852\u28A4\u2801\u2800","\u2845\u2804\u2828\u28E4\u28A9\u28A9\u28FB\u28FF\u28FF\u285E\u2873\u2819\u2803\u28B9\u2847\u2800","\u28C9\u28D1\u28D2\u28C8\u2838\u28E3\u2840\u2899\u28FF\u2874\u280B\u28C0\u28F0\u287D\u2824\u2880","\u2884\u28E4\u28C4\u28F8\u28B8\u2888\u2803\u2829\u2860\u28F6\u28F6\u28DF\u28EB\u28FE\u2802\u2800","\u288D\u28FF\u289F\u28B9\u2800\u28A7\u28D2\u28A4\u2801\u2808\u28FD\u287F\u2871\u2807\u2800\u2800"],BL=["\u2800\u2800\u28C0\u28FF\u28FF\u285F\u2801\u2800\u283B\u28AC\u28F3\u2800\u28C7\u28F2\u28DF\u28BF","\u2800\u2890\u287A\u28DB\u286F\u28ED\u2837\u280C\u2882\u2880\u2842\u2847\u284F\u2819\u281B\u2827","\u2800\u2816\u287C\u2809\u2809\u28A0\u28F0\u2825\u28AD\u2818\u28DB\u28C4\u288B\u28C9\u28C9\u2859","\u2800\u28B8\u284C\u2880\u28E0\u28F5\u28FF\u28FF\u28FF\u28FF\u28E8\u2803\u2837\u2802\u2810\u288D","\u2800\u2800\u283B\u281D\u283F\u28F4\u28FF\u28FF\u287F\u28FF\u28DF\u28CB\u284F\u2841\u2804\u2818","\u2800\u28B8\u28F0\u28F6\u28C4\u283B\u283F\u28FF\u28F9\u2830\u281F\u2882\u28A0\u285F\u28C6\u28F4","\u2800\u28AA\u2849\u2838\u28FB\u2807\u2800\u285D\u28DB\u2880\u2840\u28D8\u285F\u2877\u28EB\u286F","\u2800\u2819\u283B\u282A\u281C\u2813\u2802\u2808\u281B\u2813\u281B\u2819\u281A\u2808\u2801\u2800"],BR2=["\u287F\u28FB\u28D6\u28F8\u2800\u28DE\u2861\u281F\u2880\u2804\u28BB\u28FF\u28FF\u28C0\u2800\u2800","\u2836\u281B\u280B\u28B9\u28B8\u2890\u2840\u2850\u2821\u283E\u28ED\u28BD\u28DB\u2897\u2842\u2800","\u288B\u28C9\u28C9\u2859\u28E0\u28DB\u2803\u286D\u282C\u28C6\u2844\u2809\u2829\u28A7\u2832\u2800","\u2869\u2802\u2810\u283E\u2818\u28C5\u28FF\u28FF\u28FF\u28FF\u28EE\u28C4\u2840\u28B1\u2847\u2800","\u2803\u2880\u2888\u28B3\u28D9\u28FB\u28FF\u28DF\u28FF\u28FF\u28E6\u283F\u282B\u281F\u2800\u2800","\u28E6\u28F0\u28BB\u2844\u2850\u283B\u2803\u28CF\u28FF\u283F\u281F\u28E0\u28F6\u28C6\u2847\u2800","\u28BD\u28DD\u28AF\u28BB\u28C3\u2880\u2840\u28DB\u28E9\u2800\u2838\u28DF\u2807\u2889\u2855\u2800","\u2801\u2800\u2801\u2813\u280B\u281B\u281A\u281B\u2801\u2810\u281A\u2823\u2807\u281F\u280B\u2800"],T2=["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2844\u28E2\u28F4\u28F6\u2836\u2816\u2832\u28CC\u2818\u2809\u2822\u285B\u28A1\u2834\u2832\u2836\u28F0\u2896\u28B4\u28E4","\u28FE\u28E5\u283F\u2800\u28E0\u28B0\u283F\u28BE\u2850\u283E\u283F\u2887\u2873\u28FF\u28D7\u2804\u2800\u2823\u28D1\u28F5","\u28BE\u285F\u2804\u2810\u28AD\u28CD\u2896\u2844\u2828\u28BB\u28EB\u283D\u287C\u287F\u28BD\u28A5\u2842\u2804\u283B\u287D","\u2813\u287B\u28B6\u28C4\u2848\u2818\u282D\u281A\u280D\u28BB\u2849\u280B\u280B\u282D\u2803\u2803\u2861\u28F6\u28DF\u28BE","\u2801\u2804\u2809\u2809\u281A\u2824\u2824\u282C\u281F\u2830\u2827\u280A\u282F\u2834\u2824\u2813\u281B\u2809\u2810\u2822","\u28DB\u28DB\u285F\u28DB\u285B\u28DB\u28DB\u289B\u28DB\u28DB\u285B\u28DB\u28DB\u289B\u28FB\u28FB\u28DF\u281B\u28FB\u28BB","\u28CA\u28C9\u28C9\u28DB\u28CB\u28D9\u28CB\u28FC\u28F7\u28E5\u28EF\u28FA\u28CB\u28F5\u28F7\u28ED\u28D9\u28D1\u28FB\u28FD"],B2=["\u28FF\u28BF\u28FF\u28FF\u28BF\u28FF\u287F\u287F\u28FF\u28FF\u283F\u28FF\u28BF\u287F\u28FF\u28FF\u287F\u28FF\u287F\u28BF","\u28C3\u28DB\u28C8\u28D3\u28DA\u28DA\u28C3\u28D9\u28DB\u28C9\u28DB\u28DB\u28C1\u28DB\u28D9\u28D9\u28CB\u28D8\u28C9\u28D9","\u2820\u2884\u2884\u28C0\u2864\u28E4\u2810\u28E0\u2884\u28A0\u2844\u2864\u28C4\u2800\u2864\u2884\u28C0\u2840\u2880\u2880","\u28F1\u282C\u282B\u2811\u2881\u28E0\u28A0\u286B\u28E1\u28E0\u28E4\u28C9\u2885\u2884\u28C4\u2809\u283B\u2850\u28A5\u28CC","\u2894\u28C8\u2800\u28B0\u2841\u28B6\u28FF\u28FF\u28DF\u28FF\u28C3\u285B\u2815\u280D\u28E6\u28C3\u2844\u2802\u28F9\u2862","\u287F\u288F\u2884\u2800\u2803\u28EB\u28FF\u289C\u28A9\u28F6\u28E6\u2809\u2876\u28FE\u2856\u281B\u2800\u28E0\u285B\u287F","\u283C\u28BE\u283F\u28F5\u28D6\u28D8\u2834\u2803\u2808\u2886\u2880\u2800\u2873\u2824\u28C2\u28F2\u28FE\u282F\u281A\u280F","\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u280B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800"],L2=["\u2800\u2800\u2890\u289F\u28FE\u283F\u282E\u2836\u2877\u28EA\u283E\u2802\u2857\u28AD\u28BF\u28B9","\u2800\u2800\u28E8\u2855\u2809\u2861\u2824\u28C1\u284C\u282A\u28A7\u2801\u2847\u28F0\u28FF\u28BC","\u2800\u2800\u2839\u2843\u28BE\u28D5\u28F7\u2866\u28D3\u2840\u2849\u2846\u284F\u28F6\u2863\u28FB","\u2800\u28B0\u2876\u28AC\u28ED\u285C\u28FF\u28FF\u28EF\u2888\u2893\u2801\u284F\u28DA\u287E\u28FF","\u2800\u2818\u285B\u288A\u28D9\u2823\u2887\u28AF\u28FF\u2828\u286D\u2841\u2867\u28BC\u28F2\u28FF","\u2800\u2800\u28B1\u2849\u28BF\u2847\u2824\u28DD\u2844\u2800\u2841\u2801\u284F\u28F6\u2896\u28BF","\u2800\u2800\u28B0\u28E7\u2840\u2813\u2813\u2809\u2881\u28F4\u284D\u2800\u2847\u283A\u283D\u28BA","\u2800\u2800\u2828\u283A\u28FD\u28F7\u28E6\u2874\u285A\u2803\u2880\u2800\u2847\u287E\u28FF\u28B9"],R=["\u284F\u287F\u286D\u28BA\u2880\u2837\u289D\u28BE\u2836\u2835\u283F\u28F7\u287B\u2842\u2800\u2800","\u2867\u28FF\u28C6\u28B8\u2800\u287C\u2815\u28A1\u28C0\u2824\u288C\u2809\u28AA\u28C5\u2801\u2800","\u28DF\u289C\u28F6\u28B9\u28B0\u2889\u2880\u28DA\u28B4\u28FE\u28EA\u2877\u2898\u280F\u2800\u2800","\u28FF\u28B7\u285B\u28B9\u2808\u285A\u2841\u28FD\u28FF\u28FF\u28A3\u28ED\u2865\u28B6\u2846\u2800","\u28FF\u28D6\u2867\u28BC\u2888\u28AD\u2805\u28FF\u287D\u2878\u2858\u28CB\u2851\u289B\u2803\u2800","\u287F\u2872\u28F6\u28B9\u2808\u2888\u2800\u28A0\u28EB\u2824\u28B8\u287F\u2889\u2846\u2800\u2800","\u2857\u282F\u2817\u28B8\u2800\u28A9\u28E6\u2848\u2809\u281A\u281A\u2880\u28FC\u2846\u2800\u2800","\u284F\u28FF\u28AF\u28B8\u2800\u2880\u2818\u2893\u28A6\u28B6\u28FE\u28EF\u2817\u2805\u2800\u2800"];function frame(w2,h2){let{cw,ch,tw,tv}=FRAME,mw=w2-2*cw,mh=h2-2*ch,inner={x:cw,y:ch,w:Math.max(0,mw),h:Math.max(0,mh)};if(mw<4||mh<2)return{lines:[],inner};let repH=(p,span2)=>p.map((l2)=>l2.repeat(Math.ceil(span2/tw)).slice(0,span2)),repV=(p,span2)=>Array.from({length:span2},(_2,i)=>p[i%tv]),t2=repH(T2,mw),b2=repH(B2,mw),l=repV(L2,mh),r=repV(R,mh),mid2=" ".repeat(mw),out=[];for(let i=0;i<ch;i++)out.push(TL[i]+t2[i]+TR[i]);for(let i=0;i<mh;i++)out.push(l[i]+mid2+r[i]);for(let i=0;i<ch;i++)out.push(BL[i]+b2[i]+BR2[i]);return{lines:out,inner}}import{readFileSync as readFileSync17}from"fs";import{join as join20}from"path";var FALLBACK=["`@file:path/to/file.py` injects file contents directly into your message.","`/title <name>` names the session \u2014 resume it later from the Sessions tab.","Ctrl+G opens $EDITOR seeded with the composer contents.","Ctrl+Z suspends to the shell; `fg` resumes.","Pasting 5+ lines collapses to a `[Pasted #N \u2026]` placeholder.","Click a user message in the transcript to rewind to that point."],HL=/(\/[a-z][\w-]*|@[\w:./-]+|(?:Ctrl|Alt|Shift)\+\S+|`[^`]+`|"[^"]+")/g;function splitTip(tip2){let out=[],i=0;for(let m2 of tip2.matchAll(HL)){let j2=m2.index;if(j2>i)out.push({t:tip2.slice(i,j2),hl:!1});out.push({t:m2[0].replace(/^`|`$/g,""),hl:!0}),i=j2+m2[0].length}if(i<tip2.length)out.push({t:tip2.slice(i),hl:!1});return out}var cache5=null;function loadTips(){if(cache5)return cache5;try{let body=readFileSync17(join20(hermesAgentRoot(),"hermes_cli","tips.py"),"utf8").split(/^TIPS\s*=\s*\[/m)[1]?.split(/^\]/m)[0]??"",tips=[];for(let line4 of body.split(`
@@ -4193,14 +4193,14 @@ ${r.skipped.slice(0,8).join(", ")}${r.skipped.length>8?", \u2026":""}`:""}`,yes:
4193
4193
  `;writeSync(1,banner)}process.exit(0)}var exports_stash={};__export(exports_stash,{push:()=>push2,pop:()=>pop2,drop:()=>drop,all:()=>all,Stash:()=>exports_stash});import{join as join25}from"path";import{existsSync as existsSync26,readFileSync as readFileSync20,writeFileSync as writeFileSync9,mkdirSync as mkdirSync7}from"fs";var MAX=50,file2=()=>join25(configDir(),"stash.jsonl");function load5(){if(!existsSync26(file2()))return[];return readFileSync20(file2(),"utf-8").split(`
4194
4194
  `).filter(Boolean).map((l)=>JSON.parse(l)).slice(-MAX)}function save3(list3){mkdirSync7(configDir(),{recursive:!0}),writeFileSync9(file2(),list3.map((e)=>JSON.stringify(e)).join(`
4195
4195
  `)+`
4196
- `,"utf-8")}function push2(text4){let list3=load5(),at=Math.max(Date.now(),(list3[list3.length-1]?.at??0)+1);if(list3.push({text:text4,at}),list3.length>MAX)list3.shift();return save3(list3),list3.length}function pop2(){let list3=load5(),e=list3.pop();if(!e)return null;return save3(list3),e}function all(){return load5().reverse()}function drop(at){save3(load5().filter((e)=>e.at!==at))}var import_react127=__toESM(require_react_production(),1);var ctx=import_react127.createContext(null),BackgroundProvider=({children:children2})=>{let[set2,setSet]=import_react127.useState(()=>new Set),register2=import_react127.useCallback((id)=>{if(!id)return;setSet((prev)=>prev.has(id)?prev:new Set(prev).add(id))},[]),unregister=import_react127.useCallback((id)=>{setSet((prev)=>{if(!prev.has(id))return prev;let next2=new Set(prev);return next2.delete(id),next2})},[]),ids3=import_react127.useMemo(()=>Array.from(set2),[set2]),value=import_react127.useMemo(()=>({count:ids3.length,ids:ids3,register:register2,unregister}),[ids3,register2,unregister]);return $jsx(ctx.Provider,{value,children:children2})},useBackground=makeUse(ctx,"useBackground");var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"load.live":return{...initialTurn,messages:a.messages,streaming:a.streaming,hasContent:a.streaming&&Boolean(joinText(a.messages.at(-1)?.parts??[]))};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(sanitize(a.text))]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":{let chunk=sanitize(a.chunk);if(!chunk)return state2;return{...state2,hasContent:!0,toolActive:!1,messages:appendText(state2.messages,chunk)}}case"message.complete":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:finalize(state2.messages,a.text!=null?sanitize(a.text):void 0,a.usage)};case"tool.start":{let preview2=sanitize(a.preview),args=sanitize(a.args),raw2=args||preview2,json2=raw2&&/^\s*\{/.test(raw2),part={type:"tool",id:a.id,name:a.name,args:json2?raw2:"",status:"running",startedAt:Date.now(),preview:preview2||void 0,verboseArgs:args||void 0};return{...state2,toolActive:!0,hasContent:!1,messages:appendPart(state2.messages,part,!0)}}case"tool.progress":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:sanitize(a.preview)||p.preview}))};case"tool.generating":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:p.preview??"generating\u2026"}))};case"tool.complete":{let summary2=sanitize(a.summary),error=sanitize(a.error),diff=sanitize(a.inline_diff),result=sanitize(a.result);return{...state2,toolActive:!1,messages:updateToolById(state2.messages,a.id,(p)=>({...p,status:a.error?"error":"done",duration:a.duration??(p.startedAt?Date.now()-p.startedAt:void 0),preview:summary2||diff||p.preview,result:error||summary2||void 0,verboseResult:result||void 0,diff:diff||void 0}))}}case"thinking":return{...state2,messages:upsertThinking(state2.messages,sanitize(a.text),a.final,a.verbose)};case"subagent":return{...state2,messages:renderSubagent(state2.messages,a.event,a.payload)};case"prompt":{let part={type:"prompt",id:a.id,variant:a.req.variant,req:a.req};return{...state2,messages:appendPart(state2.messages,part,!0)}}case"prompt.answered":return{...state2,messages:updatePrompt(state2.messages,a.id,(p)=>({...p,answered:{label:a.label,ok:a.ok,at:Date.now()}}))};case"error":{let msg=systemMessage(`Error: ${sanitize(a.text)}`);if(a.fatal===!1)return{...state2,messages:[...state2.messages,msg]};return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:[...state2.messages,msg]}}case"interrupt.notice":{let clean5=sanitize(a.text),last3=state2.messages[state2.messages.length-1];if(last3?.role==="system"&&last3.parts[0]?.type==="text"&&last3.parts[0].content.includes(clean5))return state2;return{...state2,messages:[...state2.messages,systemMessage(clean5)]}}}}function userMessage(text4){return{id:mid(),role:"user",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function systemMessage(text4){return{id:mid(),role:"system",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function flatten3(text4){if(typeof text4==="string")return text4;if(!Array.isArray(text4))return"";let out=[];for(let p of text4)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")out.push(p.text);return out.join(`
4197
- `)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:sanitize(flatten3(r.text))})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,chunk){return withLastAssistant(messages,(m2)=>{let last3=m2.parts[m2.parts.length-1];if(last3?.type==="text"&&last3.streaming){let part={...last3,content:last3.content+chunk};return{...m2,parts:[...m2.parts.slice(0,-1),part]}}return{...m2,parts:[...m2.parts,{type:"text",key:pid(),content:chunk,streaming:!0}]}},()=>assistant([{type:"text",key:pid(),content:chunk,streaming:!0}]))}function appendPart(messages,part,close){return withLastAssistant(messages,(m2)=>({...m2,parts:[...close?seal(m2.parts):m2.parts,part]}),()=>assistant([part]))}function finalize(messages,final,usage){let last3=messages[messages.length-1];if(last3?.role==="assistant"){let tail=last3.parts[last3.parts.length-1],dup=final&&last3.parts.some((p)=>p.type==="text"&&sameText(p.content,final)),text4=tail?.type==="text"&&final&&sameText(tail.content,final)?tail.content:final,parts2=tail?.type==="text"&&tail.streaming?[...last3.parts.slice(0,-1),{...tail,content:text4||tail.content,streaming:!1}]:final&&!dup&&!sameText(joinText(last3.parts),final)?[...last3.parts,{type:"text",content:final,streaming:!1}]:seal(last3.parts);return[...messages.slice(0,-1),{...last3,parts:parts2,usage}]}if(!final)return messages;return[...messages,{...assistant([{type:"text",content:final,streaming:!1}]),usage}]}function joinText(parts2){return parts2.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function sameText(a,b2){return a.trim()===b2.trim()}function updateRunningTool(messages,name,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;for(let i=last3.parts.length-1;i>=0;i--){let p=last3.parts[i];if(p.type!=="tool"||p.status!=="running")continue;if(name&&p.name!==name)continue;let parts2=[...last3.parts];return parts2[i]=fn(p),[...messages.slice(0,-1),{...last3,parts:parts2}]}return messages}function updateToolById(messages,id,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;let parts2=last3.parts.map((p)=>p.type==="tool"&&p.id===id?fn(p):p);return[...messages.slice(0,-1),{...last3,parts:parts2}]}function updatePrompt(messages,id,fn){return messages.map((m2)=>{if(m2.role!=="assistant")return m2;if(!m2.parts.some((p)=>p.type==="prompt"&&p.id===id))return m2;return{...m2,parts:m2.parts.map((p)=>p.type==="prompt"&&p.id===id?fn(p):p)}})}function upsertThinking(messages,text4,final,verbose2){return withLastAssistant(messages,(m2)=>{let idx=m2.parts.findIndex((p)=>p.type==="thinking");if(idx>=0){let prev=m2.parts[idx],content=final?prev.content.trim()||text4:prev.content+text4,parts2=[...m2.parts];return parts2[idx]={...prev,content,streaming:!final,verbose:prev.verbose||verbose2||void 0},{...m2,parts:parts2}}return{...m2,parts:[{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2},...m2.parts]}},()=>assistant([{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2}]))}function renderSubagent(messages,event,p){let id=p.subagent_id?`sub-${p.subagent_id}`:`sub-${p.task_index}`;if(event==="start"){let goal=sanitize(p.goal),part={type:"tool",id,name:"delegate_task",args:"",status:"running",startedAt:Date.now(),preview:goal||void 0,goal:goal||void 0,depth:p.depth??0,trail:[]};return appendPart(messages,part,!0)}if(event==="tool"&&p.tool_name){let tname=sanitize(p.tool_name),tprev=sanitize(p.tool_preview);return updateToolById(messages,id,(t2)=>({...t2,trail:[...t2.trail??[],{name:tname,preview:tprev||void 0}],preview:tprev?`${tname}: ${tprev}`:tname}))}if(event==="complete"){let tokens3=(p.input_tokens??0)+(p.output_tokens??0),extra=tokens3?` \xB7 ${(tokens3/1000).toFixed(1)}k tok`:"",summary2=sanitize(p.summary);return updateToolById(messages,id,(t2)=>({...t2,status:p.status==="failed"||p.status==="error"||p.status==="timeout"||p.status==="interrupted"?"error":"done",duration:p.duration_seconds?p.duration_seconds*1000:t2.startedAt?Date.now()-t2.startedAt:void 0,result:summary2?summary2+extra:void 0,preview:t2.goal??t2.preview}))}return updateToolById(messages,id,(t2)=>({...t2,preview:sanitize(p.text)||t2.preview}))}function useSlash(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),themeCtx=useTheme(),cmd=useCommand(),renderer=useRenderer(),cfg=useHome("config"),bg2=useBackground(),ctx2=import_react128.useRef(c);ctx2.current=c;let gate=import_react128.useRef(cfg);gate.current=cfg;let destructive=import_react128.useCallback((arg,opts,action)=>{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",bypass=!(gate.current?.approvals?.destructive_slash_confirm??!0)||process.env.HERMES_TUI_NO_CONFIRM==="1",persist2=a==="always",fire=()=>{if(persist2)Promise.resolve().then(() => (init_lane(),exports_lane)).then(({writeConfig:writeConfig2})=>writeConfig2(gw,[{key:"approvals.destructive_slash_confirm",to:!1}]).then((r)=>{if(r.failed.length){toast.show({variant:"warning",message:`couldn't persist: ${r.failed[0].err}`});return}home2.invalidate("config"),toast.show({variant:"success",message:`${opts.yes} \xB7 future runs silent`})}).catch((e)=>toast.show({variant:"error",message:e.message})));action()};if(skip||bypass)return fire();openConfirm(dialog,{title:opts.title,body:opts.body,yes:opts.yes,danger:!0}).then((ok)=>{if(ok)fire()})},[gw,dialog,toast]),pickEikon=import_react128.useCallback(()=>openEikonPicker(dialog,(n)=>set("eikon",n)),[dialog]),applyTitle=import_react128.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{ctx2.current.setTitle(r.title),ctx2.current.dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),runCompress=import_react128.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await ctx2.current.session.compress();if(!r)return;if(r.info)ctx2.current.setInfo(r.info);if(ctx2.current.setUsage((u3)=>{let base2=r.usage??u3,max=r.usage?.context_max??u3?.context_max;if(typeof r.after_tokens!=="number"||typeof max!=="number")return base2;return{...base2??{input:0,output:0,total:0},context_used:r.after_tokens,context_max:max}}),!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines3=[s.headline,s.token_line,s.note].filter(Boolean).join(`
4196
+ `,"utf-8")}function push2(text4){let list3=load5(),at=Math.max(Date.now(),(list3[list3.length-1]?.at??0)+1);if(list3.push({text:text4,at}),list3.length>MAX)list3.shift();return save3(list3),list3.length}function pop2(){let list3=load5(),e=list3.pop();if(!e)return null;return save3(list3),e}function all(){return load5().reverse()}function drop(at){save3(load5().filter((e)=>e.at!==at))}var import_react127=__toESM(require_react_production(),1);var ctx=import_react127.createContext(null),BackgroundProvider=({children:children2})=>{let[set2,setSet]=import_react127.useState(()=>new Set),register2=import_react127.useCallback((id)=>{if(!id)return;setSet((prev)=>prev.has(id)?prev:new Set(prev).add(id))},[]),unregister=import_react127.useCallback((id)=>{setSet((prev)=>{if(!prev.has(id))return prev;let next2=new Set(prev);return next2.delete(id),next2})},[]),ids3=import_react127.useMemo(()=>Array.from(set2),[set2]),value=import_react127.useMemo(()=>({count:ids3.length,ids:ids3,register:register2,unregister}),[ids3,register2,unregister]);return $jsx(ctx.Provider,{value,children:children2})},useBackground=makeUse(ctx,"useBackground");var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"load.live":return{...initialTurn,messages:a.messages,streaming:a.streaming,hasContent:a.streaming&&Boolean(joinText(a.messages.at(-1)?.parts??[]))};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(sanitize(a.text))]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":{let chunk=sanitize(a.chunk);if(!chunk)return state2;return{...state2,hasContent:!0,toolActive:!1,messages:appendText(state2.messages,chunk)}}case"message.complete":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:finalize(state2.messages,a.text!=null?sanitize(a.text):void 0,a.usage)};case"tool.start":{let preview2=sanitize(a.preview),args=sanitize(a.args),raw2=args||preview2,json2=raw2&&/^\s*\{/.test(raw2),part={type:"tool",id:a.id,name:a.name,args:json2?raw2:"",status:"running",startedAt:Date.now(),preview:preview2||void 0,verboseArgs:args||void 0};return{...state2,toolActive:!0,hasContent:!1,messages:appendPart(state2.messages,part,!0)}}case"tool.progress":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:sanitize(a.preview)||p.preview}))};case"tool.generating":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:p.preview??"generating\u2026"}))};case"tool.complete":{let summary2=sanitize(a.summary),error=sanitize(a.error),diff=sanitize(a.inline_diff),result=sanitize(a.result);return{...state2,toolActive:!1,messages:updateToolById(state2.messages,a.id,(p)=>({...p,status:a.error?"error":"done",duration:a.duration??(p.startedAt?Date.now()-p.startedAt:void 0),preview:summary2||diff||p.preview,result:error||summary2||void 0,verboseResult:result||void 0,diff:diff||void 0}))}}case"thinking":return{...state2,messages:upsertThinking(state2.messages,sanitize(a.text),a.final,a.verbose)};case"subagent":return{...state2,messages:renderSubagent(state2.messages,a.event,a.payload)};case"prompt":{let part={type:"prompt",id:a.id,variant:a.req.variant,req:a.req};return{...state2,messages:appendPart(state2.messages,part,!0)}}case"prompt.answered":return{...state2,messages:updatePrompt(state2.messages,a.id,(p)=>({...p,answered:{label:a.label,ok:a.ok,at:Date.now(),question:promptQuestion(p.req)}}))};case"error":{let msg=systemMessage(`Error: ${sanitize(a.text)}`);if(a.fatal===!1)return{...state2,messages:[...state2.messages,msg]};return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:[...state2.messages,msg]}}case"interrupt.notice":{let clean5=sanitize(a.text),last3=state2.messages[state2.messages.length-1];if(last3?.role==="system"&&last3.parts[0]?.type==="text"&&last3.parts[0].content.includes(clean5))return state2;return{...state2,messages:[...state2.messages,systemMessage(clean5)]}}}}function userMessage(text4){return{id:mid(),role:"user",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function systemMessage(text4){return{id:mid(),role:"system",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function flatten3(text4){if(typeof text4==="string")return text4;if(!Array.isArray(text4))return"";let out=[];for(let p of text4)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")out.push(p.text);return out.join(`
4197
+ `)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:sanitize(flatten3(r.text))})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,chunk){return withLastAssistant(messages,(m2)=>{let last3=m2.parts[m2.parts.length-1];if(last3?.type==="text"&&last3.streaming){let part={...last3,content:last3.content+chunk};return{...m2,parts:[...m2.parts.slice(0,-1),part]}}return{...m2,parts:[...m2.parts,{type:"text",key:pid(),content:chunk,streaming:!0}]}},()=>assistant([{type:"text",key:pid(),content:chunk,streaming:!0}]))}function appendPart(messages,part,close){return withLastAssistant(messages,(m2)=>({...m2,parts:[...close?seal(m2.parts):m2.parts,part]}),()=>assistant([part]))}function finalize(messages,final,usage){let last3=messages[messages.length-1];if(last3?.role==="assistant"){let tail=last3.parts[last3.parts.length-1],dup=final&&last3.parts.some((p)=>p.type==="text"&&sameText(p.content,final)),text4=tail?.type==="text"&&final&&sameText(tail.content,final)?tail.content:final,parts2=tail?.type==="text"&&tail.streaming?[...last3.parts.slice(0,-1),{...tail,content:text4||tail.content,streaming:!1}]:final&&!dup&&!sameText(joinText(last3.parts),final)?[...last3.parts,{type:"text",content:final,streaming:!1}]:seal(last3.parts);return[...messages.slice(0,-1),{...last3,parts:parts2,usage}]}if(!final)return messages;return[...messages,{...assistant([{type:"text",content:final,streaming:!1}]),usage}]}function joinText(parts2){return parts2.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function sameText(a,b2){return a.trim()===b2.trim()}function updateRunningTool(messages,name,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;for(let i=last3.parts.length-1;i>=0;i--){let p=last3.parts[i];if(p.type!=="tool"||p.status!=="running")continue;if(name&&p.name!==name)continue;let parts2=[...last3.parts];return parts2[i]=fn(p),[...messages.slice(0,-1),{...last3,parts:parts2}]}return messages}function updateToolById(messages,id,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;let parts2=last3.parts.map((p)=>p.type==="tool"&&p.id===id?fn(p):p);return[...messages.slice(0,-1),{...last3,parts:parts2}]}function updatePrompt(messages,id,fn){return messages.map((m2)=>{if(m2.role!=="assistant")return m2;if(!m2.parts.some((p)=>p.type==="prompt"&&p.id===id))return m2;return{...m2,parts:m2.parts.map((p)=>p.type==="prompt"&&p.id===id?fn(p):p)}})}function promptQuestion(req){if(req.variant==="clarify")return req.question;if(req.variant==="approval")return req.description||"Shell command";if(req.variant==="sudo")return"Sudo required";return req.env_var?`Secret: ${req.env_var}`:"Secret required"}function upsertThinking(messages,text4,final,verbose2){return withLastAssistant(messages,(m2)=>{let idx=m2.parts.findIndex((p)=>p.type==="thinking");if(idx>=0){let prev=m2.parts[idx],content=final?prev.content.trim()||text4:prev.content+text4,parts2=[...m2.parts];return parts2[idx]={...prev,content,streaming:!final,verbose:prev.verbose||verbose2||void 0},{...m2,parts:parts2}}return{...m2,parts:[{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2},...m2.parts]}},()=>assistant([{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2}]))}function renderSubagent(messages,event,p){let id=p.subagent_id?`sub-${p.subagent_id}`:`sub-${p.task_index}`;if(event==="start"){let goal=sanitize(p.goal),part={type:"tool",id,name:"delegate_task",args:"",status:"running",startedAt:Date.now(),preview:goal||void 0,goal:goal||void 0,depth:p.depth??0,trail:[]};return appendPart(messages,part,!0)}if(event==="tool"&&p.tool_name){let tname=sanitize(p.tool_name),tprev=sanitize(p.tool_preview);return updateToolById(messages,id,(t2)=>({...t2,trail:[...t2.trail??[],{name:tname,preview:tprev||void 0}],preview:tprev?`${tname}: ${tprev}`:tname}))}if(event==="complete"){let tokens3=(p.input_tokens??0)+(p.output_tokens??0),extra=tokens3?` \xB7 ${(tokens3/1000).toFixed(1)}k tok`:"",summary2=sanitize(p.summary);return updateToolById(messages,id,(t2)=>({...t2,status:p.status==="failed"||p.status==="error"||p.status==="timeout"||p.status==="interrupted"?"error":"done",duration:p.duration_seconds?p.duration_seconds*1000:t2.startedAt?Date.now()-t2.startedAt:void 0,result:summary2?summary2+extra:void 0,preview:t2.goal??t2.preview}))}return updateToolById(messages,id,(t2)=>({...t2,preview:sanitize(p.text)||t2.preview}))}function useSlash(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),themeCtx=useTheme(),cmd=useCommand(),renderer=useRenderer(),cfg=useHome("config"),bg2=useBackground(),ctx2=import_react128.useRef(c);ctx2.current=c;let gate=import_react128.useRef(cfg);gate.current=cfg;let destructive=import_react128.useCallback((arg,opts,action)=>{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",bypass=!(gate.current?.approvals?.destructive_slash_confirm??!0)||process.env.HERMES_TUI_NO_CONFIRM==="1",persist2=a==="always",fire=()=>{if(persist2)Promise.resolve().then(() => (init_lane(),exports_lane)).then(({writeConfig:writeConfig2})=>writeConfig2(gw,[{key:"approvals.destructive_slash_confirm",to:!1}]).then((r)=>{if(r.failed.length){toast.show({variant:"warning",message:`couldn't persist: ${r.failed[0].err}`});return}home2.invalidate("config"),toast.show({variant:"success",message:`${opts.yes} \xB7 future runs silent`})}).catch((e)=>toast.show({variant:"error",message:e.message})));action()};if(skip||bypass)return fire();openConfirm(dialog,{title:opts.title,body:opts.body,yes:opts.yes,danger:!0}).then((ok)=>{if(ok)fire()})},[gw,dialog,toast]),pickEikon=import_react128.useCallback(()=>openEikonPicker(dialog,(n)=>set("eikon",n)),[dialog]),applyTitle=import_react128.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{ctx2.current.setTitle(r.title),ctx2.current.dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),runCompress=import_react128.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await ctx2.current.session.compress();if(!r)return;if(r.info)ctx2.current.setInfo(r.info);if(ctx2.current.setUsage((u3)=>{let base2=r.usage??u3,max=r.usage?.context_max??u3?.context_max;if(typeof r.after_tokens!=="number"||typeof max!=="number")return base2;return{...base2??{input:0,output:0,total:0},context_used:r.after_tokens,context_max:max}}),!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines3=[s.headline,s.token_line,s.note].filter(Boolean).join(`
4198
4198
  `);if(lines3)ctx2.current.dispatch({kind:"system",text:lines3});toast.show({variant:"success",message:s.headline??`Compressed ${r.before_messages??0}\u2192${r.after_messages??0} messages`})},[toast]),branch2=import_react128.useCallback((name)=>{let x2=ctx2.current;x2.session.branch(name?.trim()||void 0).then((id)=>id?void x2.activateSession(id):toast.show({variant:"error",message:"branch failed"}))},[toast]),run=import_react128.useCallback((c2,arg="")=>{let x2=ctx2.current;if(c2.target==="local")switch(c2.name){case"clear":destructive(arg,{title:"Clear session?",body:"Discards the in-memory transcript. Your session on disk is unchanged; reload to restore.",yes:"clear"},()=>x2.dispatch({kind:"reset"}));return;case"new":destructive(arg,{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{x2.newSession()});return;case"theme":{let mode=arg.trim().toLowerCase();if(!mode){openThemePicker(dialog,themeCtx);return}if(mode==="light"||mode==="dark"){themeCtx.setMode(mode),x2.dispatch({kind:"system",text:`theme mode \u2192 ${mode}`});return}toast.show({variant:"error",message:"usage: /theme [light|dark]"});return}case"help":dialog.replace($jsx(HelpDialog,{}));return;case"keys":openKeys(dialog);return;case"logs":openLogs(dialog);return;case"title":if(arg){applyTitle(arg);return}openTextPrompt(dialog,{title:"Session Title",initial:x2.title}).then((v2)=>{if(v2)applyTitle(v2)});return;case"rollback":openRollback(dialog,gw,toast);return;case"history":openHistory(dialog,gw);return;case"status":openStatus(dialog,x2.info,x2.sid);return;case"usage":openUsage(dialog,gw);return;case"profile":openProfile(dialog);return;case"chafa":if(!arg.trim()){toast.show({variant:"info",message:"usage: /chafa <path>"});return}openChafa(dialog,arg.trim());return;case"splash":x2.summoned.current=!0,x2.setSplash(!0);return;case"skin":{let name=arg.trim();if(!name){x2.dispatch({kind:"system",text:`skin: ${x2.skin.skin?.name??"\u2014"}
4199
4199
  ${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikon",void 0),x2.dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){x2.switchSession(arg);return}x2.goTo(TAB_SLASH.sessions.tab,TAB_SLASH.sessions.sub);return;case"branch":branch2(arg);return;case"compress":runCompress();return;case"undo":destructive(arg,{title:"Undo last turn?",body:"Pops the last user + assistant pair from the transcript. /redo in this session to restore.",yes:"undo"},()=>{let msgs=x2.turnRef.current.messages,at=msgs.map((m2)=>m2.role).lastIndexOf("user");if(at>=0)x2.undone.current.push(msgs.slice(at));x2.session.undo().then(()=>gw.request("session.history").then((r)=>x2.dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}))});return;case"redo":{let head=x2.undone.current.pop()?.find((m2)=>m2.role==="user");if(!head){toast.show({variant:"info",message:"nothing to redo"});return}x2.sendRef.current(text(head));return}case"retry":{let last3=[...x2.turnRef.current.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}x2.rewind(last3).then(()=>x2.sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});x2.dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"yolo":gw.request("config.set",{key:"yolo"}).then((r)=>{if(r.info)x2.setInfo(r.info),x2.setUsage(r.info.usage);else x2.setInfo({...x2.info??{},yolo:!x2.info?.yolo});if(toast.show({variant:"success",message:`yolo ${r.value??"toggled"}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,x2.sid,x2.title,gw);return;case"queue":if(!arg){x2.dispatch({kind:"system",text:`${x2.queueRef.current.length} queued`});return}x2.setQueue((q5)=>[...q5,arg]);return;case"stash":{let comp=x2.composer.current;if(arg==="pop"){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});comp?.set(e.text),x2.setFocusRegion("input");return}if(arg==="list"){let list3=exports_stash.all();if(list3.length===0)return toast.show({variant:"info",message:"stash empty"});dialog.replace($jsx(DialogSelect,{title:"Stashed prompts",filterable:list3.length>6,options:list3.map((e)=>({title:trunc5(e.text.replace(/\n/g," \u23CE "),50),value:String(e.at),hint:ago(e.at)})),onSelect:(o)=>{let e=list3.find((s)=>String(s.at)===o.value);if(e)exports_stash.drop(e.at),comp?.set(e.text),x2.setFocusRegion("input");dialog.clear()}}));return}let text4=arg||comp?.value().trim()||"";if(!text4)return toast.show({variant:"info",message:"nothing to stash \u2014 /stash list"});let n=exports_stash.push(text4);if(!arg)comp?.set("");toast.show({variant:"info",message:`stashed (${n}) \u2014 /stash pop to restore`});return}case"copy":{let all2=x2.turnRef.current.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all2.length):all2.length,m2=all2[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy2(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":x2.attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?x2.setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>{if(r.task_id)bg2.register(r.task_id);toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":x2.voiceToggle((arg||"status").toLowerCase(),x2.sid).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"browser":{let parts2=arg.trim().split(/\s+/),sub2=parts2[0]?.toLowerCase()||"connect",url2=parts2[1];if(!["connect","disconnect","status"].includes(sub2)){toast.show({variant:"error",message:"usage: /browser [connect|disconnect|status] [url]"});return}let payload={action:sub2};if(sub2==="connect"&&url2)payload.url=url2;gw.request("browser.manage",payload).then((r)=>{for(let m2 of r.messages??[])x2.dispatch({kind:"system",text:m2});if(r.connected)x2.dispatch({kind:"system",text:`Browser connected${r.url?` \u2192 ${r.url}`:""}`});else if(sub2==="disconnect")x2.dispatch({kind:"system",text:"Browser disconnected"});else if(sub2==="status")x2.dispatch({kind:"system",text:r.url??"No browser connected"})}).catch((e)=>toast.show({variant:"error",message:`browser: ${e.message}`}));return}case"compact":case"setup":x2.dispatch({kind:"system",text:`/${c2.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text4)=>gw.request("session.steer",{text:text4}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text4)=>{if(text4)fire(text4)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{x2.dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c2.target!=="gateway"||!x2.capabilities.canDispatchGatewayCommand)return;let jump=TAB_SLASH[c2.name];if(jump!==void 0&&!arg){x2.goTo(jump.tab,jump.sub);return}let full=`/${c2.name}${arg?" "+arg:""}`;if(x2.turnRef.current.streaming){x2.setQueue((q5)=>[...q5,full]);return}x2.dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)x2.dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)x2.dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c2.name,arg}).then((d2)=>{if(d2.notice)x2.dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return x2.dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void x2.sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")x2.dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c2.name}`});return void x2.sendRef.current(d2.message)}x2.dispatch({kind:"system",text:`/${c2.name}: unknown`})}).catch((e)=>x2.dispatch({kind:"system",text:`error: ${e.message}`}))})},[gw,dialog,toast,themeCtx,renderer,destructive,applyTitle,runCompress,branch2]);return import_react128.useEffect(()=>cmd.register([{title:"Help",value:"help",action:"help.open",category:"General",onSelect:()=>dialog.replace($jsx(HelpDialog,{}))},{title:"Keybindings",value:"keys",description:"View & rebind shortcuts",category:"General",onSelect:()=>openKeys(dialog)},{title:"Gateway Logs",value:"logs",description:"Show gateway stderr",category:"General",onSelect:()=>openLogs(dialog)},{title:"Switch Theme",value:"theme",action:"theme.pick",category:"General",onSelect:()=>openThemePicker(dialog,themeCtx)},{title:"Switch Model",value:"model",action:"model.pick",category:"General",onSelect:()=>openModelPicker(dialog,gw)},{title:"Pick Avatar",value:"eikon",description:"Choose sidebar .eikon avatar",category:"General",onSelect:()=>pickEikon()},{title:"Rollback",value:"rollback",description:"Browse & restore checkpoints",category:"Session",onSelect:()=>openRollback(dialog,gw,toast)},{title:"History",value:"history",action:"session.timeline",category:"Session",onSelect:()=>openHistory(dialog,gw)},{title:"Status",value:"status",action:"status.open",category:"Info",onSelect:()=>openStatus(dialog,ctx2.current.info,ctx2.current.sid)},{title:"Usage",value:"usage",description:"Tokens \xB7 context \xB7 cost",category:"Info",onSelect:()=>openUsage(dialog,gw)},{title:"Profile",value:"profile",description:"Active profile details",category:"Info",onSelect:()=>openProfile(dialog)},{title:"New Session",value:"new-session",action:"session.new",category:"Session",onSelect:()=>destructive("",{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{ctx2.current.newSession()})},{title:"Compress Session",value:"compress",action:"session.compress",category:"Session",onSelect:()=>runCompress()},{title:"Undo Last Turn",value:"undo",description:"Pop last user+assistant pair",category:"Session",onSelect:()=>run({name:"undo",target:"local"})},{title:"Redo",value:"redo",action:"session.redo",category:"Session",onSelect:()=>run({name:"redo",target:"local"})},{title:"Branch Session",value:"branch",description:"Fork the current conversation",category:"Session",onSelect:()=>branch2()}]),[cmd,dialog,themeCtx,gw,toast,destructive,pickEikon,runCompress,branch2,run]),run}var import_react132=__toESM(require_react_production(),1);var import_react130=__toESM(require_react_production(),1);function openAlert(dialog,title,body2){dialog.replace($jsx(Alert,{title,body:body2,onClose:()=>dialog.clear()}))}var Alert=(props)=>{let theme=useTheme().theme,keys=useKeys(),[copied,setCopied]=import_react130.useState(!1),doCopy=()=>{copy2(props.body),setCopied(!0),setTimeout(()=>setCopied(!1),900)};return useKeyboard((key5)=>{if(keys.match("dialog.cancel",key5)||keys.match("dialog.accept",key5))props.onClose();if(keys.match("dialog.copy",key5))doCopy()}),$jsxs("box",{flexDirection:"column",width:84,maxHeight:28,border:["left"],borderColor:theme.info,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingRight:2,paddingY:1,gap:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.info,children:"\u25C8 "}),$jsx("span",{fg:theme.text,children:props.title})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.body})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:`${keys.print("dialog.cancel")} close \xB7 ${keys.print("dialog.copy")} `})}),$jsx("box",{flexShrink:0,onMouseDown:(e)=>{e.stopPropagation(),doCopy()},children:$jsx("text",{fg:copied?theme.success:theme.textMuted,children:$jsx("u",{children:copied?"copied":"copy"})})})]})]})};init_perf();function variant(level2){switch(level2){case"error":return"error";case"warning":case"warn":return"warning";case"success":return"success";default:return"info"}}function duration2(p){if(p.kind==="sticky")return null;if(typeof p.ttl_ms==="number")return p.ttl_ms;if(typeof p.duration_ms==="number")return p.duration_ms;return}function showNotification(toast,p){let text4=String(p?.text??"").trim();if(!text4)return;toast.show({key:p?.key,variant:variant(p?.level),message:text4,duration:duration2(p??{text:text4})})}function clearNotification(toast,p){let key5=String(p?.key??"").trim();if(!key5)return;toast.clear(key5)}function count3(o){return o?Object.values(o).reduce((n,v2)=>n+v2.length,0):0}function formatProcessNotification(text4){let body2=text4.replace(/^\[IMPORTANT: /,"").replace(/\]$/,""),done2=body2.match(/^Background process (\S+) completed \(exit code (\S+)\)\.\nCommand: (.+?)(?:\n|$)/);if(done2)return`${done2[1]} exited ${done2[2]} \xB7 ${done2[3]}`;let hit2=body2.match(/^Background process (\S+) matched watch pattern "([^"]+)"\.\nCommand: (.+?)(?:\n|$)/);if(hit2)return`${hit2[1]} matched "${hit2[2]}" \xB7 ${hit2[3]}`;return body2.slice(0,100)}function mapEvent(ev,side){switch(ev.type){case"gateway.ready":if(side.onReady?.(),ev.payload?.skin)side.onSkin?.(ev.payload.skin);return null;case"session.info":{let si=ev.payload;side.onSessionInfo?.(si);let label2=si.model?`Connected \u2014 ${si.model} \xB7 ${count3(si.tools)} tools \xB7 ${count3(si.skills)} skills`:"Connected to Hermes";if(si.credential_warning)side.onStatus?.(si.credential_warning);return{kind:"system",text:label2}}case"message.start":return count("stream:start"),mem("stream-start"),{kind:"message.start"};case"message.delta":{let chunk=ev.payload?.text??"";if(!chunk)return null;return count("stream:chunk"),{kind:"message.delta",chunk}}case"message.complete":{count("stream:done"),mem("stream-done");let p=ev.payload;if(p?.usage)side.onUsage?.(p.usage);if(side.onTurnComplete?.(),p?.status==="error")return{kind:"error",text:p.text||"request failed \u2014 see messages above"};if(p?.status==="interrupted")return{kind:"message.complete",text:(p.text||"")+`
4200
4200
 
4201
4201
  *[interrupted]*`,usage:p?.usage};return{kind:"message.complete",text:p?.text??void 0,usage:p?.usage}}case"tool.start":return{kind:"tool.start",id:ev.payload.tool_id,name:ev.payload.name??"unknown",preview:ev.payload.context,args:ev.payload.args_text};case"tool.progress":return{kind:"tool.progress",name:ev.payload.name,preview:ev.payload.preview};case"tool.generating":return{kind:"tool.generating",name:ev.payload.name};case"tool.complete":return{kind:"tool.complete",id:ev.payload.tool_id,summary:ev.payload.summary,error:ev.payload.error,inline_diff:ev.payload.inline_diff,duration:typeof ev.payload.duration_s==="number"?ev.payload.duration_s*1000:void 0,result:ev.payload.result_text};case"thinking.delta":return side.onStatus?.(ev.payload?.text??""),null;case"reasoning.delta":case"reasoning.available":{let text4=ev.payload?.text;if(!text4)return null;return{kind:"thinking",text:text4,final:ev.type==="reasoning.available",verbose:ev.payload?.verbose}}case"subagent.start":case"subagent.thinking":case"subagent.tool":case"subagent.progress":case"subagent.complete":{let sub2=ev.type.slice(9);return record(sub2,ev.payload),{kind:"subagent",event:sub2,payload:ev.payload}}case"error":return{kind:"error",text:ev.payload?.message??"Unknown error"};case"clarify.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"clarify",...ev.payload}};case"approval.request":if(shouldRemember({variant:"approval",...ev.payload}))return side.onApprovalRemembered?.(),null;return{kind:"prompt",id:`approval-${pid()}`,req:{variant:"approval",...ev.payload}};case"sudo.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"sudo",...ev.payload}};case"secret.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"secret",...ev.payload}};case"background.complete":return side.onBackground?.(ev.payload.task_id,ev.payload.text),null;case"review.summary":{let text4=String(ev.payload?.text??"").trim();if(!text4)return null;return{kind:"system",text:text4}}case"btw.complete":return side.onBtw?.(ev.payload.text),null;case"gateway.stderr":{let line4=ev.payload.line;if(/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i.test(line4))return{kind:"error",text:line4,fatal:!1};return null}case"skin.changed":return side.onSkin?.(ev.payload),null;case"gateway.start_timeout":return{kind:"error",text:`gateway startup timed out (${ev.payload?.python??"python"} @ ${ev.payload?.cwd??"?"})`};case"gateway.protocol_error":return{kind:"system",text:`protocol error: ${ev.payload?.preview??"?"}`};case"browser.progress":{let text4=ev.payload?.message??"";if(!text4)return null;return ev.payload?.level==="error"?{kind:"error",text:text4}:{kind:"system",text:`\xB7 ${text4}`}}case"status.update":{let kind2=ev.payload?.kind,text4=ev.payload?.text??"";if(side.onStatus?.(text4),!kind2||kind2==="status")return null;if(kind2==="process")return side.onProcessNotification?.(text4),null;return{kind:"system",text:text4}}case"notification.show":if(side.notices)showNotification(side.notices,ev.payload);return null;case"notification.clear":if(side.notices)clearNotification(side.notices,ev.payload);return null;case"voice.status":{let state2=String(ev.payload?.state??"");return side.onVoiceStatus?.(state2),null}case"voice.transcript":{if(ev.payload?.no_speech_limit===!0)return side.onVoiceTranscript?.("",!0),null;let text4=String(ev.payload?.text??"").trim();if(!text4)return null;return side.onVoiceTranscript?.(text4,!1),null}}return null}var STREAM_EVENTS=new Set(["message.start","message.delta","reasoning.delta","reasoning.available","thinking.delta","tool.start","tool.progress","tool.generating"]),TITLE_DELAYS=[1200,5000,15000,30000];function useStream(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),bg2=useBackground(),ctx2=import_react132.useRef(c);ctx2.current=c;let timers=import_react132.useRef([]);import_react132.useEffect(()=>()=>{timers.current.forEach(clearTimeout),timers.current=[]},[]);let interrupted=import_react132.useRef(!1),info3=import_react132.useRef(!1),deltas=import_react132.useRef({text:"",think:"",timer:null}),procs=import_react132.useRef({texts:[],timer:null}),flush2=import_react132.useCallback(()=>{let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;if(d2.think)ctx2.current.dispatch({kind:"thinking",text:d2.think,final:!1}),d2.think="";if(d2.text)ctx2.current.dispatch({kind:"message.delta",chunk:d2.text}),d2.text=""},[]),flushProcs=import_react132.useCallback(()=>{let n=procs.current;if(n.timer)clearTimeout(n.timer),n.timer=null;if(!n.texts.length)return;let batch=n.texts.splice(0),lines3=batch.map((t2)=>` ${formatProcessNotification(t2)}`);ctx2.current.dispatch({kind:"system",text:batch.length===1?`\u25C6 background ${lines3[0].trim()}`:`\u25C6 ${batch.length} background notifications
4202
4202
  ${lines3.join(`
4203
- `)}`})},[]),sync=import_react132.useCallback((ms2=0)=>{let run=()=>gw.request("session.title").then((r)=>{if(ctx2.current.setTitle(r.title??""),r.session_key)set("lastSessionId",r.session_key)}).catch(()=>{});if(ms2<=0)return run();let id=setTimeout(()=>{timers.current=timers.current.filter((t2)=>t2!==id),run()},ms2);timers.current.push(id)},[gw]),handle=import_react132.useCallback((ev)=>{let x2=ctx2.current;if(ev.type==="gateway.ready")info3.current=!1;let shared=ev.type==="background.complete"||ev.type==="status.update"&&ev.payload?.kind==="process";if(ev.session_id&&x2.sidRef.current&&ev.session_id!==x2.sidRef.current&&!ev.type.startsWith("gateway.")&&!shared)return;if(interrupted.current){if(STREAM_EVENTS.has(ev.type))return;if(ev.type==="status.update"&&ev.payload?.kind==="lifecycle")return}let action=mapEvent(ev,{onReady:()=>{x2.session.boot(x2.launchRef.current).then((r)=>{if(x2.setSid(r.id),r.info)x2.setInfo(r.info),x2.setUsage(r.info.usage);if(x2.sessionStart.current=Date.now(),r.messages.length)x2.dispatch({kind:"load",messages:r.messages});if(r.note)toast.show({variant:"info",message:r.note})})},onSessionInfo:(si)=>{if(x2.setInfo(si),x2.setReady(!0),si.session_id)x2.setSid(si.session_id);let bad=(si.mcp_servers??[]).filter((s)=>!s.connected);if(bad.length)x2.dispatch({kind:"system",text:`MCP: ${bad.length} server(s) failed to connect \u2014 ${bad.map((s)=>s.name+(s.error?` (${s.error})`:"")).join(", ")}`});sync(),gw.request("config.get",{key:"busy"}).then((r)=>{let m2=r.value;if(m2==="queue"||m2==="steer"||m2==="interrupt")x2.setBusy(m2)}).catch(()=>{})},onUsage:(u3)=>x2.setUsage(u3),onTurnComplete:()=>{x2.setStatus(""),flush(gw,x2.sidRef.current),x2.goalHook.check(x2.sidRef.current),TITLE_DELAYS.forEach(sync)},onBackground:(tid,text4)=>{bg2.unregister(tid);let head=text4.split(`
4203
+ `)}`})},[]),sync=import_react132.useCallback((ms2=0)=>{let run=()=>gw.request("session.title").then((r)=>{if(ctx2.current.setTitle(r.title??""),r.session_key)set("lastSessionId",r.session_key)}).catch(()=>{});if(ms2<=0)return run();let id=setTimeout(()=>{timers.current=timers.current.filter((t2)=>t2!==id),run()},ms2);timers.current.push(id)},[gw]),handle=import_react132.useCallback((ev)=>{let x2=ctx2.current;if(ev.type==="gateway.ready")info3.current=!1;let shared=ev.type==="background.complete"||ev.type==="status.update"&&ev.payload?.kind==="process";if(ev.session_id&&x2.sidRef.current&&ev.session_id!==x2.sidRef.current&&!ev.type.startsWith("gateway.")&&!shared)return;if(interrupted.current){if(STREAM_EVENTS.has(ev.type))return;if(ev.type==="status.update"&&ev.payload?.kind==="lifecycle")return}let action=mapEvent(ev,{onReady:()=>{x2.session.boot(x2.launchRef.current).then((r)=>{if(x2.setSid(r.id),r.info)x2.setInfo(r.info),x2.setUsage(r.info.usage);if(x2.sessionStart.current=Date.now(),r.messages.length)x2.dispatch({kind:"load",messages:r.messages});if(r.note)toast.show({variant:"info",message:r.note})})},onSessionInfo:(si)=>{if(x2.setInfo(si),x2.setReady(!0),si.session_id)x2.setSid(si.session_id);x2.settle();let bad=(si.mcp_servers??[]).filter((s)=>!s.connected);if(bad.length)x2.dispatch({kind:"system",text:`MCP: ${bad.length} server(s) failed to connect \u2014 ${bad.map((s)=>s.name+(s.error?` (${s.error})`:"")).join(", ")}`});sync(),gw.request("config.get",{key:"busy"}).then((r)=>{let m2=r.value;if(m2==="queue"||m2==="steer"||m2==="interrupt")x2.setBusy(m2)}).catch(()=>{})},onUsage:(u3)=>x2.setUsage(u3),onTurnComplete:()=>{x2.setStatus(""),flush(gw,x2.sidRef.current),x2.goalHook.check(x2.sidRef.current),TITLE_DELAYS.forEach(sync)},onBackground:(tid,text4)=>{bg2.unregister(tid);let head=text4.split(`
4204
4204
  `)[0].slice(0,80);x2.dispatch({kind:"system",text:`\u25F7 background task ${tid} complete \u2014 ${head}`}),toast.show({variant:"info",title:"Background task complete",message:head,duration:8000,action:{label:"view",run:()=>openAlert(dialog,`Background task ${tid}`,text4)}})},onBtw:(text4)=>{let head=text4.split(`
4205
4205
  `)[0].slice(0,80);x2.dispatch({kind:"system",text:`\u25C8 btw \u2014 ${head}`}),toast.show({variant:"info",title:"btw",message:head,duration:8000,action:{label:"view",run:()=>openAlert(dialog,"btw",text4)}})},onStatus:(text4)=>x2.setStatus(text4),onApprovalRemembered:()=>{gw.request("approval.respond",{choice:"always"}).catch(()=>{})},onProcessNotification:(text4)=>{let n=procs.current;if(n.texts.push(text4),n.timer)clearTimeout(n.timer);n.timer=setTimeout(flushProcs,500)},onSkin:(s)=>x2.setSkin(deriveSkin(s)),notices:toast});if(!action)return;if(ev.type==="session.info"){if(info3.current)return;info3.current=!0}let d2=deltas.current;if(action.kind==="message.delta"){if(d2.think)flush2();d2.text+=action.chunk,d2.timer??=setTimeout(flush2,16);return}if(action.kind==="thinking"&&!action.final){if(d2.text)flush2();d2.think+=action.text,d2.timer??=setTimeout(flush2,16);return}if(flush2(),action.kind==="error")x2.setErrorPulse(!0);x2.dispatch(action)},[gw,dialog,toast,flush2]);useGatewayEvent(handle);let doInterrupt=import_react132.useCallback(()=>{interrupted.current=!0;let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;d2.text="",d2.think="",ctx2.current.session.interrupt()},[]);return{interrupted,doInterrupt}}var import_react138=__toESM(require_react_production(),1);init_perf();var PORT=Number(process.env.CONTROL_PORT)||7777,BIND=process.env.CONTROL_BIND||"127.0.0.1",enabled2=process.env.CONTROL==="1",LOOPBACK=new Set(["127.0.0.1","::1","localhost"]);function isLoopback(host){return LOOPBACK.has(host)}function warningFor(on,bind,port2){if(!on)return null;if(isLoopback(bind))return null;return{host:bind,port:port2,message:`CONTROL server bound to ${bind}:${port2} \u2014 reachable from the network. Set CONTROL_BIND=127.0.0.1 to restrict to loopback.`}}function warning(){return warningFor(enabled2,BIND,PORT)}var TAB_NAMES=TABS.map((t2)=>t2.name),bridge=null,pendingTab=null;function setBridge(b2){bridge=b2}function currentTab(){if(pendingTab!==null)return pendingTab;return bridge?.tab()??0}var json2=(data2,status=200)=>new Response(JSON.stringify(data2),{status,headers:{"Content-Type":"application/json"}}),idx=(name)=>{let n=TAB_NAMES.indexOf(name);if(n<0)throw Error(`control.ts DANGEROUS: tab '${name}' missing from TAB_NAMES`);return n},DANGEROUS={[idx("Chat")]:new Set(["return"]),[idx("Sessions")]:new Set(["d","delete","return"]),[idx("Profiles & Automation")]:new Set(["return","space","d","delete","k"]),[idx("Config")]:new Set(["space","return","h","l","]","[","ctrl+s","d","delete"]),[idx("Eikon")]:new Set(["return","n","d","delete","s","u","ctrl+s","ctrl+u"])};function isDangerous(tab,keyName2,ctrl){let set2=DANGEROUS[tab];if(!set2)return!1;let id=ctrl?`ctrl+${keyName2}`:keyName2;return set2.has(id)}function makeKey(opts){return{name:opts.name,ctrl:opts.ctrl??!1,meta:opts.meta??!1,shift:opts.shift??!1,option:!1,sequence:opts.raw??opts.name,number:!1,raw:opts.raw??opts.name,eventType:"press",source:"raw"}}function injectKey(renderer,key5){let r=renderer;if(!r?.keyInput?.processParsedKey)return!1;return r.keyInput.processParsedKey(key5)}function getNodeChildren(n){if(n.getChildren)return n.getChildren();if(n._childrenInLayoutOrder)return[...n._childrenInLayoutOrder];return[]}function getNodeType(n){return n._type||n.tagName||n.constructor?.name||"unknown"}function buildFocusTree(node,depth=0){if(!node||typeof node!=="object")return null;let n=node,type=getNodeType(n),focused=n.focused??!1,focusable=n.focusable??!1,children2=[];if(depth<20)for(let child of getNodeChildren(n)){let c=buildFocusTree(child,depth+1);if(c)children2.push(c)}if(!(focusable||children2.some((c)=>c.focusable||c.focused||c.children.length>0))&&!focused&&depth>0)return null;let text4=n.value||n.textContent||n.text||void 0;return{type,focused,focusable,children:children2,text:text4}}function findFocused(node){if(!node||typeof node!=="object")return null;let n=node;if(n.focused)return getNodeType(n);for(let child of getNodeChildren(n)){let found2=findFocused(child);if(found2)return found2}return null}function countNodes(node){let result={total:0,focusable:0,focused:0};function walk2(n){if(!n||typeof n!=="object")return;let nd=n;if(result.total++,nd.focusable)result.focusable++;if(nd.focused)result.focused++;for(let child of getNodeChildren(nd))walk2(child)}return walk2(node),result}async function handle(req){let url2=new URL(req.url),path7=url2.pathname;if(!bridge)return json2({error:"bridge not ready"},503);if(path7==="/status"){let m2=process.memoryUsage(),tab=currentTab();return pendingTab=null,json2({tab,tabName:TAB_NAMES[tab]??"unknown",ready:bridge.ready(),streaming:bridge.streaming(),messages:bridge.messages(),session:bridge.session(),input:bridge.input(),focusRegion:bridge.focusRegion(),rss:Math.round(m2.rss/1024/1024),heap:Math.round(m2.heapUsed/1024/1024)})}let tabMatch=path7.match(/^\/tab\/(\d+)$/);if(tabMatch){let n=Number(tabMatch[1]);if(n<0||n>TAB_MAX)return json2({error:`tab 0-${TAB_MAX}`},400);let renderer=bridge.renderer();if(renderer){let cur=bridge.tab(),diff=n-cur,key5=makeKey({name:diff>0?"right":"left",meta:!0});for(let i=Math.abs(diff);i>0;i--)injectKey(renderer,key5)}else bridge.setTab(n);return pendingTab=n,json2({tab:n,tabName:TAB_NAMES[n]})}if(path7==="/send"&&req.method==="POST"){let body2=await req.json();if(!body2.message)return json2({error:"message required"},400);if(!bridge.ready())return json2({error:"not connected"},503);if(bridge.streaming())return json2({error:"already streaming"},409);return bridge.send(body2.message),json2({sent:!0,message:body2.message})}if(path7==="/key"&&req.method==="POST"){let body2=await req.json();if(!body2.name)return json2({error:"name required"},400);let renderer=bridge.renderer();if(!renderer)return json2({error:"renderer not available"},503);let safe2=body2.safe!==!1,tab=currentTab();if(safe2&&isDangerous(tab,body2.name,!!body2.ctrl))return json2({error:"blocked",reason:`Key "${body2.ctrl?"ctrl+":""}${body2.name}" is dangerous on tab ${TAB_NAMES[tab]} (index ${tab}). Pass safe=false to override.`,tab,tabName:TAB_NAMES[tab]},403);let key5=makeKey({name:body2.name,ctrl:body2.ctrl,shift:body2.shift,meta:body2.meta,raw:body2.raw??(body2.name.length===1?body2.name:"")}),handled=injectKey(renderer,key5);return json2({injected:!0,handled,key:body2.name,tab,tabName:TAB_NAMES[tab]})}if(path7==="/keys"&&req.method==="POST"){let body2=await req.json();if(!body2.keys?.length)return json2({error:"keys array required"},400);let renderer=bridge.renderer();if(!renderer)return json2({error:"renderer not available"},503);let safe2=body2.safe!==!1,tab=currentTab(),delay=body2.delay??0,results=[];for(let k2 of body2.keys){if(safe2&&isDangerous(currentTab(),k2.name,!!k2.ctrl)){results.push({key:k2.name,injected:!1,handled:!1,blocked:!0});continue}let key5=makeKey({name:k2.name,ctrl:k2.ctrl,shift:k2.shift,meta:k2.meta,raw:k2.raw??(k2.name.length===1?k2.name:"")}),handled=injectKey(renderer,key5);if(results.push({key:k2.name,injected:!0,handled}),delay>0)await new Promise((r)=>setTimeout(r,delay))}return json2({results,tab,tabName:TAB_NAMES[tab]})}if(path7==="/type"&&req.method==="POST"){let body2=await req.json();if(!body2.text)return json2({error:"text required"},400);let renderer=bridge.renderer();if(!renderer)return json2({error:"renderer not available"},503);let safe2=body2.safe!==!1,tab=currentTab(),delay=body2.delay??0,count4=0;for(let ch of body2.text){if(safe2&&isDangerous(tab,ch,!1))continue;let key5=makeKey({name:ch,raw:ch});if(injectKey(renderer,key5),count4++,delay>0)await new Promise((r)=>setTimeout(r,delay))}return json2({typed:count4,total:body2.text.length,tab,tabName:TAB_NAMES[tab]})}if(path7==="/input"&&req.method==="POST"){let body2=await req.json();return bridge.setInput(body2.text??""),json2({ok:!0,text:body2.text??""})}if(path7==="/quit")return setTimeout(()=>process.exit(0),10),json2({ok:!0});if(path7==="/focus"){let r=bridge.renderer();if(!r?.root)return json2({error:"no renderer root"},503);let counts=countNodes(r.root),tree3=buildFocusTree(r.root),focused=findFocused(r.root),currentFocus=r.currentFocusedRenderable?getNodeType(r.currentFocusedRenderable):null;return json2({focused,currentFocus,counts,tree:tree3})}if(path7==="/frame"){let r=bridge.renderer();if(!r?.currentRenderBuffer)return json2({error:"no render buffer"},503);let frame2=new TextDecoder().decode(r.currentRenderBuffer.getRealCharBytes(!0)),grep=url2.searchParams.get("grep"),body2=grep?frame2.split(`
4206
4206
  `).filter((l)=>l.includes(grep)).join(`
@@ -4227,10 +4227,10 @@ ${lines3.join(`
4227
4227
  `)&&t2.cursorOffset!==0)return t2.cursorOffset=0,!0;return hist.up(),!0},historyDown:()=>{let t2=ta.current;if(!t2||modeRef.current==="shell")return!1;let buf2=live.current.input;if(buf2.indexOf(`
4228
4228
  `,t2.cursorOffset)>=0)return!1;if(buf2.includes(`
4229
4229
  `)&&t2.cursorOffset!==buf2.length)return t2.cursorOffset=buf2.length,!0;return hist.down(),!0}}),[hist.up,hist.down,pop3.setCursor,write]);let sidsRef=import_react146.useRef(sids);sidsRef.current=sids;let taRef=import_react146.useCallback((r)=>{if(ta.current=r,r&&!buf.current)buf.current=new PartsBuffer(r,sidsRef.current);if(!r)buf.current=null},[]),label2=!props.ready?"Connecting...":props.streaming?props.status||"Generating...":"Ready",dot=props.ready?props.streaming?theme.warning:theme.success:theme.error,rows3=Math.min(MAX_ROWS,Math.max(1,input.split(`
4230
- `).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop3.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop3.popover,cursor:pop3.cursor,onCursor:pop3.setCursor,onSelect:select2})}):props.focused&&at.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:at.items,cursor:at.cursor,onCursor:at.setCursor,onSelect:atAccept})}):props.focused&&comp.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:comp.items,cursor:comp.cursor,onCursor:comp.setCursor,onSelect:(idx2)=>{let it=comp.items[idx2];if(it?.text)write(acceptCompletion(input,it,comp.replaceFrom))}})}):null,(props.queue?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,children:props.queue.map((q5,i)=>$jsx("box",{height:1,onMouseDown:()=>props.onDequeue?.(i),children:$jsxs("text",{children:[$jsxs("span",{fg:theme.borderSubtle,children:[i===0?"\u256D":"\u2502"," "]}),$jsxs("span",{fg:theme.textMuted,children:["\u23F8 ",i+1,". ",trunc5(q5,60)]})]})},i))}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,gap:1,children:props.attachments.map((a)=>a.path?$jsx(ChafaImage,{path:a.path,width:60},`p-${a.path}`):null)}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"row",flexWrap:"wrap",gap:1,paddingX:1,paddingBottom:1,children:props.attachments.map((a,i)=>$jsxs("text",{children:[$jsx("span",{bg:theme.accent,fg:theme.background,children:" img "}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[" ",a.name??`image ${i+1}`," "]}),a.width&&a.height?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[a.width,"\xD7",a.height," "]}):null,a.token_estimate?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:["~",fmt5(a.token_estimate),"t "]}):null,$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.textMuted,children:"\u232B to detach"})]},a.path??i))}):null,$jsxs("box",{border:!0,borderStyle:"single",borderColor:mode==="shell"?theme.primary:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:mode==="shell"?"$":">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:taRef,syntaxStyle,onContentChange:()=>{let t2=ta.current;setInput(t2?.plainText??""),setCaret(t2?.cursorOffset??0)},onCursorChange:()=>{if(!live.current.input.includes("@"))return;let off=ta.current?.cursorOffset??0;setCaret((c)=>c===off?c:off)},onSubmit:submit4,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder:mode==="shell"?"Run a shell command (30s cap, cwd) \u2014 esc or \u232B to exit":props.streaming?"Type to queue... (Enter queues, click chip to edit)":"Message Hermes... (/ for commands, Shift+Enter for newline)",focused:props.focused,textColor:theme.text,focusedTextColor:theme.text,placeholderColor:theme.textMuted,cursorColor:theme.text,backgroundColor:"transparent",focusedBackgroundColor:"transparent",flexGrow:1}),pop3.ghost&&props.focused&&rows3===1?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop3.ghost})}):null]}),$jsxs("box",{height:1,flexDirection:"row",paddingX:1,children:[$jsxs("text",{children:[$jsx("span",{fg:dot,children:"\u25CF "}),$jsx("span",{fg:theme.textMuted,children:mode==="shell"?"Shell":label2}),mode==="shell"?$jsx("span",{fg:theme.textMuted,children:" esc exit shell mode"}):props.streaming&&props.escHint?$jsx("span",{fg:theme.warning,children:" esc again to interrupt"}):props.streaming?$jsx("span",{fg:theme.textMuted,children:" esc\xD72 interrupt"}):null]}),$jsx("box",{flexGrow:1}),props.streaming&&(props.queue?.length??0)>0?$jsxs("text",{fg:theme.textMuted,children:[keys.print("queue.flush")," to send queued now "]}):null,bg2.count>0?$jsxs("text",{fg:theme.text,children:["\u25B6 ",bg2.count," "]}):null,props.model?$jsx("text",{fg:theme.textMuted,children:props.model}):null]})]})}));var import_react147=__toESM(require_react_production(),1);init_sessions_db();var normalize3=(sid2)=>sid2.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user2=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user2)messages.push(...transcriptToMessages([{role:"user",text:user2}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.resume",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target2);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react147.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),{id:res.session_id,info:res.info}},[gw]),activate=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.activate",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.session_key??id);let history=res.messages?.length?transcriptToMessages(res.messages):[],running2=Boolean(res.running||res.status==="working"||res.status==="waiting");return{id,info:res.info,messages:[...history,...inflightMessages(res.inflight)],running:running2,startedAt:res.started_at?res.started_at*1000:void 0,status:res.status}},[gw]),busy=import_react147.useCallback(async()=>{try{return(await gw.request("agents.list")).processes?.some((p)=>p.status==="running")??!1}catch{return!1}},[gw]),close=import_react147.useCallback(async(sid2,opts)=>{if(!sid2)return!1;if(opts?.preserveBackground&&await busy())return!1;try{return await gw.request("session.close",{session_id:sid2}),!0}catch{return!1}},[gw,busy]),boot2=import_react147.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target2=launch.sid??exports_sessions_db.lastReal()?.id;if(!target2)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target2)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target2} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row4=last3?exports_sessions_db.byId(last3):null;if(row4?.message_count===0&&row4.parent_session_id==null)try{return await resume(row4.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react147.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react147.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react147.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react147.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react147.useMemo(()=>({boot:boot2,create,resume,activate,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,activate,close,interrupt,branch2,compress,undo])}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache3.clear(),resetKanban(),exports_preferences.reload(),home2.reset()}var import_react148=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react148.useState(p.seconds);import_react148.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(exports_preferences.get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid2)=>{if(!sid2)return;io.goalState(sid2).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid2)===s.goal)return;fired.set(sid2,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react150=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react150.useState(!1),[recording,setRecording]=import_react150.useState(!1),[processing,setProcessing]=import_react150.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react150.useState(),[tts,setTts]=import_react150.useState(!1),[onTranscript,setTranscript]=import_react150.useState(null),setOnTranscript=import_react150.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react150.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react150.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react150.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react150.useCallback(async(action,sid2)=>{try{let r=await gw("voice.toggle",{action,session_id:sid2});if(r.enabled!==void 0)setEnabled(r.enabled);if(r.tts!==void 0)setTts(r.tts);if(r.record_key)setRecordKeyRaw(r.record_key);let label2=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label2}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react150.useCallback(async(sid2)=>{if(!enabled3){sys("voice: mode is off \u2014 enable with /voice on");return}let starting=!recording,action=starting?"start":"stop";if(starting)setRecording(!0);else setRecording(!1),setProcessing(!1);try{let r=await gw("voice.record",{action,session_id:sid2});if(starting&&r.status!=="recording"){if(setRecording(!1),r.status==="busy")setProcessing(!0),sys("voice: still transcribing; try again shortly")}}catch(e){if(starting)setRecording(!1);sys(`voice error: ${e instanceof Error?e.message:"gateway error"}`)}},[enabled3,recording,gw,sys]);return{state:state2,toggle,record:record2,setEnabled,setRecording,setProcessing,setRecordKey:setRecordKeyRaw,keyLabel,onTranscript,setOnTranscript}}function VoiceIndicator({voice,keyLabel}){let theme=useTheme().theme;if(!voice.enabled&&!voice.recording&&!voice.processing)return null;let text4,fg2=theme.text;if(voice.recording)text4="\u25CF recording",fg2=theme.error;else if(voice.processing)text4="\u25CC transcribing",fg2=theme.warning;else text4=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text4," "]})})}function sessionCapabilities(input){let sessionConnected=Boolean(input.sid),metadataHydrated=input.ready;return{sessionConnected,metadataHydrated,canSubmitPrompt:sessionConnected,canDispatchGatewayCommand:sessionConnected,canDrainQueue:sessionConnected&&!input.streaming}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react152.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react152.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react152.useState(!1),[sid2,setSid]=import_react152.useState(""),sidRef=import_react152.useRef(sid2);sidRef.current=sid2;let capabilities=sessionCapabilities({sid:sid2,ready,streaming:turn.streaming}),[tab,setTab]=import_react152.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react152.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react152.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react152.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react152.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react152.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react152.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react152.useState(!1),[usage,setUsage]=import_react152.useState(void 0),[info3,setInfo]=import_react152.useState(null),[title,setTitle]=import_react152.useState(""),caption=title.trim(),titleRef=import_react152.useRef(caption);titleRef.current=caption,import_react152.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react152.useEffect(()=>{let w2=warning();if(!w2)return;toast.show({variant:"warning",title:"control server exposed",message:w2.message,duration:15000})},[toast]);let[focusRegion,setFocusRegion]=import_react152.useState("input"),goToTab=import_react152.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react152.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react152.useState(""),[escHint,setEscHint]=import_react152.useState(!1),[eikon,setEikon]=import_react152.useState(void 0),[queue,setQueue]=import_react152.useState([]),[busy,setBusy]=import_react152.useState("queue"),turnRef=import_react152.useRef(turn);turnRef.current=turn;let queueRef=import_react152.useRef(queue);queueRef.current=queue;let launchRef=import_react152.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react152.useState(launch.splash!==!1),[switching,setSwitching]=import_react152.useState(!1),summoned=import_react152.useRef(!1),[composing,setComposing]=import_react152.useState(!1),splashLast=import_react152.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react152.useMemo(()=>info3?{agentVersion:info3.version,behind:info3.update_behind,model:info3.model}:void 0,[info3?.version,info3?.update_behind,info3?.model]),splashLastProp=import_react152.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react152.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react152.useState([]),[cloudH,setCloudH]=import_react152.useState(CLOUD_MIN),[pick2,setPick]=import_react152.useState(void 0),[skin,setSkin]=import_react152.useState(()=>deriveSkin(void 0)),inflight=import_react152.useRef(!1),undone=import_react152.useRef([]),sessionStart=import_react152.useRef(Date.now()),composer2=import_react152.useRef(null),promptRef=import_react152.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react152.useRef(cmds);cmdsRef.current=cmds;let sys=import_react152.useCallback((text4)=>dispatch({kind:"system",text:text4}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react152.useEffect(()=>{voice.setOnTranscript((text4)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text4),0)})},[]);let[errorPulse,setErrorPulse]=import_react152.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react152.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react152.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react152.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react152.useRef(turn.streaming);import_react152.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react152.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react152.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react152.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react152.useRef(()=>{}),steer=import_react152.useCallback((text4)=>{let v2=text4.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),openSteer=import_react152.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react152.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q5)=>[t2,...q5]);setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react152.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse});intr.current=stream.doInterrupt;let reset4=import_react152.useCallback(()=>{stream.interrupted.current=!1,toast.clear("credits.depleted"),undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[toast]),newSession=import_react152.useCallback(async()=>{let prev=sidRef.current;if(reset4(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev,{preserveBackground:!0});try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset4,session,gw]),switchSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(setReady(!0),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev,{preserveBackground:!0});setSplash(!1),summoned.current=!1}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,gw]),liveStatus=(state2,running2=!1)=>{if(state2==="waiting")return"waiting for input\u2026";if(state2==="starting")return"starting agent\u2026";return running2||state2==="working"?"running\u2026":"ready"},activateSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.activate(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(sessionStart.current=res.startedAt??Date.now(),dispatch({kind:"load.live",messages:res.messages,streaming:res.running}),setStatus(liveStatus(res.status,res.running)),setReady(!0),setSplash(!1),summoned.current=!1,prev&&prev!==res.id)toast.show({variant:"info",message:"switched live session"})}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,toast,gw]),switchProfile=import_react152.useCallback((newHome,name)=>{rehome(newHome),reset4(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset4,goToTab,gwRestart,toast,gw]),loadEikon=import_react152.useCallback((path7)=>{try{setEikon(parseEikonFile(path7))}catch{setEikon(void 0)}},[]),eikonName=usePref("eikon"),eikonRev=import_react152.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react152.useEffect(()=>{let p=eikonName&&exports_eikon.baked(eikonName)||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonName,eikonRev,skin.skin?.name,loadEikon]);let turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text4),setFocusRegion("input")},[gw]),fork2=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await activateSession(res.session_id),composer2.current?.set(text4),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,activateSession]),msgMenu=import_react152.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react152.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),sendRef=import_react152.useRef(()=>{}),slash3=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,capabilities,info:info3,sid:sid2,title:caption,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,activateSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react152.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sidRef.current,titleRef.current,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve10(cmdsRef.current,name);if("hit"in r)return slash3(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text4=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text4=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text4].filter(Boolean).join(`
4231
- `):text4;dispatch({kind:"user",text:withMedia}),setAttachments([]),undone.current=[],gw.request("prompt.submit",{text:text4}).catch(()=>{inflight.current=!1}),setTab(CHAT_TAB)},[gw,slash3,attachments]);sendRef.current=send;let onShell=import_react152.useCallback((command)=>{setSplash(!1),dispatch({kind:"system",text:`$ ${command}`}),setStatus("running\u2026"),gw.request("shell.exec",{command}).then((r)=>{let out=(r.stdout??"").trimEnd(),err=(r.stderr??"").trimEnd(),body2=[out,err&&`stderr:
4230
+ `).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop3.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop3.popover,cursor:pop3.cursor,onCursor:pop3.setCursor,onSelect:select2})}):props.focused&&at.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:at.items,cursor:at.cursor,onCursor:at.setCursor,onSelect:atAccept})}):props.focused&&comp.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:comp.items,cursor:comp.cursor,onCursor:comp.setCursor,onSelect:(idx2)=>{let it=comp.items[idx2];if(it?.text)write(acceptCompletion(input,it,comp.replaceFrom))}})}):null,(props.queue?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,children:props.queue.map((q5,i)=>$jsx("box",{height:1,onMouseDown:()=>props.onDequeue?.(i),children:$jsxs("text",{children:[$jsxs("span",{fg:theme.borderSubtle,children:[i===0?"\u256D":"\u2502"," "]}),$jsxs("span",{fg:theme.textMuted,children:["\u23F8 ",i+1,". ",trunc5(q5,60)]})]})},i))}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,gap:1,children:props.attachments.map((a)=>a.path?$jsx(ChafaImage,{path:a.path,width:60},`p-${a.path}`):null)}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"row",flexWrap:"wrap",gap:1,paddingX:1,paddingBottom:1,children:props.attachments.map((a,i)=>$jsxs("text",{children:[$jsx("span",{bg:theme.accent,fg:theme.background,children:" img "}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[" ",a.name??`image ${i+1}`," "]}),a.width&&a.height?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[a.width,"\xD7",a.height," "]}):null,a.token_estimate?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:["~",fmt5(a.token_estimate),"t "]}):null,$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.textMuted,children:"\u232B to detach"})]},a.path??i))}):null,$jsxs("box",{border:!0,borderStyle:"single",borderColor:mode==="shell"?theme.primary:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:mode==="shell"?"$":">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:taRef,syntaxStyle,onContentChange:()=>{let t2=ta.current;setInput(t2?.plainText??""),setCaret(t2?.cursorOffset??0)},onCursorChange:()=>{if(!live.current.input.includes("@"))return;let off=ta.current?.cursorOffset??0;setCaret((c)=>c===off?c:off)},onSubmit:submit4,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder:mode==="shell"?"Run a shell command (30s cap, cwd) \u2014 esc or \u232B to exit":props.streaming?"Type to queue... (Enter queues, click chip to edit)":"Message Hermes... (/ for commands, Shift+Enter for newline)",focused:props.focused,textColor:theme.text,focusedTextColor:theme.text,placeholderColor:theme.textMuted,cursorColor:theme.text,backgroundColor:"transparent",focusedBackgroundColor:"transparent",flexGrow:1}),pop3.ghost&&props.focused&&rows3===1?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop3.ghost})}):null]}),$jsxs("box",{height:1,flexDirection:"row",paddingX:1,children:[$jsxs("text",{children:[$jsx("span",{fg:dot,children:"\u25CF "}),$jsx("span",{fg:theme.textMuted,children:mode==="shell"?"Shell":label2}),mode==="shell"?$jsx("span",{fg:theme.textMuted,children:" esc exit shell mode"}):props.streaming&&props.escHint?$jsx("span",{fg:theme.warning,children:" esc again to interrupt"}):props.streaming?$jsx("span",{fg:theme.textMuted,children:" esc\xD72 interrupt"}):null]}),$jsx("box",{flexGrow:1}),props.streaming&&(props.queue?.length??0)>0?$jsxs("text",{fg:theme.textMuted,children:[keys.print("queue.flush")," to send queued now "]}):null,bg2.count>0?$jsxs("text",{fg:theme.text,children:["\u25B6 ",bg2.count," "]}):null,props.model?$jsx("text",{fg:theme.textMuted,children:props.model}):null]})]})}));var import_react147=__toESM(require_react_production(),1);init_sessions_db();var normalize3=(sid2)=>sid2.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user2=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user2)messages.push(...transcriptToMessages([{role:"user",text:user2}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.resume",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target2);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react147.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),{id:res.session_id,info:res.info}},[gw]),activate=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.activate",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.session_key??id);let history=res.messages?.length?transcriptToMessages(res.messages):[],running2=Boolean(res.running||res.status==="working"||res.status==="waiting");return{id,info:res.info,messages:[...history,...inflightMessages(res.inflight)],running:running2,startedAt:res.started_at?res.started_at*1000:void 0,status:res.status}},[gw]),busy=import_react147.useCallback(async()=>{try{return(await gw.request("agents.list")).processes?.some((p)=>p.status==="running")??!1}catch{return!1}},[gw]),close=import_react147.useCallback(async(sid2,opts)=>{if(!sid2)return!1;if(opts?.preserveBackground&&await busy())return!1;try{return await gw.request("session.close",{session_id:sid2}),!0}catch{return!1}},[gw,busy]),boot2=import_react147.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target2=launch.sid??exports_sessions_db.lastReal()?.id;if(!target2)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target2)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target2} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row4=last3?exports_sessions_db.byId(last3):null;if(row4?.message_count===0&&row4.parent_session_id==null)try{return await resume(row4.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react147.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react147.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react147.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react147.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react147.useMemo(()=>({boot:boot2,create,resume,activate,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,activate,close,interrupt,branch2,compress,undo])}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache3.clear(),resetKanban(),exports_preferences.reload(),home2.reset()}var import_react148=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react148.useState(p.seconds);import_react148.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(exports_preferences.get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid2)=>{if(!sid2)return;io.goalState(sid2).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid2)===s.goal)return;fired.set(sid2,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react150=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react150.useState(!1),[recording,setRecording]=import_react150.useState(!1),[processing,setProcessing]=import_react150.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react150.useState(),[tts,setTts]=import_react150.useState(!1),[onTranscript,setTranscript]=import_react150.useState(null),setOnTranscript=import_react150.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react150.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react150.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react150.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react150.useCallback(async(action,sid2)=>{try{let r=await gw("voice.toggle",{action,session_id:sid2});if(r.enabled!==void 0)setEnabled(r.enabled);if(r.tts!==void 0)setTts(r.tts);if(r.record_key)setRecordKeyRaw(r.record_key);let label2=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label2}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react150.useCallback(async(sid2)=>{if(!enabled3){sys("voice: mode is off \u2014 enable with /voice on");return}let starting=!recording,action=starting?"start":"stop";if(starting)setRecording(!0);else setRecording(!1),setProcessing(!1);try{let r=await gw("voice.record",{action,session_id:sid2});if(starting&&r.status!=="recording"){if(setRecording(!1),r.status==="busy")setProcessing(!0),sys("voice: still transcribing; try again shortly")}}catch(e){if(starting)setRecording(!1);sys(`voice error: ${e instanceof Error?e.message:"gateway error"}`)}},[enabled3,recording,gw,sys]);return{state:state2,toggle,record:record2,setEnabled,setRecording,setProcessing,setRecordKey:setRecordKeyRaw,keyLabel,onTranscript,setOnTranscript}}function VoiceIndicator({voice,keyLabel}){let theme=useTheme().theme;if(!voice.enabled&&!voice.recording&&!voice.processing)return null;let text4,fg2=theme.text;if(voice.recording)text4="\u25CF recording",fg2=theme.error;else if(voice.processing)text4="\u25CC transcribing",fg2=theme.warning;else text4=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text4," "]})})}function sessionCapabilities(input){let sessionConnected=Boolean(input.sid),metadataHydrated=input.ready;return{sessionConnected,metadataHydrated,canSubmitPrompt:sessionConnected,canDispatchGatewayCommand:sessionConnected,canDrainQueue:sessionConnected&&!input.streaming}}var BUSY_RE=/session busy|waiting for model response/i,App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react152.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react152.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react152.useState(!1),[sid2,setSid]=import_react152.useState(""),sidRef=import_react152.useRef(sid2);sidRef.current=sid2;let capabilities=sessionCapabilities({sid:sid2,ready,streaming:turn.streaming}),[tab,setTab]=import_react152.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react152.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react152.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react152.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react152.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react152.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react152.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react152.useState(!1),[usage,setUsage]=import_react152.useState(void 0),[info3,setInfo]=import_react152.useState(null),[title,setTitle]=import_react152.useState(""),caption=title.trim(),titleRef=import_react152.useRef(caption);titleRef.current=caption,import_react152.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react152.useEffect(()=>{let w2=warning();if(!w2)return;toast.show({variant:"warning",title:"control server exposed",message:w2.message,duration:15000})},[toast]);let[focusRegion,setFocusRegion]=import_react152.useState("input"),goToTab=import_react152.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react152.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react152.useState(""),[escHint,setEscHint]=import_react152.useState(!1),[eikon,setEikon]=import_react152.useState(void 0),[queue,setQueue]=import_react152.useState([]),[busy,setBusy]=import_react152.useState("queue"),turnRef=import_react152.useRef(turn);turnRef.current=turn;let queueRef=import_react152.useRef(queue);queueRef.current=queue;let launchRef=import_react152.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react152.useState(launch.splash!==!1),[switching,setSwitching]=import_react152.useState(!1),summoned=import_react152.useRef(!1),[composing,setComposing]=import_react152.useState(!1),splashLast=import_react152.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react152.useMemo(()=>info3?{agentVersion:info3.version,behind:info3.update_behind,model:info3.model}:void 0,[info3?.version,info3?.update_behind,info3?.model]),splashLastProp=import_react152.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react152.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react152.useState([]),[cloudH,setCloudH]=import_react152.useState(CLOUD_MIN),[pick2,setPick]=import_react152.useState(void 0),[skin,setSkin]=import_react152.useState(()=>deriveSkin(void 0)),inflight=import_react152.useRef(!1),hold=import_react152.useRef(!1),[pulse,setPulse]=import_react152.useState(0),settle=import_react152.useCallback(()=>{if(!hold.current)return;hold.current=!1,setPulse((n)=>n+1)},[]),undone=import_react152.useRef([]),sessionStart=import_react152.useRef(Date.now()),composer2=import_react152.useRef(null),promptRef=import_react152.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react152.useRef(cmds);cmdsRef.current=cmds;let sys=import_react152.useCallback((text4)=>dispatch({kind:"system",text:text4}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react152.useEffect(()=>{voice.setOnTranscript((text4)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text4),0)})},[]);let[errorPulse,setErrorPulse]=import_react152.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react152.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react152.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react152.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react152.useRef(turn.streaming);import_react152.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react152.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react152.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react152.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react152.useRef(()=>{}),steer=import_react152.useCallback((text4)=>{let v2=text4.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),openSteer=import_react152.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react152.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt"){hold.current=!0,setQueue((q5)=>[t2,...q5]),intr.current();return}setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react152.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse,settle});intr.current=stream.doInterrupt;let reset4=import_react152.useCallback(()=>{stream.interrupted.current=!1,hold.current=!1,toast.clear("credits.depleted"),undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[toast]),newSession=import_react152.useCallback(async()=>{let prev=sidRef.current;if(reset4(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev,{preserveBackground:!0});try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset4,session,gw]),switchSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(setReady(!0),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev,{preserveBackground:!0});setSplash(!1),summoned.current=!1}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,gw]),liveStatus=(state2,running2=!1)=>{if(state2==="waiting")return"waiting for input\u2026";if(state2==="starting")return"starting agent\u2026";return running2||state2==="working"?"running\u2026":"ready"},activateSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.activate(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(sessionStart.current=res.startedAt??Date.now(),dispatch({kind:"load.live",messages:res.messages,streaming:res.running}),setStatus(liveStatus(res.status,res.running)),setReady(!0),setSplash(!1),summoned.current=!1,prev&&prev!==res.id)toast.show({variant:"info",message:"switched live session"})}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,toast,gw]),switchProfile=import_react152.useCallback((newHome,name)=>{rehome(newHome),reset4(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset4,goToTab,gwRestart,toast,gw]),loadEikon=import_react152.useCallback((path7)=>{try{setEikon(parseEikonFile(path7))}catch{setEikon(void 0)}},[]),eikonName=usePref("eikon"),eikonRev=import_react152.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react152.useEffect(()=>{let p=eikonName&&exports_eikon.baked(eikonName)||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonName,eikonRev,skin.skin?.name,loadEikon]);let turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text4),setFocusRegion("input")},[gw]),fork2=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await activateSession(res.session_id),composer2.current?.set(text4),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,activateSession]),msgMenu=import_react152.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react152.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),sendRef=import_react152.useRef(()=>{}),slash3=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,capabilities,info:info3,sid:sid2,title:caption,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,activateSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react152.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sidRef.current,titleRef.current,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve10(cmdsRef.current,name);if("hit"in r)return slash3(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text4=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text4=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text4].filter(Boolean).join(`
4231
+ `):text4;gw.request("prompt.submit",{text:text4}).then(()=>{dispatch({kind:"user",text:withMedia}),setAttachments([]),undone.current=[],setTab(CHAT_TAB)}).catch((e)=>{let msg=e instanceof Error?e.message:String(e);if(BUSY_RE.test(msg)){inflight.current=!0,setQueue((q5)=>[text4,...q5]),setStatus("queued for next turn"),toast.show({variant:"info",message:"queued for next turn"}),setTimeout(()=>{inflight.current=!1,setPulse((n)=>n+1)},400);return}inflight.current=!1,dispatch({kind:"system",text:`submit failed: ${msg}`}),toast.show({variant:"error",message:msg})})},[gw,slash3,attachments,toast]);sendRef.current=send;let onShell=import_react152.useCallback((command)=>{setSplash(!1),dispatch({kind:"system",text:`$ ${command}`}),setStatus("running\u2026"),gw.request("shell.exec",{command}).then((r)=>{let out=(r.stdout??"").trimEnd(),err=(r.stderr??"").trimEnd(),body2=[out,err&&`stderr:
4232
4232
  ${err}`].filter(Boolean).join(`
4233
- `);if(dispatch({kind:"system",text:body2||`(exit ${r.code??0})`}),(r.code??0)!==0)toast.show({variant:"warning",message:`exit ${r.code}`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`})).finally(()=>setStatus(""))},[gw,toast]),onSend=import_react152.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react152.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react152.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react152.useEffect(()=>{if(!capabilities.canDrainQueue||inflight.current||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[capabilities.canDrainQueue,queue,send]);let dequeue=import_react152.useCallback((i)=>{let item=queueRef.current[i];if(item===void 0)return;setQueue((q5)=>q5.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[]),extra=plugins.routes,all2=import_react152.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react152.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react152.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;return next2===cur?prev:{...prev,[tab]:next2}})},[tab]);useAppKeys({tab,tabMax,chatTab:CHAT_TAB,setTab,subCount,cycleSub,focusRegion,setFocusRegion,streaming:turn.streaming,dialogOpen:dialog.open,composer:composer2,onPromptKey:(k2)=>promptRef.current?.feed(k2)??!1,onEscape:()=>{if(!splash||!summoned.current)return!1;return setSplash(!1),summoned.current=!1,!0},onInterrupt:stream.doInterrupt,queued:queue.length,onFlushQueue:stream.doInterrupt,onQuit:()=>quit(renderer,sid2,caption,gw),onQuitArm:(label2)=>toast.show({variant:"info",message:`${label2} again to quit`}),onInterruptNotice:()=>{setEscHint(!0),setTimeout(()=>setEscHint(!1),5000)},onCopyLast:()=>{let m2=[...turnRef.current.messages].reverse().find((x2)=>x2.role==="assistant"&&text(x2));if(m2)copy2(text(m2))},onAttachClipboard:attachClipboard,onDetachLast:()=>{if(attachments.length===0)return!1;return setAttachments((a)=>a.slice(0,-1)),!0},onNotice:(text4)=>dispatch({kind:"system",text:text4}),onToggleSidebar:()=>setHideSidebar((v2)=>!v2),onSteer:openSteer,onStash:()=>{let c=composer2.current,v2=c?.value().trim()??"";if(!v2){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});c?.set(e.text);return}let n=exports_stash.push(v2);c?.set(""),toast.show({variant:"info",message:`stashed (${n})`})},voiceRecordKey:voice.state.recordKey,voiceEnabled:voice.state.enabled,onVoiceRecord:()=>voice.record(sidRef.current)}),useBridge({tab,ready,streaming:turn.streaming,messages:turn.messages,sid:sid2,focusRegion,setTab,setFocusRegion,dispatch,composer:composer2});let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react152.useCallback((id,label2,ok)=>dispatch({kind:"prompt.answered",id,label:label2,ok}),[]),promptWire=import_react152.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react152.useEffect(()=>{if(prompt&&tab!==CHAT_TAB)setTab(CHAT_TAB)},[prompt?.id]);let content=()=>{let inner=(()=>{switch(tab){case CHAT_TAB:return $jsx(Chat,{messages:turn.messages,streaming:turn.streaming,prompt:promptWire,cloud,cloudH,pick:pick2,onResize:setCloudH,onPick,onClose:closeCloud,onRewind:msgMenu});case SESSIONS_TAB:return $jsx(SessionsGroup,{focused:contentFocused,sub:subTabs[SESSIONS_TAB]??0,setSub:sessSub,onSwitch:switchSession,onActivateLive:activateSession,currentId:sid2,messages:turn.messages,sessionStart:sessionStart.current,info:info3??void 0,usage});case AUTOMATION_TAB:return $jsx(Automation,{focused:contentFocused,sub:subTabs[AUTOMATION_TAB]??0,setSub:autoSub,sessionId:sid2,onSwitchProfile:switchProfile});case CONFIG_TAB:return $jsx(ConfigGroup,{focused:contentFocused,sub:subTabs[CONFIG_TAB]??0,setSub:cfgSub});case EIKON_TAB:return $jsx(EikonGroup,{focused:contentFocused,sub:subTabs[EIKON_TAB]??0,setSub:eikSub});default:{let r=extra[tab-TABS.length];return r?r.render():null}}})(),name=all2[tab]?.name??"unknown";return $jsx(import_react152.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react152.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt,sidebarVisible=dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar;return $jsx(import_react152.Profiler,{id:"shell",onRender,children:$jsx(SkinProvider,{value:skin,children:$jsxs("box",{width:"100%",height:"100%",flexDirection:"column",backgroundColor:theme.background,onMouseUp,children:[$jsx(TabBar,{tabs:all2,activeTab:tab,onTabChange:goToTab}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsxs("box",{flexGrow:1,position:"relative",children:[content(),splash&&tab===CHAT_TAB?$jsx(Splash,{info:splashInfo,last:summoned.current?void 0:splashLastProp,composing,news,loading:switching||!info3}):null]}),$jsxs("box",{flexShrink:0,zIndex:1,children:[$jsx(VoiceIndicator,{voice:voice.state,keyLabel:voice.keyLabel}),$jsx(Composer,{ref:composer2,focused:inputFocused,canSubmitPrompt:capabilities.canSubmitPrompt,ready,streaming:turn.streaming,status,model:info3?.model,escHint,queue,attachments,cmds,onSend,onSlash:slash3,onShell,onAttach,onAttachClipboard:attachClipboard,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})]})]}),sidebarVisible?$jsx(import_react152.Profiler,{id:"sidebar",onRender,children:$jsx(Sidebar,{agentState,info:info3,usage,eikon,profile:activeProfileName(),title:caption,cloud:tab===0&&cloud,pulse:turn.streaming,onAvatar,onAvatarHold})}):null]}),plugins.has("app_bottom")?$jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx(plugins.Slot,{name:"app_bottom",mode:"single_winner",sid:sid2,tab,streaming:turn.streaming})}):null]})})})};var EIKON_CLI_USAGE=`herm eikon \u2014 install and manage Herm avatars
4233
+ `);if(dispatch({kind:"system",text:body2||`(exit ${r.code??0})`}),(r.code??0)!==0)toast.show({variant:"warning",message:`exit ${r.code}`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`})).finally(()=>setStatus(""))},[gw,toast]),onSend=import_react152.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react152.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react152.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react152.useEffect(()=>{if(!capabilities.canDrainQueue||inflight.current||hold.current||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[capabilities.canDrainQueue,queue,send,pulse]);let dequeue=import_react152.useCallback((i)=>{let item=queueRef.current[i];if(item===void 0)return;setQueue((q5)=>q5.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[]),extra=plugins.routes,all2=import_react152.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react152.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react152.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;return next2===cur?prev:{...prev,[tab]:next2}})},[tab]);useAppKeys({tab,tabMax,chatTab:CHAT_TAB,setTab,subCount,cycleSub,focusRegion,setFocusRegion,streaming:turn.streaming,dialogOpen:dialog.open,composer:composer2,onPromptKey:(k2)=>promptRef.current?.feed(k2)??!1,onEscape:()=>{if(!splash||!summoned.current)return!1;return setSplash(!1),summoned.current=!1,!0},onInterrupt:stream.doInterrupt,queued:queue.length,onFlushQueue:()=>{hold.current=!0,stream.doInterrupt()},onQuit:()=>quit(renderer,sid2,caption,gw),onQuitArm:(label2)=>toast.show({variant:"info",message:`${label2} again to quit`}),onInterruptNotice:()=>{setEscHint(!0),setTimeout(()=>setEscHint(!1),5000)},onCopyLast:()=>{let m2=[...turnRef.current.messages].reverse().find((x2)=>x2.role==="assistant"&&text(x2));if(m2)copy2(text(m2))},onAttachClipboard:attachClipboard,onDetachLast:()=>{if(attachments.length===0)return!1;return setAttachments((a)=>a.slice(0,-1)),!0},onNotice:(text4)=>dispatch({kind:"system",text:text4}),onToggleSidebar:()=>setHideSidebar((v2)=>!v2),onSteer:openSteer,onStash:()=>{let c=composer2.current,v2=c?.value().trim()??"";if(!v2){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});c?.set(e.text);return}let n=exports_stash.push(v2);c?.set(""),toast.show({variant:"info",message:`stashed (${n})`})},voiceRecordKey:voice.state.recordKey,voiceEnabled:voice.state.enabled,onVoiceRecord:()=>voice.record(sidRef.current)}),useBridge({tab,ready,streaming:turn.streaming,messages:turn.messages,sid:sid2,focusRegion,setTab,setFocusRegion,dispatch,composer:composer2});let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react152.useCallback((id,label2,ok)=>dispatch({kind:"prompt.answered",id,label:label2,ok}),[]),promptWire=import_react152.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react152.useEffect(()=>{if(prompt&&tab!==CHAT_TAB)setTab(CHAT_TAB)},[prompt?.id]);let content=()=>{let inner=(()=>{switch(tab){case CHAT_TAB:return $jsx(Chat,{messages:turn.messages,streaming:turn.streaming,prompt:promptWire,cloud,cloudH,pick:pick2,onResize:setCloudH,onPick,onClose:closeCloud,onRewind:msgMenu});case SESSIONS_TAB:return $jsx(SessionsGroup,{focused:contentFocused,sub:subTabs[SESSIONS_TAB]??0,setSub:sessSub,onSwitch:switchSession,onActivateLive:activateSession,currentId:sid2,messages:turn.messages,sessionStart:sessionStart.current,info:info3??void 0,usage});case AUTOMATION_TAB:return $jsx(Automation,{focused:contentFocused,sub:subTabs[AUTOMATION_TAB]??0,setSub:autoSub,sessionId:sid2,onSwitchProfile:switchProfile});case CONFIG_TAB:return $jsx(ConfigGroup,{focused:contentFocused,sub:subTabs[CONFIG_TAB]??0,setSub:cfgSub});case EIKON_TAB:return $jsx(EikonGroup,{focused:contentFocused,sub:subTabs[EIKON_TAB]??0,setSub:eikSub});default:{let r=extra[tab-TABS.length];return r?r.render():null}}})(),name=all2[tab]?.name??"unknown";return $jsx(import_react152.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react152.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt,sidebarVisible=dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar;return $jsx(import_react152.Profiler,{id:"shell",onRender,children:$jsx(SkinProvider,{value:skin,children:$jsxs("box",{width:"100%",height:"100%",flexDirection:"column",backgroundColor:theme.background,onMouseUp,children:[$jsx(TabBar,{tabs:all2,activeTab:tab,onTabChange:goToTab}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsxs("box",{flexGrow:1,position:"relative",children:[content(),splash&&tab===CHAT_TAB?$jsx(Splash,{info:splashInfo,last:summoned.current?void 0:splashLastProp,composing,news,loading:switching||!info3}):null]}),$jsxs("box",{flexShrink:0,zIndex:1,children:[$jsx(VoiceIndicator,{voice:voice.state,keyLabel:voice.keyLabel}),$jsx(Composer,{ref:composer2,focused:inputFocused,canSubmitPrompt:capabilities.canSubmitPrompt,ready,streaming:turn.streaming,status,model:info3?.model,escHint,queue,attachments,cmds,onSend,onSlash:slash3,onShell,onAttach,onAttachClipboard:attachClipboard,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})]})]}),sidebarVisible?$jsx(import_react152.Profiler,{id:"sidebar",onRender,children:$jsx(Sidebar,{agentState,info:info3,usage,eikon,profile:activeProfileName(),title:caption,cloud:tab===0&&cloud,pulse:turn.streaming,onAvatar,onAvatarHold})}):null]}),plugins.has("app_bottom")?$jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx(plugins.Slot,{name:"app_bottom",mode:"single_winner",sid:sid2,tab,streaming:turn.streaming})}):null]})})})};var EIKON_CLI_USAGE=`herm eikon \u2014 install and manage Herm avatars
4234
4234
 
4235
4235
  Usage:
4236
4236
  herm eikon search [query] [--json]