herm-tui 1.9.0-dev.12 → 1.9.0-dev.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +3 -3
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -4115,7 +4115,7 @@ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid2
|
|
|
4115
4115
|
`,skE);while(end<text3.length&&end>=0){let nl=text3.indexOf(`
|
|
4116
4116
|
`,end+1);if(nl<0){end=text3.length;break}let line2=text3.slice(end+1,nl).trim();if(line2.startsWith("#"))break;if(line2===""){if(text3.slice(nl+1,text3.indexOf(`
|
|
4117
4117
|
`,nl+1)).trim().startsWith("#")){end=nl;break}}end=nl}mark2(skH,end+1,"skills","Skills Catalog",makeSource("skills","skills/"))}let proj=text3.indexOf("# Project Context");if(proj>=0){let conv2=text3.indexOf("Conversation started:");mark2(proj,conv2>proj?conv2:text3.length,"project","Project Context",makeSource("AGENTS.md"))}let conv=text3.indexOf("Conversation started:");if(conv>=0)mark2(conv,text3.length,"meta","Session Metadata");let start=-1;for(let i=0;i<=text3.length;i++)if(i<text3.length&&!used[i]){if(start<0)start=i}else if(start>=0){let slice=text3.slice(start,i);if(slice.trim().length>0)sections.push({id:"other",label:"Other",chars:slice.length,tokens:count2(slice),text:slice});start=-1}return sections.sort((a,b2)=>text3.indexOf(a.text)-text3.indexOf(b2.text))}function classifyTools(tools){let system=[],mcp=[];for(let t2 of tools)if(t2.name.startsWith("mcp_"))mcp.push(t2);else system.push(t2);return{system,mcp}}function toolTokens(tool){return Math.ceil((tool.descriptionLength+tool.paramsLength)/CPT)}function build(opts){let pct=(t2)=>opts.contextLength>0?t2/opts.contextLength*100:0,result=[],byId2=new Map;for(let s of opts.sections)byId2.set(s.id,s);let promptChildren=opts.sections.filter((sec)=>SYSTEM_PROMPT_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),promptTok=promptChildren.reduce((s,c)=>s+c.tokens,0);if(promptTok>0)result.push({id:"system_prompt",label:"System Prompt",tokens:promptTok,percent:pct(promptTok),children:promptChildren});let{system:sysTools,mcp:mcpTools}=classifyTools(opts.tools),sysToolsTok=sysTools.reduce((s,t2)=>s+toolTokens(t2),0);if(sysToolsTok>0)result.push({id:"system_tools",label:"System Tools",tokens:sysToolsTok,percent:pct(sysToolsTok)});let mcpToolsTok=mcpTools.reduce((s,t2)=>s+toolTokens(t2),0);if(mcpToolsTok>0)result.push({id:"mcp_tools",label:"MCP Tools",tokens:mcpToolsTok,percent:pct(mcpToolsTok)});let memChildren=opts.sections.filter((sec)=>MEMORY_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),memTok=memChildren.reduce((s,c)=>s+c.tokens,0);if(memTok>0)result.push({id:"memory",label:"Memory",tokens:memTok,percent:pct(memTok),children:memChildren});let skillsSec=byId2.get("skills"),skillsTok=skillsSec?.tokens??opts.skillsTokens??0;if(skillsTok>0)result.push({id:"skills",label:"Skills",tokens:skillsTok,percent:pct(skillsTok),section:skillsSec});if(opts.conversationTokens>0){let ct=opts.conversationTokens;result.push({id:"conversation",label:"~Conversation",tokens:ct,percent:pct(ct)})}let taken=result.reduce((s,g)=>s+g.tokens,0),used=opts.usedTokens;if(typeof used!=="number"){let unknown2=Math.max(0,opts.contextLength-taken);if(unknown2>0)result.push({id:"unknown",label:"Unknown (live unavailable)",tokens:unknown2,percent:pct(unknown2)});return result}let unknown=Math.max(0,used-taken);if(unknown>0)result.push({id:"unknown",label:"Unknown / Provider Overhead",tokens:unknown,percent:pct(unknown)});let overage=Math.max(0,taken-used);if(overage>0)result.push({id:"overage",label:"Estimate Overage",tokens:overage,percent:pct(overage)});let free=Math.max(0,opts.contextLength-used);return result.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),result}function drill(group2){if(!group2.children||group2.children.length===0)return[];let total=group2.tokens;return group2.children.map((c)=>({...c,percent:total>0?c.tokens/total*100:0}))}function cells(segments,fallback="free"){let filled=segments.flatMap((seg)=>Array.from({length:Math.round(seg.percent/100*GRID)},()=>({id:seg.id}))),pad=Array.from({length:Math.max(0,GRID-filled.length)},()=>({id:fallback}));return[...filled,...pad].slice(0,GRID)}var import_react56=__toESM(require_react_production(),1);var FileLink=import_react56.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react56.useState(!1);return $jsx("box",{height:1,onMouseDown:()=>openFile(source.file),onMouseOver:()=>setHovered(!0),onMouseOut:()=>setHovered(!1),children:$jsx("text",{fg:theme.info,attributes:hovered?TextAttributes.UNDERLINE:TextAttributes.NONE,children:children2??source.label})})}),KVLink=(props)=>{let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx(FileLink,{source:props.source,children:props.text??props.source.label})})]})};var GOLDEN_ANGLE=137.50776405003785;function luminance(c){return 0.299*c.r+0.587*c.g+0.114*c.b}function rgbaToHsl(c){let{r,g,b:b2}=c,max=Math.max(r,g,b2),min=Math.min(r,g,b2),l=(max+min)/2,d2=max-min;if(d2===0)return[0,0,l];let s=l>0.5?d2/(2-max-min):d2/(max+min),h2;switch(max){case r:h2=(g-b2)/d2+(g<b2?6:0);break;case g:h2=(b2-r)/d2+2;break;default:h2=(r-g)/d2+4}return[h2*60,s,l]}function hslToRgba(h2,s,l){if(h2=(h2%360+360)%360/360,s===0)return RGBA.fromValues(l,l,l,1);let q3=l<0.5?l*(1+s):l+s-l*s,p=2*l-q3,ch=(t2)=>{if(t2<0)t2+=1;if(t2>1)t2-=1;if(t2<0.16666666666666666)return p+(q3-p)*6*t2;if(t2<0.5)return q3;if(t2<0.6666666666666666)return p+(q3-p)*(0.6666666666666666-t2)*6;return p};return RGBA.fromValues(ch(h2+0.3333333333333333),ch(h2),ch(h2-0.3333333333333333),1)}function categorical(seed,bg2,n){let[h0]=rgbaToHsl(seed),dark=luminance(bg2)<0.5,s=dark?0.6:0.7,l=dark?0.62:0.42,out=[];for(let i=0;i<n;i++)out.push(hslToRgba(h0+i*GOLDEN_ANGLE,s,l));return out}var DEFAULT_CTX=128000,COLS2=16,SLOTS2=["system_prompt","system_tools","mcp_tools","memory","skills","conversation","soul","mem0","user","project","meta","other","unknown","overage"],SLOT=Object.fromEntries(SLOTS2.map((id,i)=>[id,i])),rampCache=new WeakMap;function ramp2(theme){let r=rampCache.get(theme);if(!r)rampCache.set(theme,r=categorical(theme.primary,theme.background,SLOTS2.length));return r}function clr(id,theme){if(id==="free")return theme.borderSubtle;return ramp2(theme)[SLOT[id]??SLOT.other]}var fmt2=(n)=>{if(n>=1e6)return`${(n/1e6).toFixed(1)}M`;if(n>=1e4)return`${Math.round(n/1000)}k`;if(n>=1000)return`${(n/1000).toFixed(1)}k`;return String(n)},est=(s)=>s?count2(s):0,bar=(pct,w2=20)=>{let f=Math.round(Math.max(0,Math.min(100,pct))/100*w2);return`[${"\u2588".repeat(f)}${"\u2591".repeat(Math.max(0,w2-f))}]`},SectionPanel=import_react57.memo(({seg,theme})=>{let{syntaxStyle}=useTheme(),sec=seg.section;if(!sec)return null;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsxs("text",{children:[sec.chars.toLocaleString()," chars \xB7 ~",fmt2(sec.tokens)," tokens"]}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsx("markdown",{content:sec.text,fg:theme.markdownText,syntaxStyle})]})}),MemoryPanel=import_react57.memo(({seg,theme,label:label2,chars,limit,pct,entries:entries2,source})=>$jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:$jsx("strong",{children:label2})}),source?$jsxs($Fragment,{children:[$jsx("text",{children:" ("}),$jsx(FileLink,{source}),$jsx("text",{children:")"})]}):null]}),$jsxs("text",{children:[chars.toLocaleString()," / ",limit.toLocaleString()," chars (",pct,"%)"]}),$jsxs("text",{children:[bar(pct,25),pct>=95?" \u26A0 near limit":""]}),$jsx("text",{children:" "}),$jsxs("text",{children:[entries2.length," entries:"]}),entries2.map((e,i)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",e]},i))]})),SkillsPanel=import_react57.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line2 of sec.text.split(`
|
|
4118
|
-
`)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react57.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label2=kind2==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind2==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind2,theme),children:"\u25FC"})," ",label2," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react57.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react57.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),toolsFromInfo=(info)=>{if(!info||info.tools===void 0)return null;let tools=Object.entries(info.tools).flatMap(([group2,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group2.length})));return{source:makeSource("state.db","session.info"),tools}},configuredContextLength=(config)=>{let n=config?.model?.context_length;return typeof n==="number"&&n>0?n:void 0},contextMeter=(usage,info,config)=>({max:usage?.context_max??info?.usage?.context_max??info?.context_max??configuredContextLength(config)??DEFAULT_CTX,used:usage?.context_used??info?.usage?.context_used??info?.context_used}),Context=import_react57.memo(({messages=NO_MESSAGES,info,usage,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),[wire,setWire]=import_react57.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react57.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react57.useState(null),[selected,setSelected]=import_react57.useState(null),[drilled,setDrilled]=import_react57.useState(null);import_react57.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let meter=contextMeter(usage,info,config??null),ctxLen=meter.max,used=meter.used,reliable=typeof used==="number",output=wire.output,pct=reliable&&ctxLen>0?Math.round(used/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react57.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react57.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react57.useMemo(()=>{let liveTools=toolsFromInfo(info);if(liveTools)return liveTools;if(info?.tools!==void 0)return liveTools;return toolsInfo},[info,toolsInfo]),top=import_react57.useMemo(()=>build({contextLength:ctxLen,usedTokens:used,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,used,sections,convTok,currentTools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react57.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":reliable?"free":"unknown"),[view,drilledGroup,reliable]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react57.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react57.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react57.useRef(0),segs=view.filter((s)=>s.tokens>0),idx=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&¤tTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&¤tTools){let{mcp}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):reliable?$jsx("span",{fg:theme.info,children:" (click group to expand)"}):$jsxs("span",{fg:theme.warning,children:[" \xB7 live usage unavailable \xB7 limit ",fmt2(ctxLen)]})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,reliable&&!drilled?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})}):null]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:reliable?"\u2191\u2193 nav \xB7 click a group to drill in":"live usage unavailable \xB7 estimates shown with ~",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:reliable?`Context \xB7 ${fmt2(used)} / ${fmt2(ctxLen)} (${pct}%)`:`Context \xB7 live usage unavailable \xB7 limit ${fmt2(ctxLen)}`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[!drilled&&compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row3)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row3*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=!drilled&&row3*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row3))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react59=__toESM(require_react_production(),1);init_hermes_analytics();var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react59.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react59.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc5(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react59.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react59.useState(7),[data2,setData]=import_react59.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react59.useState(()=>cache3.get(days)?.byTool??null),[tick3,setTick]=import_react59.useState(0),gen=import_react59.useRef(0);import_react59.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick3]);let keys=useKeys();useKeyboard((key2)=>{if(!props.focused)return;if(keys.match("list.refresh",key2))return cache3.delete(days),setTick((n)=>n+1);if(key2.raw==="1")return setDays(1);if(key2.raw==="7")return setDays(7);if(key2.raw==="3")return setDays(30);if(key2.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react59.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc5(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react61=__toESM(require_react_production(),1);var SubTabBar=import_react61.memo((props)=>$jsx(TabStrip,{...props}));var TABS=[{name:"Chat",description:"Main chat interface"},{name:"Sessions",description:"Sessions, context, analytics"},{name:"Profiles & Automation",description:"Profiles, cron jobs, kanban boards"},{name:"Config",description:"Config, env, skills, toolsets, memory"},{name:"Eikon",description:"Avatar studio & gallery"}],TAB_MAX=TABS.length-1,CHAT_TAB=0,SESSIONS_TAB=1,AUTOMATION_TAB=2,CONFIG_TAB=3,EIKON_TAB=4,SUB_TABS={[1]:["List","Context","Analytics"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Gallery","Studio","Marketplace"]},TAB_SLASH={chat:{tab:0,sub:0},sessions:{tab:1,sub:0},context:{tab:1,sub:1},analytics:{tab:1,sub:2},insights:{tab:1,sub:2},kanban:{tab:2,sub:0},automation:{tab:2,sub:0},profiles:{tab:2,sub:1},agents:{tab:2,sub:1},cron:{tab:2,sub:2},config:{tab:3,sub:0},skills:{tab:3,sub:1},toolsets:{tab:3,sub:2},env:{tab:3,sub:3},memory:{tab:3,sub:4},studio:{tab:4,sub:1},gallery:{tab:4,sub:0},marketplace:{tab:4,sub:2}};var SessionsGroup=import_react62.memo((props)=>{let labels=SUB_TABS[SESSIONS_TAB];import_react62.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info,usage:props.usage})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react82=__toESM(require_react_production(),1);var import_react74=__toESM(require_react_production(),1);var acc=new Map;function record(ev,p){let id=p.subagent_id;if(!id)return;let now=Date.now()/1000;if(ev==="start"){acc.set(id,{subagent_id:id,parent_id:p.parent_id??null,depth:p.depth??0,goal:p.goal,model:p.model,started_at:now,tool_count:0,status:"running",trail:[]});return}let r=acc.get(id);if(!r)return;if(ev==="tool"&&p.tool_name){r.tool_count++,r.trail=[...r.trail??[],{name:p.tool_name,preview:p.tool_preview}].slice(-20);return}if(ev==="complete")r.status=p.status??"completed",r.finished_at=now,r.input_tokens=p.input_tokens,r.output_tokens=p.output_tokens,r.cost_usd=p.cost_usd}function trail(id){return acc.get(id)?.trail??[]}function flush(gw,sessionId){if(acc.size===0)return;let subagents=[...acc.values()];acc.clear();let label2=(subagents.filter((s)=>s.parent_id==null).slice(0,2).map((s)=>s.goal).join(" \xB7 ")||`${subagents.length} subagents`).slice(0,120),started=Math.min(...subagents.map((s)=>s.started_at));gw.request("spawn_tree.save",{session_id:sessionId,label:label2,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react65=__toESM(require_react_production(),1);var import_react63=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react63.useState(""),[cursor,setCursor]=import_react63.useState(0),mode=import_react63.useRef("kb"),moved=import_react63.useRef(!1),sb=import_react63.useRef(null),theme=useTheme().theme,filtered=import_react63.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react63.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]),rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react63.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react63.useEffect(()=>{if(!props.current){setCursor(0);return}let i=filtered.findIndex((o)=>o.value===props.current),n=Math.max(0,i);setCursor(n),scrollTo(n)},[props.current,filtered]),import_react63.useEffect(()=>{if(!moved.current)return;moved.current=!1;let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key2)=>{let onToggle=!filterable?()=>{let item=filtered[cursor];if(item)props.onSelect(item)}:void 0;if(handleListKey(keys,key2,{count:filtered.length,setSel:(fn)=>{mode.current="kb",moved.current=!0,setCursor(fn)},scrollTo,page:Math.max(1,(sb.current?.viewport.height??10)-1),onActivate:()=>{let item=filtered[cursor];if(item)props.onSelect(item)},onToggle}))return;if(props.onKey?.(key2))return});let idx=0,entries2=Array.from(groups.entries());return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),filterable?$jsxs($Fragment,{children:[$jsx("input",{value:filter,onInput:(v2)=>{mode.current="kb",setFilter(v2)},placeholder:props.placeholder??"Type to filter...",focused:!0,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{height:1})]}):null,$jsxs("scrollbox",{ref:sb,scrollY:!0,maxHeight:16,focused:!filterable,contentOptions:{flexDirection:"column"},paddingRight:1,children:[filtered.length===0?$jsx("text",{fg:theme.textMuted,children:"No results found"}):null,entries2.map(([cat,items])=>{let elements=[];if(cat)elements.push($jsx("text",{fg:theme.textMuted,children:$jsx("strong",{children:cat})},`cat-${cat}`));return items.forEach((item)=>{let i=idx++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>{mode.current="mouse",moved.current=!0,setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")moved.current=!0,setCursor(i)},onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react65.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react65.useRef(new Map),enabled2=import_react65.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react65.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react65.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react65.useCallback((val)=>{enabled2.current=val},[]),open2=import_react65.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key2)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key2))return open2();for(let c of all())if(c.action&&keys.match(c.action,key2))return c.onSelect()});let value=import_react65.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="error"?theme.error:s==="timeout"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc5(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{let entries2=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries2.length?"filter\u2026":"no saved spawn trees",options:entries2.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc5(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries2.find((e)=>e.path===opt.value);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react68=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.accept",key2))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Required"})}),req.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null,opt.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react68.useState(!1);useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.deny",key2))return props.done(null);if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.done(force);if(key2.name==="space"||key2.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react70=__toESM(require_react_production(),1);import{existsSync as existsSync14,readFileSync as readFileSync7}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join11,basename as basename10,dirname as dirname8}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join11(home3(),".hermes");function root(){let hh=hermesHome(),parent2=dirname8(hh);return basename10(parent2)==="profiles"?dirname8(parent2):hh}function profileNameFrom(hh){let parent2=dirname8(hh);return basename10(parent2)==="profiles"?basename10(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync7(join11(root(),"active_profile"),"utf-8").trim()||null}catch{return null}}var ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/;function readModel(dir){try{let raw=readFileSync7(join11(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean2=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean2(m2),clean2(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join11(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync7(join11(dir,"gateway.pid"),"utf-8").trim(),pid2=raw.startsWith("{")?Number(JSON.parse(raw).pid):Number(raw);if(!Number.isFinite(pid2)||pid2<=0)return!1;return process.kill(pid2,0),!0}catch{return!1}}function soul(dir){try{return readFileSync7(join11(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join11(dir,"distribution.yaml");if(!existsSync14(path7))return null;let data2=(()=>{try{return $parse(readFileSync7(path7,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src2=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join11(home3(),".local","bin",name);return{name,path:dir,is_default:name==="default",is_active:name===active,is_sticky:name===sticky,gateway_running:gatewayRunning(dir),model,provider,has_env:existsSync14(join11(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync14(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src2(dir,dir.replace(home3()+"/","~/")),config:src2(join11(dir,"config.yaml"),"config.yaml"),soul:src2(join11(dir,"SOUL.md"),"SOUL.md"),env:src2(join11(dir,".env"),".env"),distribution:src2(join11(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync14(r))jobs.push(info("default",r,active,sticky));let pr=join11(r,"profiles");if(existsSync14(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join11(pr,e.name),active,sticky))}return Promise.all(jobs)}function validateName(name,existing){if(!ID_RE.test(name))return"must match [a-z0-9][a-z0-9_-]{0,63}";if(existing.includes(name))return"already exists";if(["hermes","default","test","tmp","root","sudo"].includes(name))return"reserved name";return null}function readPrefs(dir){try{let raw=JSON.parse(readFileSync7(join11(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikon??(raw.eikonPath?basename10(raw.eikonPath,".eikon"):void 0),keys:raw.keys?Object.keys(raw.keys).length:0}}catch{return null}}async function profileStats(dir){let sessions=null,messages=null,dbPath=join11(dir,"state.db");if(existsSync14(dbPath))try{let db=new Database2(dbPath,{readwrite:!0,create:!1}),r=db.query("SELECT COUNT(*) AS s FROM sessions WHERE message_count > 0").get(),m2=db.query("SELECT COALESCE(SUM(message_count), 0) AS m FROM sessions").get();sessions=r.s,messages=m2.m,db.close()}catch{}let crons=null;try{let jobs=await Bun.file(join11(dir,"cron","jobs.json")).json();crons=Array.isArray(jobs)?jobs.length:jobs&&typeof jobs==="object"&&Array.isArray(jobs.jobs)?jobs.jobs.length:0}catch{crons=existsSync14(join11(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react70.useState(""),[cloneIdx,setCloneIdx]=import_react70.useState(0),[alias,setAlias]=import_react70.useState(!0),[field,setField]=import_react70.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit2=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key2)=>{if(key2.name==="escape")return done(null);if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="return")return submit2();if(field==="name"){if(key2.name==="backspace")return setName((n)=>n.slice(0,-1));if(key2.raw&&key2.raw.length===1&&/[a-z0-9_-]/.test(key2.raw))return setName((n)=>n+key2.raw);return}if(field==="clone"){if(key2.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key2.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key2.name==="space"||key2.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react72=__toESM(require_react_production(),1);import{rmSync as rmSync2,mkdtempSync as mkdtempSync2}from"fs";import{join as join12}from"path";import{tmpdir as tmpdir2}from"os";var shq=(s)=>`'${s.replace(/'/g,"'\\''")}'`;function openInstallDistribution(dialog,gw){return new Promise((resolve4)=>{askSource(dialog,gw,(r)=>{dialog.clear(),resolve4(r)})})}function askSource(dialog,gw,done){dialog.replace($jsx(Step1,{onSubmit:(source)=>preview(dialog,gw,source,done),onCancel:()=>done(null)}))}async function preview(dialog,gw,source,done){let tmp=mkdtempSync2(join12(tmpdir2(),"herm-dist-preview-")),cleanup=()=>{try{rmSync2(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest2=readDistributionManifest(tmp);if(!manifest2){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest:manifest2,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react72.useState("");return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key2)=>{if(keys.match("dialog.accept",key2)||keys.match("dialog.cancel",key2))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react72.useState(""),[alias,setAlias]=import_react72.useState(!1),[field,setField]=import_react72.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel();if(key2.name==="tab")return move(key2.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key2))return fire();if(field==="alias"&&(key2.name==="space"||key2.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react74.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react74.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react74.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react74.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react74.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react74.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc5(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react74.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc5(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc5(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react74.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react74.useState("profiles"),[pView,setPView]=import_react74.useState("list"),[profiles,setProfiles]=import_react74.useState([]),[deleg,setDeleg]=import_react74.useState(null),[liveMap,setLiveMap]=import_react74.useState(()=>new Map),[now,setNow]=import_react74.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react74.useState(0),[dSel,setDSel]=import_react74.useState(0),[err,setErr]=import_react74.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react74.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react74.useRef(void 0),[stats,setStats]=import_react74.useState(()=>new Map),[sticky,setSticky]=import_react74.useState(stickyDefault),loadProfiles=import_react74.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react74.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react74.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react74.useEffect(loadDeleg,[loadDeleg]),import_react74.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react74.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react74.useCallback((i)=>setPSel(i),[]),dHover=import_react74.useCallback((i)=>setDSel(i),[]),pDelete=import_react74.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
|
|
4118
|
+
`)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react57.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label2=kind2==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind2==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind2,theme),children:"\u25FC"})," ",label2," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react57.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react57.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),toolsFromInfo=(info)=>{if(!info||info.tools===void 0)return null;let tools=Object.entries(info.tools).flatMap(([group2,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group2.length})));return{source:makeSource("state.db","session.info"),tools}},configuredContextLength=(config)=>{let n=config?.model?.context_length;return typeof n==="number"&&n>0?n:void 0},contextMeter=(usage,info,config)=>({max:usage?.context_max??info?.usage?.context_max??info?.context_max??configuredContextLength(config)??DEFAULT_CTX,used:usage?.context_used??info?.usage?.context_used??info?.context_used}),Context=import_react57.memo(({messages=NO_MESSAGES,info,usage,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),[wire,setWire]=import_react57.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react57.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react57.useState(null),[selected,setSelected]=import_react57.useState(null),[drilled,setDrilled]=import_react57.useState(null);import_react57.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let meter=contextMeter(usage,info,config??null),ctxLen=meter.max,used=meter.used,reliable=typeof used==="number",output=wire.output,pct=reliable&&ctxLen>0?Math.round(used/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react57.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react57.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react57.useMemo(()=>{let liveTools=toolsFromInfo(info);if(liveTools)return liveTools;if(info?.tools!==void 0)return liveTools;return toolsInfo},[info,toolsInfo]),top=import_react57.useMemo(()=>build({contextLength:ctxLen,usedTokens:used,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,used,sections,convTok,currentTools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react57.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":reliable?"free":"unknown"),[view,drilledGroup,reliable]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react57.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react57.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react57.useRef(0),segs=view.filter((s)=>s.tokens>0),idx=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&¤tTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&¤tTools){let{mcp}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):reliable?$jsx("span",{fg:theme.info,children:" (click group to expand)"}):$jsxs("span",{fg:theme.warning,children:[" \xB7 live usage unavailable \xB7 limit ",fmt2(ctxLen)]})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,reliable&&!drilled?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})}):null]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:reliable?"\u2191\u2193 nav \xB7 click a group to drill in":"live usage unavailable \xB7 estimates shown with ~",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:reliable?`Context \xB7 ${fmt2(used)} / ${fmt2(ctxLen)} (${pct}%)`:`Context \xB7 live usage unavailable \xB7 limit ${fmt2(ctxLen)}`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[!drilled&&compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row3)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row3*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=!drilled&&row3*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row3))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react59=__toESM(require_react_production(),1);init_hermes_analytics();var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react59.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react59.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc5(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react59.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react59.useState(7),[data2,setData]=import_react59.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react59.useState(()=>cache3.get(days)?.byTool??null),[tick3,setTick]=import_react59.useState(0),gen=import_react59.useRef(0);import_react59.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick3]);let keys=useKeys();useKeyboard((key2)=>{if(!props.focused)return;if(keys.match("list.refresh",key2))return cache3.delete(days),setTick((n)=>n+1);if(key2.raw==="1")return setDays(1);if(key2.raw==="7")return setDays(7);if(key2.raw==="3")return setDays(30);if(key2.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react59.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc5(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react61=__toESM(require_react_production(),1);var SubTabBar=import_react61.memo((props)=>$jsx(TabStrip,{...props}));var TABS=[{name:"Chat",description:"Main chat interface"},{name:"Sessions",description:"Sessions, context, analytics"},{name:"Profiles & Automation",description:"Profiles, cron jobs, kanban boards"},{name:"Config",description:"Config, env, skills, toolsets, memory"},{name:"Eikon",description:"Avatar studio & gallery"}],TAB_MAX=TABS.length-1,CHAT_TAB=0,SESSIONS_TAB=1,AUTOMATION_TAB=2,CONFIG_TAB=3,EIKON_TAB=4,SUB_TABS={[1]:["List","Context","Analytics"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Gallery","Studio","Marketplace"]},TAB_SLASH={chat:{tab:0,sub:0},sessions:{tab:1,sub:0},context:{tab:1,sub:1},analytics:{tab:1,sub:2},insights:{tab:1,sub:2},kanban:{tab:2,sub:0},automation:{tab:2,sub:0},profiles:{tab:2,sub:1},agents:{tab:2,sub:1},cron:{tab:2,sub:2},config:{tab:3,sub:0},skills:{tab:3,sub:1},toolsets:{tab:3,sub:2},env:{tab:3,sub:3},memory:{tab:3,sub:4},studio:{tab:4,sub:1},gallery:{tab:4,sub:0},marketplace:{tab:4,sub:2}};var SessionsGroup=import_react62.memo((props)=>{let labels=SUB_TABS[SESSIONS_TAB];import_react62.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info,usage:props.usage})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react82=__toESM(require_react_production(),1);var import_react74=__toESM(require_react_production(),1);var acc=new Map;function record(ev,p){let id=p.subagent_id;if(!id)return;let now=Date.now()/1000;if(ev==="start"){acc.set(id,{subagent_id:id,parent_id:p.parent_id??null,depth:p.depth??0,goal:p.goal,model:p.model,started_at:now,tool_count:0,status:"running",trail:[]});return}let r=acc.get(id);if(!r)return;if(ev==="tool"&&p.tool_name){r.tool_count++,r.trail=[...r.trail??[],{name:p.tool_name,preview:p.tool_preview}].slice(-20);return}if(ev==="complete")r.status=p.status??"completed",r.finished_at=now,r.input_tokens=p.input_tokens,r.output_tokens=p.output_tokens,r.cost_usd=p.cost_usd}function trail(id){return acc.get(id)?.trail??[]}function flush(gw,sessionId){if(acc.size===0)return;let subagents=[...acc.values()];acc.clear();let label2=(subagents.filter((s)=>s.parent_id==null).slice(0,2).map((s)=>s.goal).join(" \xB7 ")||`${subagents.length} subagents`).slice(0,120),started=Math.min(...subagents.map((s)=>s.started_at));gw.request("spawn_tree.save",{session_id:sessionId,label:label2,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react65=__toESM(require_react_production(),1);var import_react63=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react63.useState(""),[cursor,setCursor]=import_react63.useState(0),mode=import_react63.useRef("kb"),moved=import_react63.useRef(!1),sb=import_react63.useRef(null),theme=useTheme().theme,opts=import_react63.useMemo(()=>props.options.map((o)=>({name:`${props.current==null?"":o.value===props.current?"\u25CF ":" "}${o.title}`,description:o.hint?[o.description,o.hint].filter(Boolean).join(" \u2014 "):o.description??"",value:o.value})),[props.current,props.options]),sel=props.current==null?0:Math.max(0,props.options.findIndex((o)=>o.value===props.current)),desc=props.options.some((o)=>!!o.description||!!o.hint),filtered=import_react63.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react63.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]),rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react63.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react63.useEffect(()=>{if(!props.current){setCursor(0);return}let i=filtered.findIndex((o)=>o.value===props.current),n=Math.max(0,i);setCursor(n),scrollTo(n)},[props.current,filtered]),import_react63.useEffect(()=>{if(!moved.current)return;moved.current=!1;let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key2)=>{if(!filterable)return;if(handleListKey(keys,key2,{count:filtered.length,setSel:(fn)=>{mode.current="kb",moved.current=!0,setCursor(fn)},scrollTo,page:Math.max(1,(sb.current?.viewport.height??10)-1),onActivate:()=>{let item=filtered[cursor];if(item)props.onSelect(item)}}))return;if(props.onKey?.(key2))return});let idx=0,entries2=Array.from(groups.entries());if(!filterable)return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),$jsx("select",{focused:!0,width:58,height:Math.min(16,Math.max(1,props.options.length*(desc?2:1))),options:opts,selectedIndex:sel,showDescription:desc,showScrollIndicator:props.options.length>8,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,fastScrollStep:Math.max(1,props.options.length),keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"pageup",action:"move-up-fast"},{name:"pagedown",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"}],onChange:(i)=>{let item=props.options[i];if(item&&props.onMove)props.onMove(item)},onSelect:(i)=>{let item=props.options[i];if(item)props.onSelect(item)}}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]});return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),filterable?$jsxs($Fragment,{children:[$jsx("input",{value:filter,onInput:(v2)=>{mode.current="kb",setFilter(v2)},placeholder:props.placeholder??"Type to filter...",focused:!0,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{height:1})]}):null,$jsxs("scrollbox",{ref:sb,scrollY:!0,maxHeight:16,focused:!filterable,contentOptions:{flexDirection:"column"},paddingRight:1,children:[filtered.length===0?$jsx("text",{fg:theme.textMuted,children:"No results found"}):null,entries2.map(([cat,items])=>{let elements=[];if(cat)elements.push($jsx("text",{fg:theme.textMuted,children:$jsx("strong",{children:cat})},`cat-${cat}`));return items.forEach((item)=>{let i=idx++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>{mode.current="mouse",moved.current=!0,setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")moved.current=!0,setCursor(i)},onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react65.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react65.useRef(new Map),enabled2=import_react65.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react65.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react65.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react65.useCallback((val)=>{enabled2.current=val},[]),open2=import_react65.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key2)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key2))return open2();for(let c of all())if(c.action&&keys.match(c.action,key2))return c.onSelect()});let value=import_react65.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="error"?theme.error:s==="timeout"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc5(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{let entries2=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries2.length?"filter\u2026":"no saved spawn trees",options:entries2.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc5(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries2.find((e)=>e.path===opt.value);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react68=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.accept",key2))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Required"})}),req.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null,opt.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react68.useState(!1);useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.deny",key2))return props.done(null);if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.done(force);if(key2.name==="space"||key2.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react70=__toESM(require_react_production(),1);import{existsSync as existsSync14,readFileSync as readFileSync7}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join11,basename as basename10,dirname as dirname8}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join11(home3(),".hermes");function root(){let hh=hermesHome(),parent2=dirname8(hh);return basename10(parent2)==="profiles"?dirname8(parent2):hh}function profileNameFrom(hh){let parent2=dirname8(hh);return basename10(parent2)==="profiles"?basename10(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync7(join11(root(),"active_profile"),"utf-8").trim()||null}catch{return null}}var ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/;function readModel(dir){try{let raw=readFileSync7(join11(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean2=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean2(m2),clean2(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join11(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync7(join11(dir,"gateway.pid"),"utf-8").trim(),pid2=raw.startsWith("{")?Number(JSON.parse(raw).pid):Number(raw);if(!Number.isFinite(pid2)||pid2<=0)return!1;return process.kill(pid2,0),!0}catch{return!1}}function soul(dir){try{return readFileSync7(join11(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join11(dir,"distribution.yaml");if(!existsSync14(path7))return null;let data2=(()=>{try{return $parse(readFileSync7(path7,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src2=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join11(home3(),".local","bin",name);return{name,path:dir,is_default:name==="default",is_active:name===active,is_sticky:name===sticky,gateway_running:gatewayRunning(dir),model,provider,has_env:existsSync14(join11(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync14(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src2(dir,dir.replace(home3()+"/","~/")),config:src2(join11(dir,"config.yaml"),"config.yaml"),soul:src2(join11(dir,"SOUL.md"),"SOUL.md"),env:src2(join11(dir,".env"),".env"),distribution:src2(join11(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync14(r))jobs.push(info("default",r,active,sticky));let pr=join11(r,"profiles");if(existsSync14(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join11(pr,e.name),active,sticky))}return Promise.all(jobs)}function validateName(name,existing){if(!ID_RE.test(name))return"must match [a-z0-9][a-z0-9_-]{0,63}";if(existing.includes(name))return"already exists";if(["hermes","default","test","tmp","root","sudo"].includes(name))return"reserved name";return null}function readPrefs(dir){try{let raw=JSON.parse(readFileSync7(join11(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikon??(raw.eikonPath?basename10(raw.eikonPath,".eikon"):void 0),keys:raw.keys?Object.keys(raw.keys).length:0}}catch{return null}}async function profileStats(dir){let sessions=null,messages=null,dbPath=join11(dir,"state.db");if(existsSync14(dbPath))try{let db=new Database2(dbPath,{readwrite:!0,create:!1}),r=db.query("SELECT COUNT(*) AS s FROM sessions WHERE message_count > 0").get(),m2=db.query("SELECT COALESCE(SUM(message_count), 0) AS m FROM sessions").get();sessions=r.s,messages=m2.m,db.close()}catch{}let crons=null;try{let jobs=await Bun.file(join11(dir,"cron","jobs.json")).json();crons=Array.isArray(jobs)?jobs.length:jobs&&typeof jobs==="object"&&Array.isArray(jobs.jobs)?jobs.jobs.length:0}catch{crons=existsSync14(join11(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react70.useState(""),[cloneIdx,setCloneIdx]=import_react70.useState(0),[alias,setAlias]=import_react70.useState(!0),[field,setField]=import_react70.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit2=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key2)=>{if(key2.name==="escape")return done(null);if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="return")return submit2();if(field==="name"){if(key2.name==="backspace")return setName((n)=>n.slice(0,-1));if(key2.raw&&key2.raw.length===1&&/[a-z0-9_-]/.test(key2.raw))return setName((n)=>n+key2.raw);return}if(field==="clone"){if(key2.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key2.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key2.name==="space"||key2.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react72=__toESM(require_react_production(),1);import{rmSync as rmSync2,mkdtempSync as mkdtempSync2}from"fs";import{join as join12}from"path";import{tmpdir as tmpdir2}from"os";var shq=(s)=>`'${s.replace(/'/g,"'\\''")}'`;function openInstallDistribution(dialog,gw){return new Promise((resolve4)=>{askSource(dialog,gw,(r)=>{dialog.clear(),resolve4(r)})})}function askSource(dialog,gw,done){dialog.replace($jsx(Step1,{onSubmit:(source)=>preview(dialog,gw,source,done),onCancel:()=>done(null)}))}async function preview(dialog,gw,source,done){let tmp=mkdtempSync2(join12(tmpdir2(),"herm-dist-preview-")),cleanup=()=>{try{rmSync2(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest2=readDistributionManifest(tmp);if(!manifest2){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest:manifest2,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react72.useState("");return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key2)=>{if(keys.match("dialog.accept",key2)||keys.match("dialog.cancel",key2))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react72.useState(""),[alias,setAlias]=import_react72.useState(!1),[field,setField]=import_react72.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel();if(key2.name==="tab")return move(key2.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key2))return fire();if(field==="alias"&&(key2.name==="space"||key2.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react74.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react74.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react74.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react74.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react74.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react74.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc5(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react74.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc5(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc5(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react74.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react74.useState("profiles"),[pView,setPView]=import_react74.useState("list"),[profiles,setProfiles]=import_react74.useState([]),[deleg,setDeleg]=import_react74.useState(null),[liveMap,setLiveMap]=import_react74.useState(()=>new Map),[now,setNow]=import_react74.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react74.useState(0),[dSel,setDSel]=import_react74.useState(0),[err,setErr]=import_react74.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react74.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react74.useRef(void 0),[stats,setStats]=import_react74.useState(()=>new Map),[sticky,setSticky]=import_react74.useState(stickyDefault),loadProfiles=import_react74.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react74.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react74.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react74.useEffect(loadDeleg,[loadDeleg]),import_react74.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react74.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react74.useCallback((i)=>setPSel(i),[]),dHover=import_react74.useCallback((i)=>setDSel(i),[]),pDelete=import_react74.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
|
|
4119
4119
|
|
|
4120
4120
|
Its gateway is running and will be stopped first (may take up to ~10s).`:"";if(!await openConfirm(dialog,{title:"Delete Profile?",body:`'${p.name}' \u2014 config, env, memory, skills, and sessions will be removed. This cannot be undone.${warn}`,yes:"delete",danger:!0}))return;sh(`hermes profile delete ${p.name} -y`).then(()=>{toast.show({variant:"success",message:`Deleted '${p.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,dialog,toast,loadProfiles]),pSwitch=import_react74.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_active||!props.onSwitchProfile)return;if(await openConfirm(dialog,{title:`Switch to '${p.name}'?`,body:"The gateway restarts under this profile's HERMES_HOME. The current session ends (it stays in the outgoing profile's history).",yes:"switch"}))props.onSwitchProfile(p.path,p.name)},[dialog,props.onSwitchProfile]),pUpdate=import_react74.useCallback((p,force)=>{let cmd2=`hermes profile update ${p.name} -y${force?" --force-config":""}`;toast.show({variant:"info",message:`Updating '${p.name}'\u2026`}),sh(cmd2).then(()=>{if(toast.show({variant:"success",message:`Updated '${p.name}'`}),p.is_active&&props.onSwitchProfile){props.onSwitchProfile(p.path,p.name);return}loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,toast,loadProfiles,props.onSwitchProfile]),pEnter=import_react74.useCallback((i)=>{setPSel(i);let p=live.current.profiles[i];if(!p)return;openProfileMenu(dialog,p,{switch:props.onSwitchProfile?()=>pSwitch(i):void 0,sticky:(pp)=>sh(`hermes profile use ${pp.name}`).then(()=>{toast.show({variant:"success",message:`Sticky default \u2192 '${pp.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),unsticky:()=>sh("hermes profile use --clear").then(()=>{toast.show({variant:"info",message:"Cleared sticky default"}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),export:(pp)=>sh(`hermes profile export ${pp.name}`).then((out)=>toast.show({variant:"success",message:trunc5(out.trim()||`Exported '${pp.name}'`,80)})).catch((e)=>toast.show({variant:"error",message:e.message})),remove:()=>pDelete(i),update:(pp,force)=>pUpdate(pp,force)})},[sh,dialog,toast,loadProfiles,pDelete,pSwitch,pUpdate,props.onSwitchProfile]),dKill=import_react74.useCallback(async(i)=>{let r=live.current.active[i];if(!r)return;if(!await openConfirm(dialog,{title:"Interrupt subagent?",body:`${trunc5(r.goal,120)}
|
|
4121
4121
|
|
|
@@ -4127,12 +4127,12 @@ The child returns whatever partial result it has so far.`,yes:"interrupt",danger
|
|
|
4127
4127
|
FROM task_events WHERE task_id = ? ORDER BY id DESC LIMIT ?`).all(id,EVENT_TAIL).map(toEvent).reverse()}catch{return[]}},latestSummary=(conn2,id)=>{try{return conn2.query(`SELECT summary FROM task_runs
|
|
4128
4128
|
WHERE task_id = ? AND summary IS NOT NULL AND summary != ''
|
|
4129
4129
|
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=statSync4(path7).size,want=Math.min(size,bytes),fd=openSync3(path7,"r"),buf=Buffer.alloc(want);readSync3(fd,buf,0,want,size-want),closeSync3(fd);let out=buf.toString("utf-8");if(size>bytes){let nl=out.indexOf(`
|
|
4130
|
-
`);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 readdirSync6(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=openSync3(path7,"r");try{let buf=Buffer.alloc(4);if(readSync3(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{closeSync3(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(""),[catalog2,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 catalog2){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},[catalog2,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((key2)=>{if(picker){if(key2.name==="escape")setPicker(picker.kind==="dirPath"?{kind:"workspace"}:null);return}if(key2.name==="escape")return p.done(null);if(key2.name==="return"){if(key2.ctrl)return submit2();if(field!=="body")return submit2();return}if(field==="skills"){if(key2.name==="tab"){if(!key2.shift&&commitMatch())return;return moveField(key2.shift?-1:1)}if(key2.name==="backspace"){if(filter.length>0)return setFilter((f)=>f.slice(0,-1));return popSkill()}if(key2.name==="up"){if(matches.length>0)return setMatchIdx((i)=>Math.max(0,i-1));return moveField(-1)}if(key2.name==="down"){if(matches.length>0)return setMatchIdx((i)=>Math.min(matches.length-1,i+1));return moveField(1)}if(key2.raw&&key2.raw.length===1&&/[A-Za-z0-9_\-/ ]/.test(key2.raw))setFilter((f)=>f+key2.raw),setMatchIdx(0);return}if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="up"){if(field==="body"){if((body.current?.logicalCursor.row??0)>0)return}return moveField(-1)}if(key2.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(key2.name==="return"||key2.name==="space")return setMore((m2)=>!m2);return}if(field==="triage"&&key2.name==="space")return setTriage((t2)=>!t2);if(SELECTY.has(field)&&key2.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 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"),dispatchJson=(out)=>{try{let raw=JSON.parse(out);return recOf(raw)}catch{return null}},countOf=(xs)=>Array.isArray(xs)?xs.length:0;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")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.id})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 worker log (tail)`})]})}),$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||"";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"?"\u2191\u2193 / Enter":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.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(`
|
|
4130
|
+
`);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 readdirSync6(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=openSync3(path7,"r");try{let buf=Buffer.alloc(4);if(readSync3(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{closeSync3(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(""),[catalog2,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 catalog2){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},[catalog2,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((key2)=>{if(picker){if(key2.name==="escape")setPicker(picker.kind==="dirPath"?{kind:"workspace"}:null);return}if(key2.name==="escape")return p.done(null);if(key2.name==="return"){if(key2.ctrl)return submit2();if(field!=="body")return submit2();return}if(field==="skills"){if(key2.name==="tab"){if(!key2.shift&&commitMatch())return;return moveField(key2.shift?-1:1)}if(key2.name==="backspace"){if(filter.length>0)return setFilter((f)=>f.slice(0,-1));return popSkill()}if(key2.name==="up"){if(matches.length>0)return setMatchIdx((i)=>Math.max(0,i-1));return moveField(-1)}if(key2.name==="down"){if(matches.length>0)return setMatchIdx((i)=>Math.min(matches.length-1,i+1));return moveField(1)}if(key2.raw&&key2.raw.length===1&&/[A-Za-z0-9_\-/ ]/.test(key2.raw))setFilter((f)=>f+key2.raw),setMatchIdx(0);return}if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="up"){if(field==="body"){if((body.current?.logicalCursor.row??0)>0)return}return moveField(-1)}if(key2.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(key2.name==="return"||key2.name==="space")return setMore((m2)=>!m2);return}if(field==="triage"&&key2.name==="space")return setTriage((t2)=>!t2);if(SELECTY.has(field)&&key2.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 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"),dispatchJson=(out)=>{try{let raw=JSON.parse(out);return recOf(raw)}catch{return null}},countOf=(xs)=>Array.isArray(xs)?xs.length:0;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")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.id})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 worker log (tail)`})]})}),$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||"";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.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(`
|
|
4131
4131
|
`)[0].slice(0,200)}`}):null,r.error?$jsx("text",{wrapMode:"word",fg:theme.error,children:` \u2716 ${r.error.split(`
|
|
4132
4132
|
`)[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)}
|
|
4133
4133
|
|
|
4134
4134
|
Moves to 'archived' and ends any open run. Children stay; their dependency on this task is treated as satisfied.`}).then((ok)=>{if(ok)sh(`archive ${q3(t2.id)}`,`Archived ${t2.id}`)}),[dialog,sh]),parseSpecify=(out)=>out.split(`
|
|
4135
|
-
`).flatMap((l)=>l.trim()?[JSON.parse(l)]:[]),specify=import_react80.useCallback((t2)=>{if(t2.status!=="triage")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not triage`});return sh(`specify ${q3(t2.id)} --json`).then((out)=>{if(out==null)return;let r=parseSpecify(out)[0];if(!r)return;if(!r.ok)return void toast.show({variant:"error",message:`specify ${r.task_id}: ${trunc5(r.reason??"failed",100)}`});toast.show({variant:"success",message:r.new_title?`Specified ${r.task_id} \u2192 ${trunc5(r.new_title,60)}`:`Specified ${r.task_id} \u2192 todo`})})},[sh,toast]),specifyAll=import_react80.useCallback(()=>{let triage=live.current.sec?.cols.find((c)=>c.status==="triage")?.tasks.length??0;if(triage===0)return void toast.show({variant:"info",message:`No 'triage' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Specify all \xB7 ${live.current.at}`,body:`${triage} task${triage===1?"":"s"} in 'triage'. Auxiliary LLM expands each body and promotes to todo.`,yes:"specify"}).then((go)=>{if(!go)return;return sh("specify --all --json").then((out)=>{if(out==null)return;let rows3=parseSpecify(out),ok=rows3.filter((r)=>r.ok).length,bad=rows3.length-ok;toast.show({variant:ok===0&&bad>0?"error":"success",message:`Specified ${ok}/${rows3.length}${bad?` (${bad} failed)`:""}`})})})},[dialog,sh,toast]),dispatch=import_react80.useCallback(()=>{let ready=live.current.sec?.cols.find((c)=>c.status==="ready")?.tasks.length??0;if(ready===0)return void toast.show({variant:"info",message:`No 'ready' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Dispatch \xB7 ${live.current.at}`,body:`${ready} task${ready===1?"":"s"} in 'ready'. Spawns one worker per task (one pass).`,yes:"dispatch"}).then((ok)=>{if(!ok)return;sh("dispatch --json").then((out)=>{if(out==null)return;let r=dispatchJson(out),spawned=countOf(r?.spawned),capped=countOf(r?.skipped_per_profile_capped),defaults=countOf(r?.auto_assigned_default),skipped=countOf(r?.skipped_unassigned)+countOf(r?.skipped_nonspawnable),parts2=[`${spawned} spawned`];if(defaults)parts2.push(`${defaults} default-assigned`);if(capped)parts2.push(`${capped} profile-capped`);if(skipped)parts2.push(`${skipped} skipped`);toast.show({variant:capped||skipped?"info":"success",message:`Dispatch: ${parts2.join(" \xB7 ")}`})})})},[dialog,sh,toast]),showLog=import_react80.useCallback((t2)=>{let s=live.current.at,text3=tailLogOf(s,t2.id);if(text3==null)return void toast.show({variant:"info",message:`No worker log for ${t2.id}`});setPane({kind:"log",slug:s,id:t2.id,text:text3})},[toast]),editTitle=import_react80.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit title",label:t2.id,initial:t2.title}).then((v2)=>v2!==null&&v2!==void 0&&patchDirect(t2.id,{title:v2},`Updated ${t2.id}`)),[dialog,patchDirect]),editBody=import_react80.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit body",label:t2.id,initial:t2.body??""}).then((v2)=>{if(v2===null||v2===void 0)return;patchDirect(t2.id,{body:v2},`Updated ${t2.id}`)}),[dialog,patchDirect]),editPriority=import_react80.useCallback((t2)=>{let opts=Array.from({length:10},(_2,i)=>({title:i===0?"P0 (none)":`P${i}`,value:String(i)}));dialog.replace($jsx(DialogSelect,{title:`Priority for ${t2.id}`,options:opts,current:String(t2.priority),filterable:!1,onSelect:(o)=>{dialog.clear(),patchDirect(t2.id,{priority:Number(o.value)},`${t2.id} \u2192 P${o.value}`)}}))},[dialog,patchDirect]),editResult=import_react80.useCallback((t2)=>{if(t2.status!=="done")return void toast.show({variant:"info",message:`${t2.id} is not done`});return openTextPrompt(dialog,{title:"Edit result",label:t2.id,initial:t2.result??""}).then((v2)=>{if(v2==null)return;sh(`edit ${q3(t2.id)} --result ${q3(v2)}`,`Updated ${t2.id} result`)})},[dialog,sh,toast]),editStatus=import_react80.useCallback((t2)=>{let opts=[];if(t2.status!=="done")opts.push({title:"done",value:"complete",description:"mark complete (prompts for result)"});if(t2.status!=="blocked")opts.push({title:"blocked",value:"block",description:"mark blocked (prompts for reason)"});if(t2.status!=="scheduled")opts.push({title:"scheduled",value:"schedule",description:"park until externally unblocked (prompts for reason)"});if(t2.status==="blocked"||t2.status==="scheduled")opts.push({title:"ready",value:"unblock",description:t2.status==="scheduled"?"release back to ready":"return to ready"});opts.push({title:"archived",value:"archive",description:"archive (terminal)"}),dialog.replace($jsx(DialogSelect,{title:`Status for ${t2.id}`,options:opts,current:t2.status,filterable:!1,onSelect:async(o)=>{if(dialog.clear(),o.value==="complete"){let res=await openTextPrompt(dialog,{title:`Complete ${t2.id}`,label:"Result (optional)",initial:t2.result??""}),flag=res?` --result ${q3(res)}`:"";sh(`complete ${q3(t2.id)}${flag}`,`Completed ${t2.id}`);return}if(o.value==="block"){let r=await openTextPrompt(dialog,{title:`Block ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`block ${q3(t2.id)}${arg}`,`Blocked ${t2.id}`);return}if(o.value==="schedule"){let r=await openTextPrompt(dialog,{title:`Schedule ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`schedule ${q3(t2.id)}${arg}`,`Scheduled ${t2.id}`);return}if(o.value==="unblock")return void sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`);if(o.value==="archive")return void archive(t2)}}))},[dialog,sh,archive]),editParents=import_react80.useCallback((t2)=>{let cur2=(pane?.kind==="detail"&&pane.d.id===t2.id?pane.d:detailOf(at,t2.id))?.parents??[],d2=(data2.get(at)??boardStateOf(at)).columns,opts=STATUSES.flatMap((s)=>d2.get(s)??[]).filter((x2)=>x2.id!==t2.id).map((x2)=>({title:x2.id,description:trunc5(x2.title,50),value:x2.id,category:cur2.includes(x2.id)?"linked":"available"}));dialog.replace($jsx(DialogSelect,{title:`Parents for ${t2.id}`,options:opts,placeholder:"Select to toggle link\u2026",onSelect:(o)=>{if(dialog.clear(),cur2.includes(o.value))sh(`unlink ${q3(o.value)} ${q3(t2.id)}`,`Unlinked ${o.value}`);else sh(`link ${q3(o.value)} ${q3(t2.id)}`,`Linked ${o.value}`)}}))},[dialog,sh,data2,at,pane]),openField=import_react80.useCallback((f,t2)=>{if(f==="title")return void editTitle(t2);if(f==="body")return void editBody(t2);if(f==="assignee")return assign(t2);if(f==="priority")return editPriority(t2);if(f==="status")return editStatus(t2);if(f==="parents")return editParents(t2);if(f==="result")return void editResult(t2);if(f==="comment")return void comment(t2)},[editTitle,editBody,assign,editPriority,editStatus,editParents,editResult,comment]),bumpPriority=import_react80.useCallback((t2,d2)=>{let next2=Math.max(0,Math.min(9,t2.priority+d2));if(next2===t2.priority)return;patchDirect(t2.id,{priority:next2},`${t2.id} \u2192 P${next2}`)},[patchDirect]),ACTS=import_react80.useMemo(()=>[{key:"n",title:"New task",when:()=>!0,run:()=>void create()},{key:"N",title:"New child",when:(t2)=>!!t2,run:(t2)=>void create(t2)},{key:"a",title:"Assign",when:(t2)=>!!t2,run:(t2)=>void assign(t2)},{key:"c",title:"Comment",when:(t2)=>!!t2,run:(t2)=>void comment(t2)},{key:"s",title:"Specify",when:(t2)=>t2?.status==="triage",run:(t2)=>void specify(t2)},{key:"S",title:"Specify all",when:()=>!0,run:()=>void specifyAll()},{key:"u",title:"Unblock",when:(t2)=>t2?.status==="blocked"||t2?.status==="scheduled",run:(t2)=>void unblock(t2)},{key:"d",title:"Archive",when:(t2)=>!!t2,run:(t2)=>void archive(t2)},{key:"l",title:"Worker log",when:(t2)=>!!t2,run:(t2)=>showLog(t2)},{key:"b",title:"New board",when:()=>!0,run:()=>void newBoard()},{key:"D",title:"Dispatch",when:()=>!0,run:()=>void dispatch()}],[create,assign,comment,specify,specifyAll,unblock,archive,showLog,newBoard,dispatch]),isOpen=open2.has(at),paneOpen=pane?.kind==="detail",paneFields=paneOpen?fieldsFor(pane.d):[];useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="escape"&&pane){if(tier==="pane"){setTier("grid");return}return setPane(null)}if(keys.match("list.refresh",key2))return load4();if(key2.name==="tab"){if(paneOpen&&tier!=="pane"){setTier("pane"),setPaneSel(0);return}if(tier==="pane"){let n=paneFields.length;if(n===0)return;let d2=key2.shift?-1:1;setPaneSel((s)=>(s+d2+n)%n);return}return goBoard(key2.shift?-1:1)}if(tier==="pane"){let t3=live.current.task;if(!t3||!paneOpen)return;let f=paneFields[Math.min(paneSel,paneFields.length-1)];if(key2.name==="up"){if(f==="priority")return bumpPriority(t3,1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s-1+n)%n)}if(key2.name==="down"){if(f==="priority")return bumpPriority(t3,-1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s+1)%n)}if(key2.name==="return")return openField(f,t3);let hit2=ACTS.find((a)=>a.key===key2.raw&&a.when(t3));if(hit2)return hit2.run(t3);return}if(key2.name==="space"||key2.name===" "){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip2])return flip(sec3.chips[chip2]);return}if(key2.name==="down"){if(tier==="head"){if(isOpen)return setTier("filter");let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(tier==="filter"){if(sec3&&sec3.shown>0){setTier("grid"),setRow(0);return}let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(row3<(cur?.tasks.length??1)-1)return setRow((r)=>r+1);let n=stepBoard(1);return n?enterTop(n):void 0}if(key2.name==="up"){if(tier==="head"){let p=stepBoard(-1);return p?enterBottom(p):void 0}if(tier==="filter")return setTier("head");if(row3>0)return setRow((r)=>r-1);return setTier("filter")}if(key2.name==="left"){if(tier==="filter")return setChip((c)=>Math.max(0,c-1));if(tier==="grid")return setCol((c)=>{let n=Math.max(0,c-1);return setRow(0),n});return}if(key2.name==="right"){if(tier==="filter")return setChip((c)=>Math.min((sec3?.chips.length??1)-1,c+1));if(tier==="grid")return setCol((c)=>{let n=Math.min(cols2.length-1,c+1);return setRow(0),n});return}if(key2.name==="return"){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip2])return flip(sec3.chips[chip2]);if(task)return setPane((p)=>p?.kind==="detail"&&p.d.id===task.id?null:((d2)=>d2?{kind:"detail",slug:at,d:d2}:null)(detailOf(at,task.id)));return}let t2=live.current.task,hit=ACTS.find((a)=>a.key===key2.raw&&a.when(t2));if(hit)return hit.run(t2)});let hint=import_react80.useMemo(()=>{let t2=task;return[tier==="pane"?"Esc grid":"Tab board",tier==="head"?"\u2191\u2193 nav Space fold":tier==="filter"?"\u2190\u2192 chip Space toggle":tier==="pane"?"Tab/\u2191\u2193 field Enter edit Esc grid":"\u2190\u2192\u2191\u2193 nav Enter detail",...ACTS.filter((a)=>a.when(t2)).map((a)=>`${a.key} ${a.title.toLowerCase()}`),`${keys.print("list.refresh")} reload`].join(" ")},[ACTS,keys,task,tier]),onHead=import_react80.useCallback((s)=>{setAt(s),setTier("head"),toggle(s)},[toggle]),onChip=import_react80.useCallback((s,i,c)=>{setAt(s),setTier("filter"),setChip(i),flip(c)},[flip]),onPick=import_react80.useCallback((s,ci,ri,id)=>{setAt(s),setTier("grid"),setCol(ci),setRow(ri),setOpen((o)=>o.has(s)?o:new Set(o).add(s));let d2=detailOf(s,id);if(d2)setPane({kind:"detail",slug:s,d:d2})},[]);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Kanban \xB7 ${sections.length} board${sections.length===1?"":"s"} \xB7 ${grand} task${grand===1?"":"s"}${running2?` \xB7 ${running2} running`:""}`,children:$jsx("scrollbox",{id:"kb-board-scroll",ref:outer,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:sections.map((s)=>{let on=s.board.slug===at,secOpen=open2.has(s.board.slug),m2=maskOf(s.board.slug),filt=m2.who.size+m2.pri.size+m2.status.size,dg=diags.get(s.board.slug)??EMPTY_DIAG;return $jsxs("box",{id:`kb-sec-${s.board.slug}`,flexDirection:"column",flexShrink:0,marginBottom:1,children:[$jsx("box",{height:1,onMouseDown:()=>onHead(s.board.slug),backgroundColor:on&&tier==="head"?theme.backgroundElement:void 0,children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:secOpen?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:on?theme.primary:theme.text,children:$jsx("strong",{children:s.board.name})}),$jsx("span",{fg:theme.textMuted,children:s.error?` \xB7 ${s.error.kind}`:s.corruptBackups.length>0?` \xB7 ${s.corruptBackups.length} corrupt backup${s.corruptBackups.length===1?"":"s"}`:s.total===0?" \xB7 empty":` \xB7 ${filt?`${s.shown}/`:""}${s.total} task${s.total===1?"":"s"}${s.running?` \xB7 ${s.running} running`:""}`})]})}),secOpen?s.error?$jsx(ErrorBanner,{error:s.error,backups:s.corruptBackups}):s.corruptBackups.length>0&&s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.warning,children:`corrupt backup found: ${s.corruptBackups[0]}`})}):s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsxs("text",{fg:theme.textMuted,children:["no tasks \u2014 ",$jsx("span",{fg:theme.accent,children:"n"})," to create one here"]})}):$jsxs($Fragment,{children:[$jsx(FilterBar,{chips:s.chips,mask:m2,on:on&&tier==="filter",sel:on?Math.min(chip2,s.chips.length-1):-1,onPick:(i)=>onChip(s.board.slug,i,s.chips[i])}),s.cols.length>0?$jsx("box",{flexDirection:"row",height:s.cap,gap:1,children:s.cols.map((c,ci)=>$jsx(Column,{slug:s.board.slug,status:c.status,tasks:c.tasks,diags:dg,on:on&&(tier==="grid"||tier==="pane")&&ci===clampCol,sel:on?row3:0,onPick:(ri)=>onPick(s.board.slug,ci,ri,c.tasks[ri].id)},c.status))}):$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.textMuted,children:"all columns hidden"})})]}):null]},s.board.slug)})})})}),pane?$jsx(SidePane,{pane,on:tier==="pane",sel:paneSel,diags:pane.kind==="detail"?diags.get(pane.slug)?.get(pane.d.id)??EMPTY_DIAGS:EMPTY_DIAGS}):null]}),$jsx(HintBar,{raw:hint})]})});var Automation=import_react82.memo((props)=>{let labels=SUB_TABS[AUTOMATION_TAB];import_react82.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane2,{visible:props.sub===0,children:$jsx(Kanban,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane2,{visible:props.sub===1,children:$jsx(Agents,{focused:!!props.focused&&props.sub===1,sessionId:props.sessionId,onSwitchProfile:props.onSwitchProfile})}),$jsx(Pane2,{visible:props.sub===2,children:$jsx(Cron,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane2=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react95=__toESM(require_react_production(),1);var import_react85=__toESM(require_react_production(),1);init_lane();var int=(lo,hi,what=`${lo}\u2013${hi}`)=>(raw)=>{let n=Number(raw);if(!Number.isInteger(n))return`expected integer ${what}`;if(n<lo||n>hi)return`expected ${what}`;return null},float=(lo,hi)=>(raw)=>{let n=Number(raw);if(!Number.isFinite(n))return`expected number ${lo}\u2013${hi}`;if(n<lo||n>hi)return`expected ${lo}\u2013${hi}`;return null},oneOf=(...opts)=>(raw)=>opts.includes(raw)?null:`expected one of: ${opts.join(" | ")}`,nonNeg=(raw)=>{let n=Number(raw);return Number.isFinite(n)&&n>=0?null:"expected \u2265 0"},RULES={"compression.threshold":float(0.1,0.95),"compression.target_ratio":float(0.05,0.9),"prompt_caching.cache_ttl":(raw)=>/^\d+[smhd]$/.test(raw.trim())?null:"expected duration e.g. 5m, 1h","agent.max_turns":int(1,1e4),"delegation.max_iterations":int(1,1e4),"delegation.max_concurrent_children":int(1,64),"delegation.max_spawn_depth":int(1,3),"agent.gateway_timeout":nonNeg,"agent.gateway_timeout_warning":nonNeg,"agent.gateway_notify_interval":nonNeg,"agent.restart_drain_timeout":nonNeg,"delegation.child_timeout_seconds":int(30,86400),"browser.command_timeout":int(1,600),"approvals.timeout":int(1,3600),"security.tirith_timeout":int(1,120),"agent.api_max_retries":int(0,20),"tool_output.max_bytes":int(1024,1e7),"tool_output.max_lines":int(10,1e5),"sessions.retention_days":int(1,3650),"sessions.min_interval_hours":int(1,720),"agent.service_tier":oneOf("","fast","standard"),"display.busy_input_mode":oneOf("queue","steer","interrupt"),"display.details_mode":oneOf("hidden","collapsed","expanded"),"display.thinking_mode":oneOf("collapsed","truncated","full"),"display.tool_progress":oneOf("off","new","all","verbose"),"display.final_response_markdown":oneOf("render","strip","raw"),"logging.level":oneOf("DEBUG","INFO","WARNING","ERROR"),"approvals.mode":oneOf("manual","ask","yolo","deny"),"code_execution.mode":oneOf("project","strict")},check=(key2,raw)=>RULES[key2]?.(raw)??null;init_schema();init_lane();var SELECTS={"terminal.backend":["local","docker","ssh","modal","daytona","singularity","vercel_sandbox"],"tts.provider":["edge","elevenlabs","openai","neutts","xai","mistral"],"display.skin":[...SKINS],"logging.level":["DEBUG","INFO","WARNING","ERROR"],"agent.reasoning_effort":["","none","minimal","low","medium","high","xhigh"],"display.busy_input_mode":["queue","steer","interrupt"],"display.details_mode":["hidden","collapsed","expanded"],"display.thinking_mode":["collapsed","truncated","full"],"display.tool_progress":["off","new","all","verbose"],"approvals.mode":["manual","ask","yolo","deny"]},get4=(obj,path7)=>{let cur=obj;for(let p of path7.split("."))if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},classify2=(key2,t2)=>{if(route(key2).via==="readonly")return"readonly";if(SELECTS[key2])return"select";if(t2==="bool")return"boolean";if(t2==="int"||t2==="float")return"number";return"string"},labelOf=(key2)=>{let raw=SCHEMA[key2]?.group??key2.split(".")[0];return key2.startsWith(`${raw}.`)?key2.slice(raw.length+1):key2},buildFields=(user)=>{let seen=new Set,out=[];for(let key2 of SCHEMA_KEYS){let s=SCHEMA[key2],uv=get4(user,key2),set2=uv!==void 0;out.push({key:key2,label:labelOf(key2),type:classify2(key2,s.type),value:set2?uv:s.default,set:set2,doc:s.doc,effect:s.effect,options:SELECTS[key2]}),seen.add(key2)}let walk=(obj,prefix="")=>{for(let[k2,v2]of Object.entries(obj)){let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2)){if(SCHEMA[key2]?.type==="dict"){seen.add(key2);continue}walk(v2,key2);continue}if(seen.has(key2))continue;out.push({key:key2,label:labelOf(key2),type:Array.isArray(v2)?"readonly":typeof v2==="boolean"?"boolean":typeof v2==="number"?"number":"string",value:v2,set:!0,doc:"",effect:"live"})}};return walk(user),out},MERGE={approvals:"security",privacy:"security",secrets:"security",checkpoints:"agent",context:"agent",cron:"agent",network:"agent",model_catalog:"general",onboarding:"general",human_delay:"display",dashboard:"display",gateway:"display",tool_output:"agent",prompt_caching:"compression",code_execution:"terminal",lsp:"agent",x_search:"agent",slack:"platforms",telegram:"platforms",mattermost:"platforms",discord:"platforms",whatsapp:"platforms",matrix:"platforms"},rawGroupOf=(key2)=>SCHEMA[key2]?.group??(key2.includes(".")?key2.split(".")[0]:"general"),groupOf=(key2)=>{let raw=rawGroupOf(key2);return MERGE[raw]??raw},sections=(group2,fields)=>{let by=new Map;for(let f of fields){let r=rawGroupOf(f.key);if(!by.has(r))by.set(r,[]);by.get(r).push(f)}if(by.size<=1)return[{head:null,items:fields}];return[...by.keys()].sort((a,b2)=>a===group2?-1:b2===group2?1:a.localeCompare(b2)).map((r)=>({head:r,items:by.get(r)}))},GROUPS=(()=>{let g=new Set(["general"]);for(let k2 of SCHEMA_KEYS)g.add(groupOf(k2));return[...g]})(),EFFECT_GLYPH={live:"",session:"\u21BB",restart:"\u27F3"};init_lane();var AUX_TASKS=[{key:"vision",label:"Vision",hint:"Image analysis"},{key:"web_extract",label:"Web Extract",hint:"Page summarization"},{key:"compression",label:"Compression",hint:"Context compaction"},{key:"session_search",label:"Session Search",hint:"Recall queries"},{key:"skills_hub",label:"Skills Hub",hint:"Skill search"},{key:"approval",label:"Approval",hint:"Smart auto-approve"},{key:"mcp",label:"MCP",hint:"MCP tool routing"},{key:"title_generation",label:"Title Gen",hint:"Session titles"},{key:"triage_specifier",label:"Triage Specifier",hint:"Kanban spec fleshing"},{key:"kanban_decomposer",label:"Kanban Decomposer",hint:"Task decomposition"},{key:"profile_describer",label:"Profile Describer",hint:"Auto profile descriptions"},{key:"curator",label:"Curator",hint:"Skill-usage review"}],dig=(o,...path7)=>path7.reduce((c,p)=>c&&typeof c==="object"?c[p]:void 0,o),str2=(v2)=>typeof v2==="string"?v2:"",readSlots=(raw)=>{let main2={kind:"main",key:"main",label:"Main model",hint:"Primary agent model",provider:str2(dig(raw,"model","provider")),model:str2(dig(raw,"model","default"))||str2(dig(raw,"model","name")),auto:!1},aux=AUX_TASKS.map((t2)=>{let p=str2(dig(raw,"auxiliary",t2.key,"provider"));return{kind:"aux",key:t2.key,label:t2.label,hint:t2.hint,provider:p,model:str2(dig(raw,"auxiliary",t2.key,"model")),auto:p===""||p==="auto"}});return[main2,...aux]},staleAuxForMain=(slots,provider)=>slots.filter((s)=>s.kind==="aux"&&!s.auto&&s.provider!==""&&s.provider!=="auto"&&s.provider!==provider),assign=async(gw,slot,provider,model)=>{if(slot==="main"){let r=await gw.request("config.set",{key:"model",value:`${model} --provider ${provider} --global`,session_id:void 0});return{ok:["model.default","model.provider"],failed:[],warnings:[],warning:r.warning}}return writeConfig(gw,[{key:`auxiliary.${slot}.provider`,to:provider},{key:`auxiliary.${slot}.model`,to:model}])},resetAux=(gw,slot)=>{let keys=slot==="all"?AUX_TASKS.map((t2)=>t2.key):[slot];return writeConfig(gw,keys.flatMap((k2)=>[{key:`auxiliary.${k2}.provider`,to:"auto"},{key:`auxiliary.${k2}.model`,to:""}]))};var import_react84=__toESM(require_react_production(),1);var import_react83=__toESM(require_react_production(),1);var SecretPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react83.useState("");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,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,$jsx(MaskInput,{value,input:setValue,submit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)}}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel":"Esc cancel"})})]})};var configured=(p)=>(p.models?.length??0)>0,setupDescription=(p)=>{if(p.warning)return p.warning;if(p.auth_type==="api_key"&&p.key_env)return`paste ${p.key_env} to activate`;if(p.key_env)return p.key_env;if(p.auth_type)return`run hermes model to configure (${p.auth_type})`;return},providerDescription=(p)=>{if(p.authenticated===!1)return setupDescription(p);return p.total_models?`${p.total_models} models`:void 0},providerHint=(p)=>{if(p.authenticated!==!1)return;return p.auth_type?`auth_type=${p.auth_type}`:void 0},replaceProvider=(data2,slug2,next2)=>({...data2,providers:(data2.providers??[]).map((p)=>p.slug===slug2?next2:p)}),ModelPickerDialog=(props)=>{let dialog=useDialog(),toast=useToast(),theme=useTheme().theme,[data2,setData]=import_react84.useState(null),[step,setStep]=import_react84.useState("provider"),[provider,setProvider]=import_react84.useState(null),[setupProvider,setSetupProvider]=import_react84.useState(null),[global2,setGlobal]=import_react84.useState(!1),refresh=import_react84.useCallback(()=>props.gw.request("model.options").then(setData).catch(()=>setData({providers:[]})),[props.gw]);import_react84.useEffect(()=>{refresh()},[refresh]);let apply=import_react84.useCallback((model,prov)=>{if(props.onApply)return void props.onApply(prov,model).catch((e)=>toast.show({variant:"error",message:e.message}));let value=`${model} --provider ${prov}${global2?" --global":""}`;props.gw.request("config.set",global2?{key:"model",value,session_id:void 0}:{key:"model",value}).then((r)=>{if(toast.show({variant:"success",message:`model \u2192 ${r.value??model}${global2?" (global)":""}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[props.gw,props.onApply,global2,toast]),submitKey=import_react84.useCallback(async(p2,key2)=>{try{let r=await props.gw.request("model.save_key",{slug:p2.slug,api_key:key2});if(r.warning)toast.show({variant:"warning",message:r.warning});let next2=r.provider??(await props.gw.request("model.options")).providers?.find((pp)=>pp.slug===p2.slug);if(!next2){toast.show({variant:"warning",message:"Provider saved; refresh model options to continue"});return}if(setData((d2)=>d2?replaceProvider(d2,p2.slug,next2):d2),configured(next2)){setSetupProvider(null),setProvider(next2.slug),setStep("model"),toast.show({variant:"success",message:`${next2.name} activated`});return}toast.show({variant:"warning",message:next2.warning??"Provider saved but no models were returned"})}catch(e){toast.show({variant:"error",message:e instanceof Error?e.message:String(e)})}},[props.gw,toast]),setup=import_react84.useCallback((p2)=>{let msg=setupDescription(p2);if(p2.auth_type!=="api_key"||!p2.key_env){toast.show({variant:"warning",message:msg??"Run hermes model to configure this provider"});return}setSetupProvider(p2),setStep("setup")},[toast]),onKey=import_react84.useCallback((k2)=>{if(k2.name==="tab"&&!props.onApply)return setGlobal((g)=>!g),!0;if(k2.name==="left"&&step!=="provider")return setStep("provider"),!0;return!1},[step,props.onApply]),footer=props.onApply?$jsx("text",{fg:theme.textMuted,children:step==="model"?"\u2190: providers":" "}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{children:"Scope: "}),$jsx("span",{fg:global2?theme.warning:theme.accent,children:global2?"global (persists to config)":"this session"}),$jsxs("span",{children:[" \xB7 Tab: toggle",step==="model"?" \xB7 \u2190: providers":""]})]});if(!data2)return $jsx("box",{width:50,padding:1,children:$jsx("text",{children:"Loading models\u2026"})});if(step==="setup"&&setupProvider?.key_env)return $jsx(SecretPrompt,{title:`Paste ${setupProvider.key_env}`,label:setupDescription(setupProvider)??`API key for ${setupProvider.name}`,onSubmit:(key2)=>{submitKey(setupProvider,key2)}});if(step==="provider"){let options2=(data2.providers??[]).toSorted((a,b2)=>Number(Boolean(b2.is_current))-Number(Boolean(a.is_current))).map((p2)=>({title:p2.name,value:p2.slug,description:providerDescription(p2),hint:providerHint(p2),category:p2.is_current?"Current":p2.authenticated===!1?"Setup required":"Available"}));return $jsx(DialogSelect,{title:props.title??"Switch Provider",options:options2,current:data2.provider,onSelect:(o)=>{let p2=data2.providers?.find((pp)=>pp.slug===o.value);if(p2?.authenticated===!1||p2&&!configured(p2))return void setup(p2);setProvider(o.value),setStep("model")},onKey,placeholder:"Search providers...",footer})}let p=data2.providers?.find((pp)=>pp.slug===provider),options=(p?.models??[]).map((m2)=>{let caps=p?.capabilities?.[m2],badges=[caps?.fast?"fast":"",caps?.reasoning?"reasoning":""].filter(Boolean);return{title:m2,value:m2,hint:badges.length>0?badges.join(" \xB7 "):void 0}});return $jsx(DialogSelect,{title:props.title?`${props.title} \xB7 ${p?.name??provider}`:`Switch Model (${p?.name??provider})`,options,current:provider===data2.provider?data2.model:void 0,onSelect:(o)=>{if(provider)apply(o.value,provider);dialog.clear()},onKey,placeholder:"Search models...",footer})},openModelPicker=(dialog,gw,opts)=>{dialog.replace($jsx(ModelPickerDialog,{gw,title:opts?.title,onApply:opts?.onApply}))};var flatten=(obj,prefix="")=>Object.entries(obj).flatMap(([k2,v2])=>{let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2))return flatten(v2,key2);return[[key2,v2]]}),setNested=(obj,path7,val)=>{let parts2=path7.split("."),cur=obj;for(let i=0;i<parts2.length-1;i++){if(!cur[parts2[i]]||typeof cur[parts2[i]]!=="object")cur[parts2[i]]={};cur=cur[parts2[i]]}cur[parts2[parts2.length-1]]=val},getNested=(obj,path7)=>{let parts2=path7.split("."),cur=obj;for(let p of parts2)if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},FieldRow=import_react85.memo((props)=>{let theme=useTheme().theme,f=props.field,bg2=props.active?theme.backgroundElement:void 0,indicator=props.active?"\u25B8 ":" ",mark2=props.changed?"\u25CF ":f.set?"\xB7":" ",markFg=props.changed?theme.warning:theme.textMuted,display=()=>{if(props.editing)return props.buf+"\u2588";if(f.type==="readonly"){let n=Array.isArray(f.value)?f.value.length:f.value&&typeof f.value==="object"?Object.keys(f.value).length:0;return n===0?"\u2014":`${n} item${n===1?"":"s"}`}if(f.type==="boolean")return f.value?"\u2713 ON":"\u2717 OFF";return String(f.value??"")},hint=()=>{if(props.readonly||f.type==="readonly")return"\uD83D\uDD12";if(f.type==="boolean")return"[space]";if(f.type==="select")return"[h/l]";return"[enter]"},ro=props.readonly||f.type==="readonly",valFg=ro||!f.set?theme.textMuted:f.type==="boolean"?f.value?theme.success:theme.error:theme.text,labelFg=ro?theme.textMuted:props.active?theme.accent:theme.text,lead=4+(props.badge!==void 0?12:0),glyph=props.active?EFFECT_GLYPH[f.effect]:"";return $jsxs("box",{id:props.id,flexDirection:"column",backgroundColor:bg2,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:markFg,children:mark2}),$jsx(Col,{w:2,fg:props.active?theme.primary:theme.text,children:indicator}),props.badge!==void 0?$jsx(Col,{w:12,fg:theme.textMuted,children:props.badge}):null,$jsx(Col,{w:40,fg:labelFg,children:f.label}),$jsx(Col,{grow:!0,min:6,fg:valFg,children:display()}),$jsx(Col,{w:2,fg:theme.textMuted,children:glyph}),$jsx(Col,{w:9,fg:theme.textMuted,right:!0,children:props.active?hint():""})]}),props.error?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:lead+40,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:6,fg:theme.error,children:`\u2717 ${props.error}`})]}):props.active&&f.doc?$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:lead,flexShrink:0}),$jsx("box",{width:40,flexShrink:0,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:f.doc})})]}):null]})}),SlotRow=import_react85.memo((p)=>{let theme=useTheme().theme,main2=p.s.kind==="main",val=main2?`${p.s.provider||"(unset)"} \xB7 ${p.s.model||"(unset)"}`:p.s.auto?"auto (use main model)":`${p.s.provider} \xB7 ${p.s.model||"(provider default)"}`;return $jsxs("box",{id:p.id,flexDirection:"row",height:1,backgroundColor:p.on?theme.backgroundElement:void 0,children:[$jsx(Col,{w:2,fg:p.on?theme.primary:theme.text,children:p.on?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:main2?theme.primary:theme.textMuted,children:main2?"\u2605":" "}),$jsx(Col,{w:16,fg:p.on?theme.accent:theme.text,children:p.s.label}),$jsx(Col,{w:22,fg:theme.textMuted,children:p.s.hint}),$jsx(Col,{grow:!0,min:10,fg:p.s.auto?theme.textMuted:theme.text,children:val}),$jsx(Col,{w:14,fg:theme.textMuted,right:!0,children:p.on?main2?"[enter]":"[enter] [x]":""})]})}),Config=import_react85.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),toast=useToast(),dialog=useDialog(),[raw,setRaw]=import_react85.useState({}),[original,setOriginal]=import_react85.useState({}),[yaml,setYaml]=import_react85.useState(""),[mode,setMode]=import_react85.useState("form"),[cat,setCat]=import_react85.useState(0),[cursor,setCursor]=import_react85.useState(0),[editing,setEditing]=import_react85.useState(!1),[buf,setBuf]=import_react85.useState(""),[err,setErr]=import_react85.useState({}),[searching,setSearching]=import_react85.useState(!1),[query,setQuery]=import_react85.useState(""),[focus,setFocus]=import_react85.useState("categories"),[managed,setManaged]=import_react85.useState(null);import_react85.useEffect(()=>{managedSystem().then(setManaged)},[]);let load4=import_react85.useCallback(()=>{gw.request("config.get",{key:"full"}).then((res)=>{let parsed=res.config??{};setRaw(structuredClone(parsed)),setOriginal(structuredClone(parsed)),setYaml($stringify(parsed)),setErr({})}).catch(()=>{setRaw({}),setOriginal({}),setYaml("")})},[gw]);import_react85.useEffect(()=>{load4()},[load4]);let all=buildFields(raw),grouped=all.reduce((map,f)=>{let g=groupOf(f.key);if(!map.has(g))map.set(g,[]);return map.get(g).push(f),map},new Map(GROUPS.map((g)=>[g,[]]))),groups=[...grouped.keys()];groups.splice(1,0,"models");let active=groups[cat]??groups[0],onSlots=active==="models"&&!searching,slots=readSlots(raw),secs=searching&&query.trim()?[{head:null,items:all.filter((f)=>f.key.toLowerCase().includes(query.toLowerCase()))}]:sections(active,grouped.get(active)??[]),fields=secs.flatMap((s)=>s.items),count3=onSlots?slots.length:fields.length,follow=useFollow("cfg"),catFollow=useFollow("cfg-cat"),changed=(key2)=>JSON.stringify(getNested(raw,key2))!==JSON.stringify(getNested(original,key2)),nChanged=all.reduce((n,f)=>n+(changed(f.key)?1:0),0),update=(key2,val)=>{let next2=structuredClone(raw);setNested(next2,key2,val),setRaw(next2),setYaml($stringify(next2))},fmt3=(v2)=>v2===void 0?"\u2014":Array.isArray(v2)?v2.join(", "):String(v2),save2=async()=>{if(managed){toast.show({variant:"error",message:`Managed by ${managed} \u2014 edit configuration.nix`});return}let nErr=Object.keys(err).length;if(nErr>0){toast.show({variant:"error",message:`${nErr} invalid field${nErr===1?"":"s"}`});return}let target=mode==="yaml"?$parse(yaml)??{}:raw,diffs=flatten(target).filter(([key2])=>JSON.stringify(getNested(target,key2))!==JSON.stringify(getNested(original,key2))).map(([key2,val])=>({key:key2,from:getNested(original,key2),to:val}));if(diffs.length===0){toast.show({variant:"info",message:"No changes"});return}let body=diffs.map((d2)=>`${d2.key}: ${fmt3(d2.from)} \u2192 ${fmt3(d2.to)}`).join(`
|
|
4135
|
+
`).flatMap((l)=>l.trim()?[JSON.parse(l)]:[]),specify=import_react80.useCallback((t2)=>{if(t2.status!=="triage")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not triage`});return sh(`specify ${q3(t2.id)} --json`).then((out)=>{if(out==null)return;let r=parseSpecify(out)[0];if(!r)return;if(!r.ok)return void toast.show({variant:"error",message:`specify ${r.task_id}: ${trunc5(r.reason??"failed",100)}`});toast.show({variant:"success",message:r.new_title?`Specified ${r.task_id} \u2192 ${trunc5(r.new_title,60)}`:`Specified ${r.task_id} \u2192 todo`})})},[sh,toast]),specifyAll=import_react80.useCallback(()=>{let triage=live.current.sec?.cols.find((c)=>c.status==="triage")?.tasks.length??0;if(triage===0)return void toast.show({variant:"info",message:`No 'triage' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Specify all \xB7 ${live.current.at}`,body:`${triage} task${triage===1?"":"s"} in 'triage'. Auxiliary LLM expands each body and promotes to todo.`,yes:"specify"}).then((go)=>{if(!go)return;return sh("specify --all --json").then((out)=>{if(out==null)return;let rows3=parseSpecify(out),ok=rows3.filter((r)=>r.ok).length,bad=rows3.length-ok;toast.show({variant:ok===0&&bad>0?"error":"success",message:`Specified ${ok}/${rows3.length}${bad?` (${bad} failed)`:""}`})})})},[dialog,sh,toast]),dispatch=import_react80.useCallback(()=>{let ready=live.current.sec?.cols.find((c)=>c.status==="ready")?.tasks.length??0;if(ready===0)return void toast.show({variant:"info",message:`No 'ready' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Dispatch \xB7 ${live.current.at}`,body:`${ready} task${ready===1?"":"s"} in 'ready'. Spawns one worker per task (one pass).`,yes:"dispatch"}).then((ok)=>{if(!ok)return;sh("dispatch --json").then((out)=>{if(out==null)return;let r=dispatchJson(out),spawned=countOf(r?.spawned),capped=countOf(r?.skipped_per_profile_capped),defaults=countOf(r?.auto_assigned_default),skipped=countOf(r?.skipped_unassigned)+countOf(r?.skipped_nonspawnable),parts2=[`${spawned} spawned`];if(defaults)parts2.push(`${defaults} default-assigned`);if(capped)parts2.push(`${capped} profile-capped`);if(skipped)parts2.push(`${skipped} skipped`);toast.show({variant:capped||skipped?"info":"success",message:`Dispatch: ${parts2.join(" \xB7 ")}`})})})},[dialog,sh,toast]),showLog=import_react80.useCallback((t2)=>{let s=live.current.at,text3=tailLogOf(s,t2.id);if(text3==null)return void toast.show({variant:"info",message:`No worker log for ${t2.id}`});setPane({kind:"log",slug:s,id:t2.id,text:text3})},[toast]),editTitle=import_react80.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit title",label:t2.id,initial:t2.title}).then((v2)=>v2!==null&&v2!==void 0&&patchDirect(t2.id,{title:v2},`Updated ${t2.id}`)),[dialog,patchDirect]),editBody=import_react80.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit body",label:t2.id,initial:t2.body??""}).then((v2)=>{if(v2===null||v2===void 0)return;patchDirect(t2.id,{body:v2},`Updated ${t2.id}`)}),[dialog,patchDirect]),editPriority=import_react80.useCallback((t2)=>{let opts=Array.from({length:10},(_2,i)=>({title:i===0?"P0 (none)":`P${i}`,value:String(i)}));dialog.replace($jsx(DialogSelect,{title:`Priority for ${t2.id}`,options:opts,current:String(t2.priority),filterable:!1,onSelect:(o)=>{dialog.clear(),patchDirect(t2.id,{priority:Number(o.value)},`${t2.id} \u2192 P${o.value}`)}}))},[dialog,patchDirect]),editResult=import_react80.useCallback((t2)=>{if(t2.status!=="done")return void toast.show({variant:"info",message:`${t2.id} is not done`});return openTextPrompt(dialog,{title:"Edit result",label:t2.id,initial:t2.result??""}).then((v2)=>{if(v2==null)return;sh(`edit ${q3(t2.id)} --result ${q3(v2)}`,`Updated ${t2.id} result`)})},[dialog,sh,toast]),editStatus=import_react80.useCallback((t2)=>{let opts=[];if(t2.status!=="done")opts.push({title:"done",value:"complete",description:"mark complete (prompts for result)"});if(t2.status!=="blocked")opts.push({title:"blocked",value:"block",description:"mark blocked (prompts for reason)"});if(t2.status!=="scheduled")opts.push({title:"scheduled",value:"schedule",description:"park until externally unblocked (prompts for reason)"});if(t2.status==="blocked"||t2.status==="scheduled")opts.push({title:"ready",value:"unblock",description:t2.status==="scheduled"?"release back to ready":"return to ready"});opts.push({title:"archived",value:"archive",description:"archive (terminal)"}),dialog.replace($jsx(DialogSelect,{title:`Status for ${t2.id}`,options:opts,current:t2.status,filterable:!1,onSelect:async(o)=>{if(dialog.clear(),o.value==="complete"){let res=await openTextPrompt(dialog,{title:`Complete ${t2.id}`,label:"Result (optional)",initial:t2.result??""}),flag=res?` --result ${q3(res)}`:"";sh(`complete ${q3(t2.id)}${flag}`,`Completed ${t2.id}`);return}if(o.value==="block"){let r=await openTextPrompt(dialog,{title:`Block ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`block ${q3(t2.id)}${arg}`,`Blocked ${t2.id}`);return}if(o.value==="schedule"){let r=await openTextPrompt(dialog,{title:`Schedule ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`schedule ${q3(t2.id)}${arg}`,`Scheduled ${t2.id}`);return}if(o.value==="unblock")return void sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`);if(o.value==="archive")return void archive(t2)}}))},[dialog,sh,archive]),editParents=import_react80.useCallback((t2)=>{let cur2=(pane?.kind==="detail"&&pane.d.id===t2.id?pane.d:detailOf(at,t2.id))?.parents??[],d2=(data2.get(at)??boardStateOf(at)).columns,opts=STATUSES.flatMap((s)=>d2.get(s)??[]).filter((x2)=>x2.id!==t2.id).map((x2)=>({title:x2.id,description:trunc5(x2.title,50),value:x2.id,category:cur2.includes(x2.id)?"linked":"available"}));dialog.replace($jsx(DialogSelect,{title:`Parents for ${t2.id}`,options:opts,placeholder:"Select to toggle link\u2026",onSelect:(o)=>{if(dialog.clear(),cur2.includes(o.value))sh(`unlink ${q3(o.value)} ${q3(t2.id)}`,`Unlinked ${o.value}`);else sh(`link ${q3(o.value)} ${q3(t2.id)}`,`Linked ${o.value}`)}}))},[dialog,sh,data2,at,pane]),openField=import_react80.useCallback((f,t2)=>{if(f==="title")return void editTitle(t2);if(f==="body")return void editBody(t2);if(f==="assignee")return assign(t2);if(f==="priority")return editPriority(t2);if(f==="status")return editStatus(t2);if(f==="parents")return editParents(t2);if(f==="result")return void editResult(t2);if(f==="comment")return void comment(t2)},[editTitle,editBody,assign,editPriority,editStatus,editParents,editResult,comment]),ACTS=import_react80.useMemo(()=>[{key:"n",title:"New task",when:()=>!0,run:()=>void create()},{key:"N",title:"New child",when:(t2)=>!!t2,run:(t2)=>void create(t2)},{key:"a",title:"Assign",when:(t2)=>!!t2,run:(t2)=>void assign(t2)},{key:"c",title:"Comment",when:(t2)=>!!t2,run:(t2)=>void comment(t2)},{key:"s",title:"Specify",when:(t2)=>t2?.status==="triage",run:(t2)=>void specify(t2)},{key:"S",title:"Specify all",when:()=>!0,run:()=>void specifyAll()},{key:"u",title:"Unblock",when:(t2)=>t2?.status==="blocked"||t2?.status==="scheduled",run:(t2)=>void unblock(t2)},{key:"d",title:"Archive",when:(t2)=>!!t2,run:(t2)=>void archive(t2)},{key:"l",title:"Worker log",when:(t2)=>!!t2,run:(t2)=>showLog(t2)},{key:"b",title:"New board",when:()=>!0,run:()=>void newBoard()},{key:"D",title:"Dispatch",when:()=>!0,run:()=>void dispatch()}],[create,assign,comment,specify,specifyAll,unblock,archive,showLog,newBoard,dispatch]),isOpen=open2.has(at),paneOpen=pane?.kind==="detail",paneFields=paneOpen?fieldsFor(pane.d):[];useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="escape"&&pane){if(tier==="pane"){setTier("grid");return}return setPane(null)}if(keys.match("list.refresh",key2))return load4();if(key2.name==="tab"){if(paneOpen&&tier!=="pane"){setTier("pane"),setPaneSel(0);return}if(tier==="pane"){let n=paneFields.length;if(n===0)return;let d2=key2.shift?-1:1;setPaneSel((s)=>(s+d2+n)%n);return}return goBoard(key2.shift?-1:1)}if(tier==="pane"){let t3=live.current.task;if(!t3||!paneOpen)return;let f=paneFields[Math.min(paneSel,paneFields.length-1)];if(key2.name==="up"){let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s-1+n)%n)}if(key2.name==="down"){let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s+1)%n)}if(key2.name==="return")return openField(f,t3);let hit2=ACTS.find((a)=>a.key===key2.raw&&a.when(t3));if(hit2)return hit2.run(t3);return}if(key2.name==="space"||key2.name===" "){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip2])return flip(sec3.chips[chip2]);return}if(key2.name==="down"){if(tier==="head"){if(isOpen)return setTier("filter");let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(tier==="filter"){if(sec3&&sec3.shown>0){setTier("grid"),setRow(0);return}let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(row3<(cur?.tasks.length??1)-1)return setRow((r)=>r+1);let n=stepBoard(1);return n?enterTop(n):void 0}if(key2.name==="up"){if(tier==="head"){let p=stepBoard(-1);return p?enterBottom(p):void 0}if(tier==="filter")return setTier("head");if(row3>0)return setRow((r)=>r-1);return setTier("filter")}if(key2.name==="left"){if(tier==="filter")return setChip((c)=>Math.max(0,c-1));if(tier==="grid")return setCol((c)=>{let n=Math.max(0,c-1);return setRow(0),n});return}if(key2.name==="right"){if(tier==="filter")return setChip((c)=>Math.min((sec3?.chips.length??1)-1,c+1));if(tier==="grid")return setCol((c)=>{let n=Math.min(cols2.length-1,c+1);return setRow(0),n});return}if(key2.name==="return"){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip2])return flip(sec3.chips[chip2]);if(task)return setPane((p)=>p?.kind==="detail"&&p.d.id===task.id?null:((d2)=>d2?{kind:"detail",slug:at,d:d2}:null)(detailOf(at,task.id)));return}let t2=live.current.task,hit=ACTS.find((a)=>a.key===key2.raw&&a.when(t2));if(hit)return hit.run(t2)});let hint=import_react80.useMemo(()=>{let t2=task;return[tier==="pane"?"Esc grid":"Tab board",tier==="head"?"\u2191\u2193 nav Space fold":tier==="filter"?"\u2190\u2192 chip Space toggle":tier==="pane"?"Tab/\u2191\u2193 field Enter edit Esc grid":"\u2190\u2192\u2191\u2193 nav Enter detail",...ACTS.filter((a)=>a.when(t2)).map((a)=>`${a.key} ${a.title.toLowerCase()}`),`${keys.print("list.refresh")} reload`].join(" ")},[ACTS,keys,task,tier]),onHead=import_react80.useCallback((s)=>{setAt(s),setTier("head"),toggle(s)},[toggle]),onChip=import_react80.useCallback((s,i,c)=>{setAt(s),setTier("filter"),setChip(i),flip(c)},[flip]),onPick=import_react80.useCallback((s,ci,ri,id)=>{setAt(s),setTier("grid"),setCol(ci),setRow(ri),setOpen((o)=>o.has(s)?o:new Set(o).add(s));let d2=detailOf(s,id);if(d2)setPane({kind:"detail",slug:s,d:d2})},[]);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Kanban \xB7 ${sections.length} board${sections.length===1?"":"s"} \xB7 ${grand} task${grand===1?"":"s"}${running2?` \xB7 ${running2} running`:""}`,children:$jsx("scrollbox",{id:"kb-board-scroll",ref:outer,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:sections.map((s)=>{let on=s.board.slug===at,secOpen=open2.has(s.board.slug),m2=maskOf(s.board.slug),filt=m2.who.size+m2.pri.size+m2.status.size,dg=diags.get(s.board.slug)??EMPTY_DIAG;return $jsxs("box",{id:`kb-sec-${s.board.slug}`,flexDirection:"column",flexShrink:0,marginBottom:1,children:[$jsx("box",{height:1,onMouseDown:()=>onHead(s.board.slug),backgroundColor:on&&tier==="head"?theme.backgroundElement:void 0,children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:secOpen?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:on?theme.primary:theme.text,children:$jsx("strong",{children:s.board.name})}),$jsx("span",{fg:theme.textMuted,children:s.error?` \xB7 ${s.error.kind}`:s.corruptBackups.length>0?` \xB7 ${s.corruptBackups.length} corrupt backup${s.corruptBackups.length===1?"":"s"}`:s.total===0?" \xB7 empty":` \xB7 ${filt?`${s.shown}/`:""}${s.total} task${s.total===1?"":"s"}${s.running?` \xB7 ${s.running} running`:""}`})]})}),secOpen?s.error?$jsx(ErrorBanner,{error:s.error,backups:s.corruptBackups}):s.corruptBackups.length>0&&s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.warning,children:`corrupt backup found: ${s.corruptBackups[0]}`})}):s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsxs("text",{fg:theme.textMuted,children:["no tasks \u2014 ",$jsx("span",{fg:theme.accent,children:"n"})," to create one here"]})}):$jsxs($Fragment,{children:[$jsx(FilterBar,{chips:s.chips,mask:m2,on:on&&tier==="filter",sel:on?Math.min(chip2,s.chips.length-1):-1,onPick:(i)=>onChip(s.board.slug,i,s.chips[i])}),s.cols.length>0?$jsx("box",{flexDirection:"row",height:s.cap,gap:1,children:s.cols.map((c,ci)=>$jsx(Column,{slug:s.board.slug,status:c.status,tasks:c.tasks,diags:dg,on:on&&(tier==="grid"||tier==="pane")&&ci===clampCol,sel:on?row3:0,onPick:(ri)=>onPick(s.board.slug,ci,ri,c.tasks[ri].id)},c.status))}):$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.textMuted,children:"all columns hidden"})})]}):null]},s.board.slug)})})})}),pane?$jsx(SidePane,{pane,on:tier==="pane",sel:paneSel,diags:pane.kind==="detail"?diags.get(pane.slug)?.get(pane.d.id)??EMPTY_DIAGS:EMPTY_DIAGS}):null]}),$jsx(HintBar,{raw:hint})]})});var Automation=import_react82.memo((props)=>{let labels=SUB_TABS[AUTOMATION_TAB];import_react82.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane2,{visible:props.sub===0,children:$jsx(Kanban,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane2,{visible:props.sub===1,children:$jsx(Agents,{focused:!!props.focused&&props.sub===1,sessionId:props.sessionId,onSwitchProfile:props.onSwitchProfile})}),$jsx(Pane2,{visible:props.sub===2,children:$jsx(Cron,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane2=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react95=__toESM(require_react_production(),1);var import_react85=__toESM(require_react_production(),1);init_lane();var int=(lo,hi,what=`${lo}\u2013${hi}`)=>(raw)=>{let n=Number(raw);if(!Number.isInteger(n))return`expected integer ${what}`;if(n<lo||n>hi)return`expected ${what}`;return null},float=(lo,hi)=>(raw)=>{let n=Number(raw);if(!Number.isFinite(n))return`expected number ${lo}\u2013${hi}`;if(n<lo||n>hi)return`expected ${lo}\u2013${hi}`;return null},oneOf=(...opts)=>(raw)=>opts.includes(raw)?null:`expected one of: ${opts.join(" | ")}`,nonNeg=(raw)=>{let n=Number(raw);return Number.isFinite(n)&&n>=0?null:"expected \u2265 0"},RULES={"compression.threshold":float(0.1,0.95),"compression.target_ratio":float(0.05,0.9),"prompt_caching.cache_ttl":(raw)=>/^\d+[smhd]$/.test(raw.trim())?null:"expected duration e.g. 5m, 1h","agent.max_turns":int(1,1e4),"delegation.max_iterations":int(1,1e4),"delegation.max_concurrent_children":int(1,64),"delegation.max_spawn_depth":int(1,3),"agent.gateway_timeout":nonNeg,"agent.gateway_timeout_warning":nonNeg,"agent.gateway_notify_interval":nonNeg,"agent.restart_drain_timeout":nonNeg,"delegation.child_timeout_seconds":int(30,86400),"browser.command_timeout":int(1,600),"approvals.timeout":int(1,3600),"security.tirith_timeout":int(1,120),"agent.api_max_retries":int(0,20),"tool_output.max_bytes":int(1024,1e7),"tool_output.max_lines":int(10,1e5),"sessions.retention_days":int(1,3650),"sessions.min_interval_hours":int(1,720),"agent.service_tier":oneOf("","fast","standard"),"display.busy_input_mode":oneOf("queue","steer","interrupt"),"display.details_mode":oneOf("hidden","collapsed","expanded"),"display.thinking_mode":oneOf("collapsed","truncated","full"),"display.tool_progress":oneOf("off","new","all","verbose"),"display.final_response_markdown":oneOf("render","strip","raw"),"logging.level":oneOf("DEBUG","INFO","WARNING","ERROR"),"approvals.mode":oneOf("manual","ask","yolo","deny"),"code_execution.mode":oneOf("project","strict")},check=(key2,raw)=>RULES[key2]?.(raw)??null;init_schema();init_lane();var SELECTS={"terminal.backend":["local","docker","ssh","modal","daytona","singularity","vercel_sandbox"],"tts.provider":["edge","elevenlabs","openai","neutts","xai","mistral"],"display.skin":[...SKINS],"logging.level":["DEBUG","INFO","WARNING","ERROR"],"agent.reasoning_effort":["","none","minimal","low","medium","high","xhigh"],"display.busy_input_mode":["queue","steer","interrupt"],"display.details_mode":["hidden","collapsed","expanded"],"display.thinking_mode":["collapsed","truncated","full"],"display.tool_progress":["off","new","all","verbose"],"approvals.mode":["manual","ask","yolo","deny"]},get4=(obj,path7)=>{let cur=obj;for(let p of path7.split("."))if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},classify2=(key2,t2)=>{if(route(key2).via==="readonly")return"readonly";if(SELECTS[key2])return"select";if(t2==="bool")return"boolean";if(t2==="int"||t2==="float")return"number";return"string"},labelOf=(key2)=>{let raw=SCHEMA[key2]?.group??key2.split(".")[0];return key2.startsWith(`${raw}.`)?key2.slice(raw.length+1):key2},buildFields=(user)=>{let seen=new Set,out=[];for(let key2 of SCHEMA_KEYS){let s=SCHEMA[key2],uv=get4(user,key2),set2=uv!==void 0;out.push({key:key2,label:labelOf(key2),type:classify2(key2,s.type),value:set2?uv:s.default,set:set2,doc:s.doc,effect:s.effect,options:SELECTS[key2]}),seen.add(key2)}let walk=(obj,prefix="")=>{for(let[k2,v2]of Object.entries(obj)){let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2)){if(SCHEMA[key2]?.type==="dict"){seen.add(key2);continue}walk(v2,key2);continue}if(seen.has(key2))continue;out.push({key:key2,label:labelOf(key2),type:Array.isArray(v2)?"readonly":typeof v2==="boolean"?"boolean":typeof v2==="number"?"number":"string",value:v2,set:!0,doc:"",effect:"live"})}};return walk(user),out},MERGE={approvals:"security",privacy:"security",secrets:"security",checkpoints:"agent",context:"agent",cron:"agent",network:"agent",model_catalog:"general",onboarding:"general",human_delay:"display",dashboard:"display",gateway:"display",tool_output:"agent",prompt_caching:"compression",code_execution:"terminal",lsp:"agent",x_search:"agent",slack:"platforms",telegram:"platforms",mattermost:"platforms",discord:"platforms",whatsapp:"platforms",matrix:"platforms"},rawGroupOf=(key2)=>SCHEMA[key2]?.group??(key2.includes(".")?key2.split(".")[0]:"general"),groupOf=(key2)=>{let raw=rawGroupOf(key2);return MERGE[raw]??raw},sections=(group2,fields)=>{let by=new Map;for(let f of fields){let r=rawGroupOf(f.key);if(!by.has(r))by.set(r,[]);by.get(r).push(f)}if(by.size<=1)return[{head:null,items:fields}];return[...by.keys()].sort((a,b2)=>a===group2?-1:b2===group2?1:a.localeCompare(b2)).map((r)=>({head:r,items:by.get(r)}))},GROUPS=(()=>{let g=new Set(["general"]);for(let k2 of SCHEMA_KEYS)g.add(groupOf(k2));return[...g]})(),EFFECT_GLYPH={live:"",session:"\u21BB",restart:"\u27F3"};init_lane();var AUX_TASKS=[{key:"vision",label:"Vision",hint:"Image analysis"},{key:"web_extract",label:"Web Extract",hint:"Page summarization"},{key:"compression",label:"Compression",hint:"Context compaction"},{key:"session_search",label:"Session Search",hint:"Recall queries"},{key:"skills_hub",label:"Skills Hub",hint:"Skill search"},{key:"approval",label:"Approval",hint:"Smart auto-approve"},{key:"mcp",label:"MCP",hint:"MCP tool routing"},{key:"title_generation",label:"Title Gen",hint:"Session titles"},{key:"triage_specifier",label:"Triage Specifier",hint:"Kanban spec fleshing"},{key:"kanban_decomposer",label:"Kanban Decomposer",hint:"Task decomposition"},{key:"profile_describer",label:"Profile Describer",hint:"Auto profile descriptions"},{key:"curator",label:"Curator",hint:"Skill-usage review"}],dig=(o,...path7)=>path7.reduce((c,p)=>c&&typeof c==="object"?c[p]:void 0,o),str2=(v2)=>typeof v2==="string"?v2:"",readSlots=(raw)=>{let main2={kind:"main",key:"main",label:"Main model",hint:"Primary agent model",provider:str2(dig(raw,"model","provider")),model:str2(dig(raw,"model","default"))||str2(dig(raw,"model","name")),auto:!1},aux=AUX_TASKS.map((t2)=>{let p=str2(dig(raw,"auxiliary",t2.key,"provider"));return{kind:"aux",key:t2.key,label:t2.label,hint:t2.hint,provider:p,model:str2(dig(raw,"auxiliary",t2.key,"model")),auto:p===""||p==="auto"}});return[main2,...aux]},staleAuxForMain=(slots,provider)=>slots.filter((s)=>s.kind==="aux"&&!s.auto&&s.provider!==""&&s.provider!=="auto"&&s.provider!==provider),assign=async(gw,slot,provider,model)=>{if(slot==="main"){let r=await gw.request("config.set",{key:"model",value:`${model} --provider ${provider} --global`,session_id:void 0});return{ok:["model.default","model.provider"],failed:[],warnings:[],warning:r.warning}}return writeConfig(gw,[{key:`auxiliary.${slot}.provider`,to:provider},{key:`auxiliary.${slot}.model`,to:model}])},resetAux=(gw,slot)=>{let keys=slot==="all"?AUX_TASKS.map((t2)=>t2.key):[slot];return writeConfig(gw,keys.flatMap((k2)=>[{key:`auxiliary.${k2}.provider`,to:"auto"},{key:`auxiliary.${k2}.model`,to:""}]))};var import_react84=__toESM(require_react_production(),1);var import_react83=__toESM(require_react_production(),1);var SecretPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react83.useState("");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,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,$jsx(MaskInput,{value,input:setValue,submit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)}}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel":"Esc cancel"})})]})};var configured=(p)=>(p.models?.length??0)>0,setupDescription=(p)=>{if(p.warning)return p.warning;if(p.auth_type==="api_key"&&p.key_env)return`paste ${p.key_env} to activate`;if(p.key_env)return p.key_env;if(p.auth_type)return`run hermes model to configure (${p.auth_type})`;return},providerDescription=(p)=>{if(p.authenticated===!1)return setupDescription(p);return p.total_models?`${p.total_models} models`:void 0},providerHint=(p)=>{if(p.authenticated!==!1)return;return p.auth_type?`auth_type=${p.auth_type}`:void 0},replaceProvider=(data2,slug2,next2)=>({...data2,providers:(data2.providers??[]).map((p)=>p.slug===slug2?next2:p)}),ModelPickerDialog=(props)=>{let dialog=useDialog(),toast=useToast(),theme=useTheme().theme,[data2,setData]=import_react84.useState(null),[step,setStep]=import_react84.useState("provider"),[provider,setProvider]=import_react84.useState(null),[setupProvider,setSetupProvider]=import_react84.useState(null),[global2,setGlobal]=import_react84.useState(!1),refresh=import_react84.useCallback(()=>props.gw.request("model.options").then(setData).catch(()=>setData({providers:[]})),[props.gw]);import_react84.useEffect(()=>{refresh()},[refresh]);let apply=import_react84.useCallback((model,prov)=>{if(props.onApply)return void props.onApply(prov,model).catch((e)=>toast.show({variant:"error",message:e.message}));let value=`${model} --provider ${prov}${global2?" --global":""}`;props.gw.request("config.set",global2?{key:"model",value,session_id:void 0}:{key:"model",value}).then((r)=>{if(toast.show({variant:"success",message:`model \u2192 ${r.value??model}${global2?" (global)":""}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[props.gw,props.onApply,global2,toast]),submitKey=import_react84.useCallback(async(p2,key2)=>{try{let r=await props.gw.request("model.save_key",{slug:p2.slug,api_key:key2});if(r.warning)toast.show({variant:"warning",message:r.warning});let next2=r.provider??(await props.gw.request("model.options")).providers?.find((pp)=>pp.slug===p2.slug);if(!next2){toast.show({variant:"warning",message:"Provider saved; refresh model options to continue"});return}if(setData((d2)=>d2?replaceProvider(d2,p2.slug,next2):d2),configured(next2)){setSetupProvider(null),setProvider(next2.slug),setStep("model"),toast.show({variant:"success",message:`${next2.name} activated`});return}toast.show({variant:"warning",message:next2.warning??"Provider saved but no models were returned"})}catch(e){toast.show({variant:"error",message:e instanceof Error?e.message:String(e)})}},[props.gw,toast]),setup=import_react84.useCallback((p2)=>{let msg=setupDescription(p2);if(p2.auth_type!=="api_key"||!p2.key_env){toast.show({variant:"warning",message:msg??"Run hermes model to configure this provider"});return}setSetupProvider(p2),setStep("setup")},[toast]),onKey=import_react84.useCallback((k2)=>{if(k2.name==="tab"&&!props.onApply)return setGlobal((g)=>!g),!0;if(k2.name==="left"&&step!=="provider")return setStep("provider"),!0;return!1},[step,props.onApply]),footer=props.onApply?$jsx("text",{fg:theme.textMuted,children:step==="model"?"\u2190: providers":" "}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{children:"Scope: "}),$jsx("span",{fg:global2?theme.warning:theme.accent,children:global2?"global (persists to config)":"this session"}),$jsxs("span",{children:[" \xB7 Tab: toggle",step==="model"?" \xB7 \u2190: providers":""]})]});if(!data2)return $jsx("box",{width:50,padding:1,children:$jsx("text",{children:"Loading models\u2026"})});if(step==="setup"&&setupProvider?.key_env)return $jsx(SecretPrompt,{title:`Paste ${setupProvider.key_env}`,label:setupDescription(setupProvider)??`API key for ${setupProvider.name}`,onSubmit:(key2)=>{submitKey(setupProvider,key2)}});if(step==="provider"){let options2=(data2.providers??[]).toSorted((a,b2)=>Number(Boolean(b2.is_current))-Number(Boolean(a.is_current))).map((p2)=>({title:p2.name,value:p2.slug,description:providerDescription(p2),hint:providerHint(p2),category:p2.is_current?"Current":p2.authenticated===!1?"Setup required":"Available"}));return $jsx(DialogSelect,{title:props.title??"Switch Provider",options:options2,current:data2.provider,onSelect:(o)=>{let p2=data2.providers?.find((pp)=>pp.slug===o.value);if(p2?.authenticated===!1||p2&&!configured(p2))return void setup(p2);setProvider(o.value),setStep("model")},onKey,placeholder:"Search providers...",footer})}let p=data2.providers?.find((pp)=>pp.slug===provider),options=(p?.models??[]).map((m2)=>{let caps=p?.capabilities?.[m2],badges=[caps?.fast?"fast":"",caps?.reasoning?"reasoning":""].filter(Boolean);return{title:m2,value:m2,hint:badges.length>0?badges.join(" \xB7 "):void 0}});return $jsx(DialogSelect,{title:props.title?`${props.title} \xB7 ${p?.name??provider}`:`Switch Model (${p?.name??provider})`,options,current:provider===data2.provider?data2.model:void 0,onSelect:(o)=>{if(provider)apply(o.value,provider);dialog.clear()},onKey,placeholder:"Search models...",footer})},openModelPicker=(dialog,gw,opts)=>{dialog.replace($jsx(ModelPickerDialog,{gw,title:opts?.title,onApply:opts?.onApply}))};var flatten=(obj,prefix="")=>Object.entries(obj).flatMap(([k2,v2])=>{let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2))return flatten(v2,key2);return[[key2,v2]]}),setNested=(obj,path7,val)=>{let parts2=path7.split("."),cur=obj;for(let i=0;i<parts2.length-1;i++){if(!cur[parts2[i]]||typeof cur[parts2[i]]!=="object")cur[parts2[i]]={};cur=cur[parts2[i]]}cur[parts2[parts2.length-1]]=val},getNested=(obj,path7)=>{let parts2=path7.split("."),cur=obj;for(let p of parts2)if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},FieldRow=import_react85.memo((props)=>{let theme=useTheme().theme,f=props.field,bg2=props.active?theme.backgroundElement:void 0,indicator=props.active?"\u25B8 ":" ",mark2=props.changed?"\u25CF ":f.set?"\xB7":" ",markFg=props.changed?theme.warning:theme.textMuted,display=()=>{if(props.editing)return props.buf+"\u2588";if(f.type==="readonly"){let n=Array.isArray(f.value)?f.value.length:f.value&&typeof f.value==="object"?Object.keys(f.value).length:0;return n===0?"\u2014":`${n} item${n===1?"":"s"}`}if(f.type==="boolean")return f.value?"\u2713 ON":"\u2717 OFF";return String(f.value??"")},hint=()=>{if(props.readonly||f.type==="readonly")return"\uD83D\uDD12";if(f.type==="boolean")return"[space]";if(f.type==="select")return"[h/l]";return"[enter]"},ro=props.readonly||f.type==="readonly",valFg=ro||!f.set?theme.textMuted:f.type==="boolean"?f.value?theme.success:theme.error:theme.text,labelFg=ro?theme.textMuted:props.active?theme.accent:theme.text,lead=4+(props.badge!==void 0?12:0),glyph=props.active?EFFECT_GLYPH[f.effect]:"";return $jsxs("box",{id:props.id,flexDirection:"column",backgroundColor:bg2,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:markFg,children:mark2}),$jsx(Col,{w:2,fg:props.active?theme.primary:theme.text,children:indicator}),props.badge!==void 0?$jsx(Col,{w:12,fg:theme.textMuted,children:props.badge}):null,$jsx(Col,{w:40,fg:labelFg,children:f.label}),$jsx(Col,{grow:!0,min:6,fg:valFg,children:display()}),$jsx(Col,{w:2,fg:theme.textMuted,children:glyph}),$jsx(Col,{w:9,fg:theme.textMuted,right:!0,children:props.active?hint():""})]}),props.error?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:lead+40,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:6,fg:theme.error,children:`\u2717 ${props.error}`})]}):props.active&&f.doc?$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:lead,flexShrink:0}),$jsx("box",{width:40,flexShrink:0,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:f.doc})})]}):null]})}),SlotRow=import_react85.memo((p)=>{let theme=useTheme().theme,main2=p.s.kind==="main",val=main2?`${p.s.provider||"(unset)"} \xB7 ${p.s.model||"(unset)"}`:p.s.auto?"auto (use main model)":`${p.s.provider} \xB7 ${p.s.model||"(provider default)"}`;return $jsxs("box",{id:p.id,flexDirection:"row",height:1,backgroundColor:p.on?theme.backgroundElement:void 0,children:[$jsx(Col,{w:2,fg:p.on?theme.primary:theme.text,children:p.on?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:main2?theme.primary:theme.textMuted,children:main2?"\u2605":" "}),$jsx(Col,{w:16,fg:p.on?theme.accent:theme.text,children:p.s.label}),$jsx(Col,{w:22,fg:theme.textMuted,children:p.s.hint}),$jsx(Col,{grow:!0,min:10,fg:p.s.auto?theme.textMuted:theme.text,children:val}),$jsx(Col,{w:14,fg:theme.textMuted,right:!0,children:p.on?main2?"[enter]":"[enter] [x]":""})]})}),Config=import_react85.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),toast=useToast(),dialog=useDialog(),[raw,setRaw]=import_react85.useState({}),[original,setOriginal]=import_react85.useState({}),[yaml,setYaml]=import_react85.useState(""),[mode,setMode]=import_react85.useState("form"),[cat,setCat]=import_react85.useState(0),[cursor,setCursor]=import_react85.useState(0),[editing,setEditing]=import_react85.useState(!1),[buf,setBuf]=import_react85.useState(""),[err,setErr]=import_react85.useState({}),[searching,setSearching]=import_react85.useState(!1),[query,setQuery]=import_react85.useState(""),[focus,setFocus]=import_react85.useState("categories"),[managed,setManaged]=import_react85.useState(null);import_react85.useEffect(()=>{managedSystem().then(setManaged)},[]);let load4=import_react85.useCallback(()=>{gw.request("config.get",{key:"full"}).then((res)=>{let parsed=res.config??{};setRaw(structuredClone(parsed)),setOriginal(structuredClone(parsed)),setYaml($stringify(parsed)),setErr({})}).catch(()=>{setRaw({}),setOriginal({}),setYaml("")})},[gw]);import_react85.useEffect(()=>{load4()},[load4]);let all=buildFields(raw),grouped=all.reduce((map,f)=>{let g=groupOf(f.key);if(!map.has(g))map.set(g,[]);return map.get(g).push(f),map},new Map(GROUPS.map((g)=>[g,[]]))),groups=[...grouped.keys()];groups.splice(1,0,"models");let active=groups[cat]??groups[0],onSlots=active==="models"&&!searching,slots=readSlots(raw),secs=searching&&query.trim()?[{head:null,items:all.filter((f)=>f.key.toLowerCase().includes(query.toLowerCase()))}]:sections(active,grouped.get(active)??[]),fields=secs.flatMap((s)=>s.items),count3=onSlots?slots.length:fields.length,follow=useFollow("cfg"),catFollow=useFollow("cfg-cat"),changed=(key2)=>JSON.stringify(getNested(raw,key2))!==JSON.stringify(getNested(original,key2)),nChanged=all.reduce((n,f)=>n+(changed(f.key)?1:0),0),update=(key2,val)=>{let next2=structuredClone(raw);setNested(next2,key2,val),setRaw(next2),setYaml($stringify(next2))},fmt3=(v2)=>v2===void 0?"\u2014":Array.isArray(v2)?v2.join(", "):String(v2),save2=async()=>{if(managed){toast.show({variant:"error",message:`Managed by ${managed} \u2014 edit configuration.nix`});return}let nErr=Object.keys(err).length;if(nErr>0){toast.show({variant:"error",message:`${nErr} invalid field${nErr===1?"":"s"}`});return}let target=mode==="yaml"?$parse(yaml)??{}:raw,diffs=flatten(target).filter(([key2])=>JSON.stringify(getNested(target,key2))!==JSON.stringify(getNested(original,key2))).map(([key2,val])=>({key:key2,from:getNested(original,key2),to:val}));if(diffs.length===0){toast.show({variant:"info",message:"No changes"});return}let body=diffs.map((d2)=>`${d2.key}: ${fmt3(d2.from)} \u2192 ${fmt3(d2.to)}`).join(`
|
|
4136
4136
|
`);if(!await openConfirm(dialog,{title:`Write ${diffs.length} change${diffs.length===1?"":"s"} to config.yaml?`,body,yes:"save"}))return;let res=await writeConfig(gw,diffs.map((d2)=>({key:d2.key,to:d2.to})));for(let w2 of res.warnings)toast.show({variant:"info",message:`${w2.key}: ${w2.msg}`});if(load4(),res.failed.length>0){toast.show({variant:"error",message:`${res.failed.length} failed: ${res.failed.map((f)=>f.key).join(", ")}`});return}let landed=diffs.filter((d2)=>res.ok.includes(d2.key)),miss=await verifyWrite(gw,landed.map((d2)=>({key:d2.key,to:d2.to})));if(miss.length>0){toast.show({variant:"error",message:`Write didn't land: ${miss.join(", ")}`});return}let tier=maxEffect(res.ok);if(tier==="restart"){if(await openConfirm(dialog,{title:`Saved \u2014 ${res.ok.length} setting${res.ok.length===1?"":"s"} need a gateway restart`,body:"Restart now? This interrupts any running turn.",yes:"restart now",no:"later",danger:!0}))gw.start(),toast.show({variant:"info",message:"Gateway restarting\u2026"});return}toast.show({variant:"success",message:tier==="live"?"Saved":"Saved \u2014 new sessions pick this up"})},pick=import_react85.useCallback((s)=>{if(managed)return toast.show({variant:"error",message:`Managed by ${managed}`});let warnStaleAux=async(prov)=>{let stale=staleAuxForMain(readSlots(raw),prov);if(stale.length===0)return;let names=stale.map((x2)=>x2.label).join(", ");if(!await openConfirm(dialog,{title:"Auxiliary models still pinned to another provider",body:`${names}
|
|
4137
4137
|
|
|
4138
4138
|
Reset these slots to auto so they follow the main model?`,yes:"reset stale",no:"keep"})){toast.show({variant:"warning",message:`Aux still pinned to another provider: ${names}. Press X to reset all to auto.`});return}for(let slot of stale){let r=await resetAux(gw,slot.key);if(r.failed.length){toast.show({variant:"error",message:`${slot.label}: ${r.failed.map((f)=>f.err).join("; ")}`});return}}toast.show({variant:"success",message:`Reset ${stale.length} aux slot${stale.length===1?"":"s"} \u2192 auto`}),load4()};openModelPicker(dialog,gw,{title:s.kind==="main"?"Set main model":`Set auxiliary \xB7 ${s.label}`,onApply:async(prov,model)=>{let r=await assign(gw,s.key,prov,model);if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});if(toast.show({variant:"success",message:s.kind==="main"?`main \u2192 ${prov} \xB7 ${model}`:`${s.key} \u2192 ${prov} \xB7 ${model}`}),r.warning)toast.show({variant:"warning",message:r.warning});if(load4(),s.kind==="main")await warnStaleAux(prov)}})},[gw,dialog,toast,load4,managed,raw]),unset=import_react85.useCallback((s)=>{if(managed||s.kind!=="aux"||s.auto)return;resetAux(gw,s.key).then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});toast.show({variant:"success",message:`${s.key} \u2192 auto`}),load4()})},[gw,toast,load4,managed]),unsetAll=import_react85.useCallback(()=>openConfirm(dialog,{title:"Reset all auxiliary slots to auto?",body:`${AUX_TASKS.length} slots. Each falls back to the main model.`,yes:"reset",danger:!0}).then((ok)=>{if(!ok)return;resetAux(gw,"all").then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:`${r.failed.length} failed`});toast.show({variant:"success",message:"All auxiliary slots \u2192 auto"}),load4()})}),[gw,dialog,toast,load4]),keys=useKeys();if(useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(keys.match("config.mode",key2)&&!editing&&!searching){setMode((m2)=>m2==="form"?"yaml":"form");return}if(keys.match("config.save",key2))return void save2();if(mode==="yaml"){if(key2.name==="backspace"){setYaml((prev)=>prev.slice(0,-1));return}if(key2.name==="return"){setYaml((prev)=>prev+`
|