herm-tui 1.3.0-dev.13 → 1.3.0-dev.14

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/db.worker.js CHANGED
@@ -34,7 +34,7 @@ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defP
34
34
  JOIN messages m ON m.id = messages_fts.rowid
35
35
  JOIN sessions s ON s.id = m.session_id
36
36
  WHERE messages_fts MATCH ?
37
- ORDER BY rank LIMIT ?`)?.all(m,limit*4)??[],seen=new Set;return raw.filter((r)=>!seen.has(r.session_id)&&(seen.add(r.session_id),!0)).slice(0,limit)}finally{end()}}function rename(sid,title){let db=new Database(conn.path);try{return db.run("UPDATE sessions SET title = ? WHERE id = ?",[title,sid]),db.query("SELECT changes() AS c").get().c>0}finally{db.close()}}function remove(sid){let db=new Database(conn.path);try{if(!db.query("SELECT 1 FROM sessions WHERE id = ?").get(sid))return!1;return db.run("UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id = ?",[sid]),db.run("DELETE FROM messages WHERE session_id = ?",[sid]),db.run("DELETE FROM sessions WHERE id = ?",[sid]),!0}finally{db.close()}}var HERMES,SRC,conn,setHome=(h)=>{let next=`${h}/state.db`;if(conn.path===next)return;conn.path=SRC.file=next,resetDb()},stateDb=()=>{if(conn.ro)return conn.ro;try{return conn.ro=new Database(conn.path,{readonly:!0})}catch{return null}},resetDb=()=>{for(let s of stmts.values())s.finalize();stmts.clear(),conn.ro?.close(),conn.ro=null},stmts,q=(sql)=>{let db=stateDb();if(!db)return null;let s=stmts.get(sql);if(!s)stmts.set(sql,s=db.query(sql));return s},SUB=(c)=>`(p.ended_at IS NULL OR ${c}.started_at < p.ended_at)`,CONT=(c)=>`(p.end_reason = 'compression' AND ${c}.started_at >= p.ended_at)`,BR=(c)=>`(p.end_reason = 'branched' AND ${c}.started_at >= p.ended_at)`,COLS=`
37
+ ORDER BY rank LIMIT ?`)?.all(m,limit*4)??[],seen=new Set;return raw.filter((r)=>!seen.has(r.session_id)&&(seen.add(r.session_id),!0)).slice(0,limit)}finally{end()}}function rename(sid,title){let db=new Database(conn.path);try{return db.run("UPDATE sessions SET title = ? WHERE id = ?",[title,sid]),db.query("SELECT changes() AS c").get().c>0}finally{db.close()}}function remove(sid){let db=new Database(conn.path);try{if(!db.query("SELECT 1 FROM sessions WHERE id = ?").get(sid))return!1;return db.run("UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id = ?",[sid]),db.run("DELETE FROM messages WHERE session_id = ?",[sid]),db.run("DELETE FROM sessions WHERE id = ?",[sid]),!0}finally{db.close()}}var HERMES,SRC,conn,setHome=(h)=>{let next=`${h}/state.db`;if(conn.path===next)return;conn.path=SRC.file=next,resetDb()},stateDb=()=>{if(conn.ro)return conn.ro;try{return conn.ro=new Database(conn.path,{readwrite:!0,create:!1})}catch{return null}},resetDb=()=>{for(let s of stmts.values())s.finalize();stmts.clear(),conn.ro?.close(),conn.ro=null},stmts,q=(sql)=>{let db=stateDb();if(!db)return null;let s=stmts.get(sql);if(!s)stmts.set(sql,s=db.query(sql));return s},SUB=(c)=>`(p.ended_at IS NULL OR ${c}.started_at < p.ended_at)`,CONT=(c)=>`(p.end_reason = 'compression' AND ${c}.started_at >= p.ended_at)`,BR=(c)=>`(p.end_reason = 'branched' AND ${c}.started_at >= p.ended_at)`,COLS=`
38
38
  s.id, s.source, s.model, s.started_at, s.ended_at, s.end_reason,
39
39
  s.message_count, s.tool_call_count,
40
40
  s.input_tokens, s.output_tokens,
package/index.js CHANGED
@@ -3304,7 +3304,7 @@ ${closingIndent}}`}default:return"any"}}function formatFunctionDefinitions(funct
3304
3304
  JOIN messages m ON m.id = messages_fts.rowid
3305
3305
  JOIN sessions s ON s.id = m.session_id
3306
3306
  WHERE messages_fts MATCH ?
3307
- ORDER BY rank LIMIT ?`)?.all(m2,limit*4)??[],seen=new Set;return raw.filter((r)=>!seen.has(r.session_id)&&(seen.add(r.session_id),!0)).slice(0,limit)}finally{end()}}function rename(sid,title){let db=new Database(conn.path);try{return db.run("UPDATE sessions SET title = ? WHERE id = ?",[title,sid]),db.query("SELECT changes() AS c").get().c>0}finally{db.close()}}function remove(sid){let db=new Database(conn.path);try{if(!db.query("SELECT 1 FROM sessions WHERE id = ?").get(sid))return!1;return db.run("UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id = ?",[sid]),db.run("DELETE FROM messages WHERE session_id = ?",[sid]),db.run("DELETE FROM sessions WHERE id = ?",[sid]),!0}finally{db.close()}}var HERMES,SRC,conn,setHome=(h2)=>{let next=`${h2}/state.db`;if(conn.path===next)return;conn.path=SRC.file=next,resetDb()},stateDb=()=>{if(conn.ro)return conn.ro;try{return conn.ro=new Database(conn.path,{readonly:!0})}catch{return null}},resetDb=()=>{for(let s of stmts.values())s.finalize();stmts.clear(),conn.ro?.close(),conn.ro=null},stmts,q2=(sql)=>{let db=stateDb();if(!db)return null;let s=stmts.get(sql);if(!s)stmts.set(sql,s=db.query(sql));return s},SUB=(c)=>`(p.ended_at IS NULL OR ${c}.started_at < p.ended_at)`,CONT=(c)=>`(p.end_reason = 'compression' AND ${c}.started_at >= p.ended_at)`,BR=(c)=>`(p.end_reason = 'branched' AND ${c}.started_at >= p.ended_at)`,COLS=`
3307
+ ORDER BY rank LIMIT ?`)?.all(m2,limit*4)??[],seen=new Set;return raw.filter((r)=>!seen.has(r.session_id)&&(seen.add(r.session_id),!0)).slice(0,limit)}finally{end()}}function rename(sid,title){let db=new Database(conn.path);try{return db.run("UPDATE sessions SET title = ? WHERE id = ?",[title,sid]),db.query("SELECT changes() AS c").get().c>0}finally{db.close()}}function remove(sid){let db=new Database(conn.path);try{if(!db.query("SELECT 1 FROM sessions WHERE id = ?").get(sid))return!1;return db.run("UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id = ?",[sid]),db.run("DELETE FROM messages WHERE session_id = ?",[sid]),db.run("DELETE FROM sessions WHERE id = ?",[sid]),!0}finally{db.close()}}var HERMES,SRC,conn,setHome=(h2)=>{let next=`${h2}/state.db`;if(conn.path===next)return;conn.path=SRC.file=next,resetDb()},stateDb=()=>{if(conn.ro)return conn.ro;try{return conn.ro=new Database(conn.path,{readwrite:!0,create:!1})}catch{return null}},resetDb=()=>{for(let s of stmts.values())s.finalize();stmts.clear(),conn.ro?.close(),conn.ro=null},stmts,q2=(sql)=>{let db=stateDb();if(!db)return null;let s=stmts.get(sql);if(!s)stmts.set(sql,s=db.query(sql));return s},SUB=(c)=>`(p.ended_at IS NULL OR ${c}.started_at < p.ended_at)`,CONT=(c)=>`(p.end_reason = 'compression' AND ${c}.started_at >= p.ended_at)`,BR=(c)=>`(p.end_reason = 'branched' AND ${c}.started_at >= p.ended_at)`,COLS=`
3308
3308
  s.id, s.source, s.model, s.started_at, s.ended_at, s.end_reason,
3309
3309
  s.message_count, s.tool_call_count,
3310
3310
  s.input_tokens, s.output_tokens,
@@ -4105,11 +4105,11 @@ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid)
4105
4105
  `,skE);while(end<text2.length&&end>=0){let nl=text2.indexOf(`
4106
4106
  `,end+1);if(nl<0){end=text2.length;break}let line2=text2.slice(end+1,nl).trim();if(line2.startsWith("#"))break;if(line2===""){if(text2.slice(nl+1,text2.indexOf(`
4107
4107
  `,nl+1)).trim().startsWith("#")){end=nl;break}}end=nl}mark2(skH,end+1,"skills","Skills Catalog",makeSource("skills","skills/"))}let proj=text2.indexOf("# Project Context");if(proj>=0){let conv2=text2.indexOf("Conversation started:");mark2(proj,conv2>proj?conv2:text2.length,"project","Project Context",makeSource("AGENTS.md"))}let conv=text2.indexOf("Conversation started:");if(conv>=0)mark2(conv,text2.length,"meta","Session Metadata");let start2=-1;for(let i=0;i<=text2.length;i++)if(i<text2.length&&!used[i]){if(start2<0)start2=i}else if(start2>=0){let slice=text2.slice(start2,i);if(slice.trim().length>0)sections.push({id:"other",label:"Other",chars:slice.length,tokens:count2(slice),text:slice});start2=-1}return sections.sort((a,b2)=>text2.indexOf(a.text)-text2.indexOf(b2.text))}function classifyTools(tools){let system=[],mcp=[];for(let t2 of tools)if(t2.name.startsWith("mcp_"))mcp.push(t2);else system.push(t2);return{system,mcp}}function toolTokens(tool){return Math.ceil((tool.descriptionLength+tool.paramsLength)/CPT)}function build(opts){let pct=(t2)=>opts.contextLength>0?t2/opts.contextLength*100:0,result=[],byId2=new Map;for(let s of opts.sections)byId2.set(s.id,s);let promptChildren=opts.sections.filter((sec)=>SYSTEM_PROMPT_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),promptTok=promptChildren.reduce((s,c)=>s+c.tokens,0);if(promptTok>0)result.push({id:"system_prompt",label:"System Prompt",tokens:promptTok,percent:pct(promptTok),children:promptChildren});let{system:sysTools,mcp:mcpTools}=classifyTools(opts.tools),sysToolsTok=sysTools.reduce((s,t2)=>s+toolTokens(t2),0);if(sysToolsTok>0)result.push({id:"system_tools",label:"System Tools",tokens:sysToolsTok,percent:pct(sysToolsTok)});let mcpToolsTok=mcpTools.reduce((s,t2)=>s+toolTokens(t2),0);if(mcpToolsTok>0)result.push({id:"mcp_tools",label:"MCP Tools",tokens:mcpToolsTok,percent:pct(mcpToolsTok)});let memChildren=opts.sections.filter((sec)=>MEMORY_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),memTok=memChildren.reduce((s,c)=>s+c.tokens,0);if(memTok>0)result.push({id:"memory",label:"Memory",tokens:memTok,percent:pct(memTok),children:memChildren});let skillsSec=byId2.get("skills"),skillsTok=skillsSec?.tokens??opts.skillsTokens??0;if(skillsTok>0)result.push({id:"skills",label:"Skills",tokens:skillsTok,percent:pct(skillsTok),section:skillsSec});if(opts.conversationTokens>0){let ct=Math.min(opts.conversationTokens,opts.inputTokens||opts.conversationTokens);result.push({id:"conversation",label:"Conversation",tokens:ct,percent:pct(ct)})}let taken=result.reduce((s,g)=>s+g.tokens,0),free=Math.max(0,opts.contextLength-taken);return result.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),result}function drill(group){if(!group.children||group.children.length===0)return[];let total=group.tokens;return group.children.map((c)=>({...c,percent:total>0?c.tokens/total*100:0}))}function cells(segments,fallback="free"){let filled=segments.flatMap((seg)=>Array.from({length:Math.round(seg.percent/100*GRID)},()=>({id:seg.id}))),pad=Array.from({length:Math.max(0,GRID-filled.length)},()=>({id:fallback}));return[...filled,...pad].slice(0,GRID)}var import_react54=__toESM(require_react_production(),1);var FileLink=import_react54.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react54.useState(!1);return $jsx("box",{height:1,onMouseDown:()=>openFile(source.file),onMouseOver:()=>setHovered(!0),onMouseOut:()=>setHovered(!1),children:$jsx("text",{fg:theme.info,attributes:hovered?TextAttributes.UNDERLINE:TextAttributes.NONE,children:children2??source.label})})}),KVLink=(props)=>{let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx(FileLink,{source:props.source,children:props.text??props.source.label})})]})};var GOLDEN_ANGLE=137.50776405003785;function luminance(c){return 0.299*c.r+0.587*c.g+0.114*c.b}function rgbaToHsl(c){let{r,g,b:b2}=c,max=Math.max(r,g,b2),min=Math.min(r,g,b2),l=(max+min)/2,d2=max-min;if(d2===0)return[0,0,l];let s=l>0.5?d2/(2-max-min):d2/(max+min),h2;switch(max){case r:h2=(g-b2)/d2+(g<b2?6:0);break;case g:h2=(b2-r)/d2+2;break;default:h2=(r-g)/d2+4}return[h2*60,s,l]}function hslToRgba(h2,s,l){if(h2=(h2%360+360)%360/360,s===0)return RGBA.fromValues(l,l,l,1);let q3=l<0.5?l*(1+s):l+s-l*s,p=2*l-q3,ch=(t2)=>{if(t2<0)t2+=1;if(t2>1)t2-=1;if(t2<0.16666666666666666)return p+(q3-p)*6*t2;if(t2<0.5)return q3;if(t2<0.6666666666666666)return p+(q3-p)*(0.6666666666666666-t2)*6;return p};return RGBA.fromValues(ch(h2+0.3333333333333333),ch(h2),ch(h2-0.3333333333333333),1)}function categorical(seed,bg2,n){let[h0]=rgbaToHsl(seed),dark=luminance(bg2)<0.5,s=dark?0.6:0.7,l=dark?0.62:0.42,out=[];for(let i=0;i<n;i++)out.push(hslToRgba(h0+i*GOLDEN_ANGLE,s,l));return out}var DEFAULT_CTX=128000,COLS2=16,SLOTS2=["system_prompt","system_tools","mcp_tools","memory","skills","conversation","soul","mem0","user","project","meta","other"],SLOT=Object.fromEntries(SLOTS2.map((id,i)=>[id,i])),rampCache=new WeakMap;function ramp2(theme){let r=rampCache.get(theme);if(!r)rampCache.set(theme,r=categorical(theme.primary,theme.background,SLOTS2.length));return r}function clr(id,theme){if(id==="free")return theme.borderSubtle;return ramp2(theme)[SLOT[id]??SLOT.other]}var fmt2=(n)=>{if(n>=1e6)return`${(n/1e6).toFixed(1)}M`;if(n>=1e4)return`${Math.round(n/1000)}k`;if(n>=1000)return`${(n/1000).toFixed(1)}k`;return String(n)},est=(s)=>s?count2(s):0,bar=(pct,w2=20)=>{let f=Math.round(Math.max(0,Math.min(100,pct))/100*w2);return`[${"\u2588".repeat(f)}${"\u2591".repeat(Math.max(0,w2-f))}]`},SectionPanel=import_react55.memo(({seg,theme})=>{let{syntaxStyle}=useTheme(),sec=seg.section;if(!sec)return null;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsxs("text",{children:[sec.chars.toLocaleString()," chars \xB7 ~",fmt2(sec.tokens)," tokens"]}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsx("markdown",{content:sec.text,fg:theme.markdownText,syntaxStyle})]})}),MemoryPanel=import_react55.memo(({seg,theme,label,chars,limit,pct,entries,source})=>$jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:$jsx("strong",{children:label})}),source?$jsxs($Fragment2,{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:[entries.length," entries:"]}),entries.map((e,i)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",e]},i))]})),SkillsPanel=import_react55.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line2 of sec.text.split(`
4108
- `)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react55.memo(({seg,theme,tools,kind})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label=kind==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind==="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(kind,theme),children:"\u25FC"})," ",label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react55.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment2,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react55.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment2,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),Context=import_react55.memo(({messages=NO_MESSAGES,info,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),recentSessions=useHome("recentSessions"),liveSessions=useHome("liveSessions"),[wire,setWire]=import_react55.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react55.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react55.useState(null),[selected,setSelected]=import_react55.useState(null),[drilled,setDrilled]=import_react55.useState(null);import_react55.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let session=recentSessions?.[0],ctxLen=info?.context_max??DEFAULT_CTX,lastPrompt=(session?Object.values(liveSessions??{}).find((ls)=>ls.session_id===session.id):void 0)?.last_prompt_tokens??0,fill=wire.calls>0?wire.input:lastPrompt>0?lastPrompt:session?.input_tokens??0,cumulative=wire.calls===0&&lastPrompt===0&&(session?.input_tokens??0)>0,output=wire.calls>0?wire.output:session?.output_tokens??0,pct=ctxLen>0?Math.round(fill/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react55.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react55.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),top=import_react55.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:toolsInfo?.tools??[]}),[ctxLen,fill,sections,convTok,toolsInfo?.tools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react55.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":"free"),[view,drilledGroup]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react55.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react55.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react55.useRef(0),segs=view.filter((s)=>s.tokens>0),idx2=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx2):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&&toolsInfo){let{system}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&toolsInfo){let{mcp}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):$jsx("span",{fg:theme.info,children:" (click group to expand)"})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})})]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:wire.calls===0&&fill===0?"[no data]":cumulative?"[cumulative \u2014 not current fill]":wire.calls===0&&fill>0?"[live session]":"\u2191\u2193 nav \xB7 click a group to drill in",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:`Context \xB7 ${fmt2(fill)} / ${fmt2(ctxLen)} (${pct}%)`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=row*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)})},row))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react57=__toESM(require_react_production(),1);init_hermes_analytics();var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react57.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react57.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc4(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react57.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react57.useState(7),[data2,setData]=import_react57.useState(()=>cache2.get(days)??null),[tools,setTools]=import_react57.useState(()=>cache2.get(days)?.byTool??null),[tick2,setTick]=import_react57.useState(0),gen=import_react57.useRef(0);import_react57.useEffect(()=>{let hit=cache2.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache2.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick2]);let keys=useKeys();useKeyboard((key2)=>{if(!props.focused)return;if(keys.match("list.refresh",key2))return cache2.delete(days),setTick((n)=>n+1);if(key2.raw==="1")return setDays(1);if(key2.raw==="7")return setDays(7);if(key2.raw==="3")return setDays(30);if(key2.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react57.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc4(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react59=__toESM(require_react_production(),1);var SubTabBar=import_react59.memo((props)=>$jsx(TabStrip,{...props}));var SessionsGroup=import_react60.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[SESSIONS_TAB];import_react60.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} group \xB7 shift+\u2190/\u2192 sub`;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:children2}):null;var import_react81=__toESM(require_react_production(),1);var import_react72=__toESM(require_react_production(),1);var import_react63=__toESM(require_react_production(),1);var import_react61=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react61.useState(""),[cursor,setCursor]=import_react61.useState(0),sb=import_react61.useRef(null),theme=useTheme().theme,filtered=import_react61.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react61.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]);import_react61.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]);let rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react61.useEffect(()=>{let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key2)=>{let onToggle=!filterable?()=>{let item=filtered[cursor];if(item)props.onSelect(item)}:void 0;if(handleListKey(keys,key2,{count:filtered.length,setSel:setCursor,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 idx2=0,entries=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($Fragment2,{children:[$jsx("input",{value:filter,onInput:setFilter,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,entries.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=idx2++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>setCursor(i),onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react63.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react63.useRef(new Map),[,setRevision]=import_react63.useState(0),enabled3=import_react63.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react63.useCallback(()=>{let result=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>result.push(c))),result},[]),register=import_react63.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),setRevision((r)=>r+1),()=>{registry.current.delete(id),setRevision((r)=>r+1)}},[]),setEnabled=import_react63.useCallback((val)=>{enabled3.current=val},[]),open2=import_react63.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key2)=>{if(!enabled3.current||dialog.open())return;if(keys.match("palette.open",key2))return open2();for(let c of all())if(c.action&&keys.match(c.action,key2))return c.onSelect()});let value=import_react63.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=()=>{let ctx=import_react63.useContext(Ctx6);if(!ctx)throw Error("useCommand() must be inside <CommandProvider>");return ctx};var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc4(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{let entries=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries.length?"filter\u2026":"no saved spawn trees",options:entries.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc4(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries.find((e)=>e.path===opt.value);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react66=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.accept",key2))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment2,{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($Fragment2,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react66.useState(!1);useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.deny",key2))return props.done(null);if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.done(force);if(key2.name==="space"||key2.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react68=__toESM(require_react_production(),1);import{existsSync as existsSync10,readFileSync as readFileSync3}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join8,basename as basename7,dirname as dirname5}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join8(home3(),".hermes");function root(){let hh=hermesHome(),parent=dirname5(hh);return basename7(parent)==="profiles"?dirname5(parent):hh}function profileNameFrom(hh){let parent=dirname5(hh);return basename7(parent)==="profiles"?basename7(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync3(join8(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=readFileSync3(join8(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean(m2),clean(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join8(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync3(join8(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 readFileSync3(join8(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join8(dir,"distribution.yaml");if(!existsSync10(path7))return null;let data2=(()=>{try{return $parse(readFileSync3(path7,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src=(file,label)=>({file,relative:file.replace(home3()+"/","~/"),label});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join8(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:existsSync10(join8(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync10(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src(dir,dir.replace(home3()+"/","~/")),config:src(join8(dir,"config.yaml"),"config.yaml"),soul:src(join8(dir,"SOUL.md"),"SOUL.md"),env:src(join8(dir,".env"),".env"),distribution:src(join8(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync10(r))jobs.push(info("default",r,active,sticky));let pr=join8(r,"profiles");if(existsSync10(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join8(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(readFileSync3(join8(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikonPath?basename7(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=join8(dir,"state.db");if(existsSync10(dbPath))try{let db=new Database2(dbPath,{readonly:!0}),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(join8(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=existsSync10(join8(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react68.useState(""),[cloneIdx,setCloneIdx]=import_react68.useState(0),[alias,setAlias]=import_react68.useState(!0),[field,setField]=import_react68.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key2)=>{if(key2.name==="escape")return done(null);if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="return")return submit();if(field==="name"){if(key2.name==="backspace")return setName((n)=>n.slice(0,-1));if(key2.raw&&key2.raw.length===1&&/[a-z0-9_-]/.test(key2.raw))return setName((n)=>n+key2.raw);return}if(field==="clone"){if(key2.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key2.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key2.name==="space"||key2.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react70=__toESM(require_react_production(),1);import{rmSync,mkdtempSync}from"fs";import{join as join9}from"path";import{tmpdir}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=mkdtempSync(join9(tmpdir(),"herm-dist-preview-")),cleanup=()=>{try{rmSync(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest=readDistributionManifest(tmp);if(!manifest){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react70.useState("");return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key2)=>{if(keys.match("dialog.accept",key2)||keys.match("dialog.cancel",key2))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react70.useState(""),[alias,setAlias]=import_react70.useState(!1),[field,setField]=import_react70.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel();if(key2.name==="tab")return move(key2.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key2))return fire();if(field==="alias"&&(key2.name==="space"||key2.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react72.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react72.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react72.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react72.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react72.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react72.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc4(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react72.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc4(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc4(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react72.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react72.useState("profiles"),[pView,setPView]=import_react72.useState("list"),[profiles,setProfiles]=import_react72.useState([]),[deleg,setDeleg]=import_react72.useState(null),[liveMap,setLiveMap]=import_react72.useState(()=>new Map),[now,setNow]=import_react72.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react72.useState(0),[dSel,setDSel]=import_react72.useState(0),[err,setErr]=import_react72.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react72.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react72.useRef(void 0),[stats,setStats]=import_react72.useState(()=>new Map),[sticky,setSticky]=import_react72.useState(stickyDefault),loadProfiles=import_react72.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react72.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react72.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react72.useEffect(loadDeleg,[loadDeleg]),import_react72.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react72.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react72.useCallback((i)=>setPSel(i),[]),dHover=import_react72.useCallback((i)=>setDSel(i),[]),pDelete=import_react72.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
4108
+ `)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react55.memo(({seg,theme,tools,kind})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label=kind==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind==="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(kind,theme),children:"\u25FC"})," ",label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react55.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment2,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react55.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment2,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),Context=import_react55.memo(({messages=NO_MESSAGES,info,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),recentSessions=useHome("recentSessions"),liveSessions=useHome("liveSessions"),[wire,setWire]=import_react55.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react55.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react55.useState(null),[selected,setSelected]=import_react55.useState(null),[drilled,setDrilled]=import_react55.useState(null);import_react55.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let session=recentSessions?.[0],ctxLen=info?.context_max??DEFAULT_CTX,lastPrompt=(session?Object.values(liveSessions??{}).find((ls)=>ls.session_id===session.id):void 0)?.last_prompt_tokens??0,fill=wire.calls>0?wire.input:lastPrompt>0?lastPrompt:session?.input_tokens??0,cumulative=wire.calls===0&&lastPrompt===0&&(session?.input_tokens??0)>0,output=wire.calls>0?wire.output:session?.output_tokens??0,pct=ctxLen>0?Math.round(fill/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react55.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react55.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),top=import_react55.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:toolsInfo?.tools??[]}),[ctxLen,fill,sections,convTok,toolsInfo?.tools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react55.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":"free"),[view,drilledGroup]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react55.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react55.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react55.useRef(0),segs=view.filter((s)=>s.tokens>0),idx2=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx2):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&&toolsInfo){let{system}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&toolsInfo){let{mcp}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):$jsx("span",{fg:theme.info,children:" (click group to expand)"})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})})]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:wire.calls===0&&fill===0?"[no data]":cumulative?"[cumulative \u2014 not current fill]":wire.calls===0&&fill>0?"[live session]":"\u2191\u2193 nav \xB7 click a group to drill in",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:`Context \xB7 ${fmt2(fill)} / ${fmt2(ctxLen)} (${pct}%)`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=row*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)})},row))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react57=__toESM(require_react_production(),1);init_hermes_analytics();var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react57.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react57.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc4(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react57.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react57.useState(7),[data2,setData]=import_react57.useState(()=>cache2.get(days)??null),[tools,setTools]=import_react57.useState(()=>cache2.get(days)?.byTool??null),[tick2,setTick]=import_react57.useState(0),gen=import_react57.useRef(0);import_react57.useEffect(()=>{let hit=cache2.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache2.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick2]);let keys=useKeys();useKeyboard((key2)=>{if(!props.focused)return;if(keys.match("list.refresh",key2))return cache2.delete(days),setTick((n)=>n+1);if(key2.raw==="1")return setDays(1);if(key2.raw==="7")return setDays(7);if(key2.raw==="3")return setDays(30);if(key2.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react57.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc4(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react59=__toESM(require_react_production(),1);var SubTabBar=import_react59.memo((props)=>$jsx(TabStrip,{...props}));var SessionsGroup=import_react60.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[SESSIONS_TAB];import_react60.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} group \xB7 shift+\u2190/\u2192 sub`;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:children2}):null;var import_react81=__toESM(require_react_production(),1);var import_react72=__toESM(require_react_production(),1);var import_react63=__toESM(require_react_production(),1);var import_react61=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react61.useState(""),[cursor,setCursor]=import_react61.useState(0),sb=import_react61.useRef(null),theme=useTheme().theme,filtered=import_react61.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react61.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]);import_react61.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]);let rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react61.useEffect(()=>{let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key2)=>{let onToggle=!filterable?()=>{let item=filtered[cursor];if(item)props.onSelect(item)}:void 0;if(handleListKey(keys,key2,{count:filtered.length,setSel:setCursor,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 idx2=0,entries=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($Fragment2,{children:[$jsx("input",{value:filter,onInput:setFilter,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,entries.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=idx2++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>setCursor(i),onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react63.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react63.useRef(new Map),[,setRevision]=import_react63.useState(0),enabled3=import_react63.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react63.useCallback(()=>{let result=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>result.push(c))),result},[]),register=import_react63.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),setRevision((r)=>r+1),()=>{registry.current.delete(id),setRevision((r)=>r+1)}},[]),setEnabled=import_react63.useCallback((val)=>{enabled3.current=val},[]),open2=import_react63.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key2)=>{if(!enabled3.current||dialog.open())return;if(keys.match("palette.open",key2))return open2();for(let c of all())if(c.action&&keys.match(c.action,key2))return c.onSelect()});let value=import_react63.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=()=>{let ctx=import_react63.useContext(Ctx6);if(!ctx)throw Error("useCommand() must be inside <CommandProvider>");return ctx};var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc4(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{let entries=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries.length?"filter\u2026":"no saved spawn trees",options:entries.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc4(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries.find((e)=>e.path===opt.value);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react66=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.accept",key2))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment2,{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($Fragment2,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react66.useState(!1);useKeyboard((key2)=>{if(keys.match("dialog.cancel",key2)||keys.match("dialog.deny",key2))return props.done(null);if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.done(force);if(key2.name==="space"||key2.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react68=__toESM(require_react_production(),1);import{existsSync as existsSync10,readFileSync as readFileSync3}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join8,basename as basename7,dirname as dirname5}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join8(home3(),".hermes");function root(){let hh=hermesHome(),parent=dirname5(hh);return basename7(parent)==="profiles"?dirname5(parent):hh}function profileNameFrom(hh){let parent=dirname5(hh);return basename7(parent)==="profiles"?basename7(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync3(join8(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=readFileSync3(join8(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean(m2),clean(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join8(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync3(join8(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 readFileSync3(join8(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join8(dir,"distribution.yaml");if(!existsSync10(path7))return null;let data2=(()=>{try{return $parse(readFileSync3(path7,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src=(file,label)=>({file,relative:file.replace(home3()+"/","~/"),label});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join8(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:existsSync10(join8(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync10(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src(dir,dir.replace(home3()+"/","~/")),config:src(join8(dir,"config.yaml"),"config.yaml"),soul:src(join8(dir,"SOUL.md"),"SOUL.md"),env:src(join8(dir,".env"),".env"),distribution:src(join8(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync10(r))jobs.push(info("default",r,active,sticky));let pr=join8(r,"profiles");if(existsSync10(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join8(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(readFileSync3(join8(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikonPath?basename7(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=join8(dir,"state.db");if(existsSync10(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(join8(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=existsSync10(join8(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react68.useState(""),[cloneIdx,setCloneIdx]=import_react68.useState(0),[alias,setAlias]=import_react68.useState(!0),[field,setField]=import_react68.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key2)=>{if(key2.name==="escape")return done(null);if(key2.name==="tab")return moveField(key2.shift?-1:1);if(key2.name==="return")return submit();if(field==="name"){if(key2.name==="backspace")return setName((n)=>n.slice(0,-1));if(key2.raw&&key2.raw.length===1&&/[a-z0-9_-]/.test(key2.raw))return setName((n)=>n+key2.raw);return}if(field==="clone"){if(key2.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key2.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key2.name==="space"||key2.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react70=__toESM(require_react_production(),1);import{rmSync,mkdtempSync}from"fs";import{join as join9}from"path";import{tmpdir}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=mkdtempSync(join9(tmpdir(),"herm-dist-preview-")),cleanup=()=>{try{rmSync(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest=readDistributionManifest(tmp);if(!manifest){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react70.useState("");return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key2)=>{if(keys.match("dialog.accept",key2)||keys.match("dialog.cancel",key2))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react70.useState(""),[alias,setAlias]=import_react70.useState(!1),[field,setField]=import_react70.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key2)=>{if(key2.name==="escape")return p.onCancel();if(key2.name==="tab")return move(key2.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key2))return fire();if(field==="alias"&&(key2.name==="space"||key2.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react72.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react72.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react72.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react72.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react72.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react72.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc4(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react72.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc4(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc4(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react72.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react72.useState("profiles"),[pView,setPView]=import_react72.useState("list"),[profiles,setProfiles]=import_react72.useState([]),[deleg,setDeleg]=import_react72.useState(null),[liveMap,setLiveMap]=import_react72.useState(()=>new Map),[now,setNow]=import_react72.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react72.useState(0),[dSel,setDSel]=import_react72.useState(0),[err,setErr]=import_react72.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react72.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react72.useRef(void 0),[stats,setStats]=import_react72.useState(()=>new Map),[sticky,setSticky]=import_react72.useState(stickyDefault),loadProfiles=import_react72.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react72.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react72.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react72.useEffect(loadDeleg,[loadDeleg]),import_react72.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react72.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react72.useCallback((i)=>setPSel(i),[]),dHover=import_react72.useCallback((i)=>setDSel(i),[]),pDelete=import_react72.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
4109
4109
 
4110
4110
  Its gateway is running and will be stopped first (may take up to ~10s).`:"";if(!await openConfirm(dialog,{title:"Delete Profile?",body:`'${p.name}' \u2014 config, env, memory, skills, and sessions will be removed. This cannot be undone.${warn}`,yes:"delete",danger:!0}))return;sh(`hermes profile delete ${p.name} -y`).then(()=>{toast.show({variant:"success",message:`Deleted '${p.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,dialog,toast,loadProfiles]),pSwitch=import_react72.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_active||!props.onSwitchProfile)return;if(await openConfirm(dialog,{title:`Switch to '${p.name}'?`,body:"The gateway restarts under this profile's HERMES_HOME. The current session ends (it stays in the outgoing profile's history).",yes:"switch"}))props.onSwitchProfile(p.path,p.name)},[dialog,props.onSwitchProfile]),pUpdate=import_react72.useCallback((p,force)=>{let cmd2=`hermes profile update ${p.name} -y${force?" --force-config":""}`;toast.show({variant:"info",message:`Updating '${p.name}'\u2026`}),sh(cmd2).then(()=>{if(toast.show({variant:"success",message:`Updated '${p.name}'`}),p.is_active&&props.onSwitchProfile){props.onSwitchProfile(p.path,p.name);return}loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,toast,loadProfiles,props.onSwitchProfile]),pEnter=import_react72.useCallback((i)=>{setPSel(i);let p=live.current.profiles[i];if(!p)return;openProfileMenu(dialog,p,{switch:props.onSwitchProfile?()=>pSwitch(i):void 0,sticky:(pp)=>sh(`hermes profile use ${pp.name}`).then(()=>{toast.show({variant:"success",message:`Sticky default \u2192 '${pp.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),unsticky:()=>sh("hermes profile use --clear").then(()=>{toast.show({variant:"info",message:"Cleared sticky default"}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),export:(pp)=>sh(`hermes profile export ${pp.name}`).then((out)=>toast.show({variant:"success",message:trunc4(out.trim()||`Exported '${pp.name}'`,80)})).catch((e)=>toast.show({variant:"error",message:e.message})),remove:()=>pDelete(i),update:(pp,force)=>pUpdate(pp,force)})},[sh,dialog,toast,loadProfiles,pDelete,pSwitch,pUpdate,props.onSwitchProfile]),dKill=import_react72.useCallback(async(i)=>{let r=live.current.active[i];if(!r)return;if(!await openConfirm(dialog,{title:"Interrupt subagent?",body:`${trunc4(r.goal,120)}
4111
4111
 
4112
- The child returns whatever partial result it has so far.`,yes:"interrupt",danger:!0}))return;gw.request("subagent.interrupt",{subagent_id:r.subagent_id}).then((res)=>{toast.show(res.found?{variant:"success",message:`Interrupted ${r.subagent_id}`}:{variant:"info",message:"Already finished"}),loadDeleg()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,dialog,toast,loadDeleg]),create=import_react72.useCallback(()=>{openCreateProfile(dialog,{existing:live.current.profiles.map((p)=>p.name)}).then((r)=>{if(!r)return;let flags=[r.cloneFrom?`--clone --clone-from ${r.cloneFrom}`:"",r.alias?"":"--no-alias"].filter(Boolean).join(" ");return toast.show({variant:"info",message:`Creating '${r.name}'\u2026`}),sh(`hermes profile create ${r.name} ${flags}`.trim()).then(()=>{toast.show({variant:"success",message:`Created '${r.name}'`}),loadProfiles()})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,dialog,toast,loadProfiles]),install=import_react72.useCallback(()=>{openInstallDistribution(dialog,gw).then((r)=>{if(!r)return;let shq2=(s)=>`'${s.replace(/'/g,"'\\''")}'`,flags=[r.name?`--name ${shq2(r.name)}`:"",r.alias?"--alias":""].filter(Boolean).join(" ");return toast.show({variant:"info",message:`Installing '${r.manifest.name}'\u2026`}),sh(`hermes profile install ${shq2(r.source)} -y ${flags}`.trim()).then(()=>{let installed=r.name||r.manifest.name;toast.show({variant:"success",message:`Installed '${installed}'`}),loadProfiles();let reqs=r.manifest.env_requires.filter((e)=>e.required).map((e)=>e.name);if(reqs.length>0)toast.show({variant:"warning",title:"Env vars needed",message:`${reqs.join(", ")} \u2014 add to the profile's .env before using it`,duration:6000})})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,sh,dialog,toast,loadProfiles]),selected=profiles[pSel],statGen=import_react72.useRef(0);import_react72.useEffect(()=>{let path7=selected?.path;if(!path7||stats.has(path7))return;let g=++statGen.current;profileStats(path7).then((s)=>{if(statGen.current!==g)return;setStats((prev)=>new Map(prev).set(path7,s))})},[selected?.path,stats]);let dims=useTerminalDimensions(),wide=dims.width>=130,pWide=dims.width>=170||!wide&&dims.width>=90,pFollow=useFollow("prof"),dFollow=useFollow("deleg"),keys=useKeys();useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="tab")return setPane((p)=>p==="profiles"?"deleg":"profiles");if(keys.match("list.refresh",key2)){loadProfiles(),loadDeleg(),toast.show({variant:"info",message:"Reloaded",duration:1000});return}if(pane==="profiles"){if(key2.name==="escape"&&!pWide&&pView==="detail")return setPView("list");if(key2.name==="s")return void pSwitch(pSel);if(keys.match("agents.install",key2))return install();handleListKey(keys,key2,{count:profiles.length,setSel:setPSel,...pFollow.opts,onNew:create,onDelete:()=>pDelete(pSel),onActivate:()=>{if(!pWide&&pView==="list")return setPView("detail");pEnter(pSel)}});return}if(handleListKey(keys,key2,{count:active.length,setSel:setDSel,...dFollow.opts,onDelete:()=>dKill(dSel)}))return;if(keys.match("agents.kill",key2))return dKill(dSel);if(keys.match("agents.history",key2))return openSpawnHistory(dialog,gw,props.sessionId)});let showProfiles=wide||pane==="profiles",showDeleg=wide||pane==="deleg",showList=pWide||pView==="list",showDetail=pWide||pView==="detail",limits=deleg?`depth\u2264${deleg.max_spawn_depth} \xB7 conc\u2264${deleg.max_concurrent_children}`:"",dHint=active.length>0?`${spark(nodes)} ${summary(all)}`:limits,togglePause=import_react72.useCallback(()=>{let next=!deleg?.paused;gw.request("delegation.pause",{paused:next}).then((r)=>{setDeleg((d2)=>d2?{...d2,paused:r.paused}:d2),toast.show({variant:"info",message:r.paused?"Delegation paused":"Delegation resumed"})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast,deleg?.paused]);import_react72.useEffect(()=>cmd.register([{title:deleg?.paused?"Resume Delegation":"Pause Delegation",value:"deleg.pause",category:"Agents",onSelect:togglePause},{title:"Install Distribution\u2026",value:"profile.install",category:"Agents",description:"from git URL or local directory",onSelect:install}]),[cmd,togglePause,deleg?.paused,install]);let pair=(k2,v2)=>`[${k2}] ${v2}`,join10=(...parts2)=>parts2.filter(Boolean).join(" "),sw=props.onSwitchProfile?pair("s","switch"):"",profilesHint=`${pWide?join10("[\u2191\u2193] nav",pair(keys.print("list.activate"),"actions"),sw,pair(keys.print("list.new"),"new"),pair(keys.print("agents.install"),"install"),pair(keys.print("list.delete"),"delete"),pair(keys.print("list.refresh"),"refresh")):pView==="list"?join10("[\u2191\u2193] nav",pair(keys.print("list.activate"),"detail"),sw,pair(keys.print("list.new"),"new"),pair(keys.print("list.delete"),"delete")):join10(pair(keys.print("list.activate"),"actions"),sw,"[Esc] back",pair(keys.print("list.delete"),"delete"))} ${pair("Tab",wide?"\u2192 delegation":"\u2194 delegation")}`,delegKeys=join10("[\u2191\u2193] nav",pair(keys.print("agents.kill"),"interrupt"),pair(keys.print("agents.history"),"history"),pair(keys.print("list.refresh"),"refresh")),delegHint=dHint?`${delegKeys} \xB7 ${dHint}`:delegKeys,footerHint=wide?pane==="profiles"?`${profilesHint} \xB7 ${delegHint}`:`${delegHint} \xB7 ${profilesHint}`:pane==="profiles"?profilesHint:delegHint;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[showProfiles?$jsx(TabShell,{title:`Profiles (${profiles.length})${sticky?` \xB7 \u2605 ${sticky}`:""}`,error:err||null,focus:pane==="profiles",grow:3,children:$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,children:[showList?$jsx("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:14,children:$jsx("scrollbox",{ref:pFollow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:profiles.length===0?$jsx("box",{height:1,children:err?$jsx("text",{fg:theme.textMuted,children:"\u2014"}):$jsx(Spinner,{color:theme.textMuted,label:"scanning profiles\u2026"})}):profiles.map((p,i)=>$jsx(ProfileRow,{id:pFollow.id(i),p,idx:i,selected:i===pSel,onHover:pHover,onEnter:pEnter,onDelete:pDelete},p.name))})}):null,showList&&showDetail?$jsx("box",{width:2}):null,showDetail?$jsx("box",{flexDirection:"column",flexGrow:2,flexBasis:0,minWidth:0,children:selected?$jsx(ProfileDetail,{p:selected,stats:stats.get(selected.path)}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No profiles"})})}):null]})}):null,showDeleg?$jsxs(TabShell,{title:`Delegation (${active.length})`,focus:pane==="deleg",grow:2,children:[$jsxs("box",{height:1,flexDirection:"row",marginBottom:1,children:[$jsx("box",{flexShrink:0,paddingX:1,backgroundColor:deleg?.paused?theme.warning:theme.backgroundElement,onMouseDown:togglePause,children:$jsx("text",{fg:deleg?.paused?theme.background:theme.text,children:deleg?.paused?"\u23F8 paused":"\u25B6 active"})}),$jsx("box",{flexGrow:1}),$jsxs("text",{fg:theme.textMuted,children:["click to ",deleg?.paused?"resume":"pause"]})]}),active.length===0?$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:deleg?.paused?"Paused \u2014 new subagents will queue":"No subagents running \xB7 h for history"})},"empty"):$jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:[$jsx("scrollbox",{ref:dFollow.ref,scrollY:!0,flexGrow:3,flexBasis:0,verticalScrollbarOptions:VBAR,children:active.map((r,i)=>{let lv=liveMap.get(r.subagent_id),row=lv?{...r,tool_count:lv.tool_count}:r,h2=heat(aggOf.get(r.subagent_id)?.hot??0,hotPeak,HOT.length);return $jsx(DelegRow,{id:dFollow.id(i),r:row,idx:i,selected:i===dSel,now,hot:h2,onHover:dHover,onKill:dKill},r.subagent_id)})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(4)})}),$jsx("box",{flexGrow:2,flexBasis:0,minHeight:0,children:active[dSel]?$jsx(DelegDetail,{r:active[dSel],live:liveMap.get(active[dSel].subagent_id),agg:aggOf.get(active[dSel].subagent_id),now}):null})]},"body")]}):null]}),$jsx(HintBar,{raw:footerHint})]})});var import_react74=__toESM(require_react_production(),1);var normalize=(j2)=>({id:j2.job_id??j2.id??"",name:j2.name??"",prompt:j2.prompt??j2.prompt_preview??"",schedule:j2.schedule??"",enabled:j2.enabled??!0,state:j2.state??"scheduled",deliver:j2.deliver??"local",repeat:j2.repeat,last_run:j2.last_run_at,next_run:j2.next_run_at,last_status:j2.last_status==="ok"||j2.last_status==="error"?j2.last_status:void 0,last_error:j2.last_delivery_error,paused_reason:j2.paused_reason,model:j2.model,skills:j2.skills,workdir:j2.workdir,script:j2.script}),sec2=(iso2)=>iso2?new Date(iso2).getTime()/1000:null,last2=(iso2)=>{let t2=sec2(iso2);return t2?ago(t2):"\u2014"},next=(iso2)=>{let t2=sec2(iso2);return t2?until(t2):"\u2014"},JobRow=import_react74.memo((props)=>{let theme=useTheme().theme,j2=props.job,bg2=props.selected?theme.backgroundElement:void 0,glyph=j2.enabled?"\u25CF":"\u25CB",glyphColor=!j2.enabled?theme.textMuted:j2.last_status==="error"?theme.error:j2.last_status==="ok"?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphColor,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:j2.name||j2.id}),$jsx(Col,{w:18,fg:theme.textMuted,children:j2.schedule||"\u2014"}),$jsx(Col,{w:16,fg:theme.textMuted,children:`last: ${last2(j2.last_run)}`}),$jsx(Col,{w:16,fg:j2.enabled?theme.text:theme.textMuted,children:`next: ${j2.enabled?next(j2.next_run):"paused"}`})]})}),DetailPanel=import_react74.memo((props)=>{let theme=useTheme().theme,j2=props.job,[output,setOutput]=import_react74.useState(null);return import_react74.useEffect(()=>{let live=!0;return readCronOutput(j2.id,30).then((o)=>{if(live)setOutput(o)}),()=>{live=!1}},[j2.id,props.reloadKey]),$jsx(TabShell,{title:"Job Detail",grow:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:j2.name||j2.id})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["ID",j2.id],["State",j2.enabled?"active":"paused",j2.enabled?theme.success:theme.warning],["Schedule",j2.schedule||"\u2014"],["Repeat",j2.repeat],["Deliver",j2.deliver??"local"],["Last Run",j2.last_run?`${last2(j2.last_run)} \xB7 ${j2.last_status??"?"}`:"never",j2.last_status==="error"?theme.error:void 0],["Next Run",j2.enabled?next(j2.next_run):"paused"],["Model",j2.model],["Skills",j2.skills?.length?j2.skills.join(", "):void 0],["Workdir",j2.workdir],["Script",j2.script],["Paused",j2.paused_reason],["Error",j2.last_error,theme.error]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Prompt"})}),$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:j2.prompt})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Last Output",output?` \xB7 ${ago(output.at.getTime()/1000)}`:""]})}),output?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:output.text})}):$jsx("text",{fg:theme.textMuted,children:"(none yet)"})]})})})}),Cron=import_react74.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),[jobs,setJobs]=import_react74.useState([]),[sel,setSel]=import_react74.useState(0),[err,setErr]=import_react74.useState(null),[reloadKey,setReloadKey]=import_react74.useState(0),live=import_react74.useRef({jobs,sel});live.current={jobs,sel};let load3=import_react74.useCallback(()=>{gw.request("cron.manage",{action:"list"}).then((res)=>{setJobs((res.jobs??[]).map(normalize)),setErr(null),setReloadKey((k2)=>k2+1)}).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]);import_react74.useEffect(()=>{load3()},[load3]);let create=import_react74.useCallback(async()=>{let schedule=await openTextPrompt(dialog,{title:"New Cron Job",label:"Schedule (cron expr or 'every 30m')"});if(schedule===null)return;let prompt=await openTextPrompt(dialog,{title:"New Cron Job",label:"Prompt"});if(prompt===null)return;gw.request("cron.manage",{action:"add",name:"",schedule,prompt}).then(()=>{toast.show({variant:"success",message:"Job created"}),load3()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,dialog,toast,load3]),toggle=import_react74.useCallback(()=>{let j2=live.current.jobs[live.current.sel];if(!j2)return;let action=j2.enabled?"pause":"resume";gw.request("cron.manage",{action,name:j2.id}).then(()=>{toast.show({variant:"success",message:j2.enabled?"Paused":"Resumed"}),load3()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast,load3]),remove2=import_react74.useCallback(async()=>{let j2=live.current.jobs[live.current.sel];if(!j2)return;if(!await openConfirm(dialog,{title:"Delete Job?",body:`Delete "${j2.name||j2.id}"? This cannot be undone.`,yes:"delete",danger:!0}))return;gw.request("cron.manage",{action:"remove",name:j2.id}).then(()=>{toast.show({variant:"success",message:"Deleted"}),setSel((s)=>Math.max(0,Math.min(s,live.current.jobs.length-2))),load3()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,dialog,toast,load3]),follow=useFollow("cron"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:jobs.length,setSel,...follow.opts,onToggle:toggle,onDelete:remove2,onNew:create,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),job=jobs[sel]??null,showDetail=dims.width>=120&&job!==null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Cron Jobs (${jobs.length})`,error:err,grow:3,children:jobs.length===0?$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:"No cron jobs. Press n to create one."})},"empty"):$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:18,fg:theme.textMuted,bold:!0,children:"Schedule"}),$jsx(Col,{w:16,fg:theme.textMuted,bold:!0,children:"Last"}),$jsx(Col,{w:16,fg:theme.textMuted,bold:!0,children:"Next"})]}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:jobs.map((j2,i)=>$jsx(JobRow,{id:follow.id(i),job:j2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},j2.id))})]},"table")}),showDetail?$jsx(DetailPanel,{job,reloadKey}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.new"),"new"],[keys.print("list.toggle"),"pause/resume"],[keys.print("list.delete"),"delete"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react79=__toESM(require_react_production(),1);import{Database as Database3}from"bun:sqlite";import{existsSync as existsSync11,readdirSync as readdirSync4,statSync as statSync3,openSync as openSync3,readSync as readSync3,closeSync as closeSync3,readFileSync as readFileSync4}from"fs";var STATUSES=["triage","todo","ready","running","blocked","done"],SEV=new Set(["warning","error","critical"]);function parseDiagnostics(stdout){let trimmed=stdout.trim();if(!trimmed)return[];let raw;try{raw=JSON.parse(trimmed)}catch{return[]}if(!Array.isArray(raw))return[];return raw.flatMap((r)=>{if(!r||typeof r!=="object")return[];let rec=r,id=rec.task_id;if(typeof id!=="string"||!id)return[];let diags=Array.isArray(rec.diagnostics)?rec.diagnostics:[];return[{task_id:id,title:typeof rec.title==="string"?rec.title:void 0,status:typeof rec.status==="string"?rec.status:void 0,assignee:typeof rec.assignee==="string"?rec.assignee:null,diagnostics:diags.flatMap(toDiag)}]})}var toDiag=(raw)=>{if(!raw||typeof raw!=="object")return[];let r=raw,sev=r.severity;if(typeof sev!=="string"||!SEV.has(sev))return[];let actions=Array.isArray(r.actions)?r.actions.flatMap(toAction):[];return[{kind:String(r.kind??""),severity:sev,title:String(r.title??""),detail:String(r.detail??""),actions,first_seen_at:Number(r.first_seen_at)||0,last_seen_at:Number(r.last_seen_at)||0,count:Number(r.count)||1,run_id:typeof r.run_id==="number"?r.run_id:null,data:r.data&&typeof r.data==="object"?r.data:{}}]},toAction=(raw)=>{if(!raw||typeof raw!=="object")return[];let r=raw,kind=r.kind,label=r.label;if(typeof kind!=="string"||typeof label!=="string")return[];return[{kind,label,payload:r.payload&&typeof r.payload==="object"?r.payload:{},suggested:r.suggested===!0}]},SEV_RANK={critical:3,error:2,warning:1},maxSeverity=(ds)=>{let best=null;for(let d2 of ds)if(!best||SEV_RANK[d2.severity]>SEV_RANK[best])best=d2.severity;return best},sortDiags=(ds)=>[...ds].sort((a,b2)=>SEV_RANK[b2.severity]-SEV_RANK[a.severity]||a.kind.localeCompare(b2.kind)),DEFAULT2="default",SLUG=/^[a-z0-9][a-z0-9_-]{0,63}$/,resolve6=()=>{let env2=(process.env.HERMES_KANBAN_BOARD??"").trim().toLowerCase();if(SLUG.test(env2))return env2;try{let txt=readFileSync4(hermesPath("kanban/current"),"utf-8").trim().toLowerCase();if(SLUG.test(txt))return txt}catch{}return DEFAULT2},slug=resolve6(),handles=new Map,currentBoard=()=>slug,dbPath=(s)=>hermesPath(s===DEFAULT2?"kanban.db":`kanban/boards/${s}/kanban.db`),logsDir=(s)=>hermesPath(s===DEFAULT2?"kanban/logs":`kanban/boards/${s}/logs`),pair=(s)=>{let cached2=handles.get(s);if(cached2)return cached2;let next2={ro:null,rw:null};return handles.set(s,next2),next2},dbOf=(s)=>{let h2=pair(s);if(h2.ro!==null)return h2.ro;try{h2.ro=new Database3(dbPath(s),{readonly:!0})}catch{h2.ro=null}return h2.ro},rwOf=(s)=>{let h2=pair(s);if(h2.rw)return h2.rw;if(!existsSync11(dbPath(s)))return null;try{let db=new Database3(dbPath(s));return db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON"),h2.rw=db,db}catch{return null}},resetKanban=()=>{for(let h2 of handles.values())h2.ro?.close(),h2.rw?.close();handles.clear(),slug=resolve6()};function listBoards(){let out=new Map([[DEFAULT2,"Default"]]),dir=hermesPath("kanban/boards");if(existsSync11(dir))for(let e of readdirSync4(dir,{withFileTypes:!0})){if(!e.isDirectory()||!SLUG.test(e.name))continue;let name=e.name;try{let meta=JSON.parse(readFileSync4(`${dir}/${e.name}/board.json`,"utf-8")),n=typeof meta?.name==="string"?meta.name:typeof meta?.display_name==="string"?meta.display_name:null;if(n)name=n}catch{}out.set(e.name,name)}return[...out].map(([s,n])=>({slug:s,name:n})).sort((a,b2)=>a.slug===DEFAULT2?-1:b2.slug===DEFAULT2?1:a.slug.localeCompare(b2.slug))}var AT="COALESCE(completed_at, started_at, created_at)",cols=new WeakMap,colsOf=(conn2)=>{let cached2=cols.get(conn2);if(cached2)return cached2;let set2=new Set;try{for(let r of conn2.query("PRAGMA table_info(tasks)").all())set2.add(r.name)}catch{}return cols.set(conn2,set2),set2},selectCol=(have,name,alias)=>{let a=alias??name;return have.has(name)?`${name} AS ${a}`:`NULL AS ${a}`},taskColumns=(have)=>["id","title",selectCol(have,"body"),selectCol(have,"assignee"),"status","priority",selectCol(have,"tenant"),selectCol(have,"created_at"),selectCol(have,"completed_at"),selectCol(have,"result"),selectCol(have,"last_spawn_error"),selectCol(have,"worker_pid"),selectCol(have,"workspace_kind"),selectCol(have,"workspace_path"),selectCol(have,"skills"),selectCol(have,"max_runtime_seconds"),selectCol(have,"max_retries"),`${AT} AS updated_at`].join(", "),parseSkills=(raw)=>{if(typeof raw!=="string"||!raw)return[];try{let j2=JSON.parse(raw);return Array.isArray(j2)?j2.filter((v2)=>typeof v2==="string"&&!!v2):[]}catch{return[]}},toTask=(r)=>({id:String(r.id),title:String(r.title??""),body:r.body??null,assignee:r.assignee??null,status:r.status??"todo",priority:Number(r.priority)||0,created_at:Number(r.created_at)||0,updated_at:Number(r.updated_at)||0,completed_at:r.completed_at??null,result:r.result??null,error:r.last_spawn_error??null,tenant:r.tenant??null,pid:r.worker_pid??null,workspace_kind:r.workspace_kind??null,workspace_path:r.workspace_path??null,skills:parseSkills(r.skills),max_runtime_seconds:r.max_runtime_seconds??null,max_retries:r.max_retries??null}),toRun=(r)=>({id:Number(r.id),profile:r.profile??null,status:r.status??null,outcome:r.outcome??null,started_at:Number(r.started_at)||0,ended_at:r.ended_at??null,summary:r.summary??null,error:r.error??null,worker_pid:r.worker_pid??null}),toEvent=(r)=>{let raw=r.payload,payload=null;if(raw)try{payload=JSON.parse(raw)}catch{payload=raw}return{id:Number(r.id),kind:String(r.kind??""),payload,created_at:Number(r.created_at)||0,run_id:r.run_id??null}};function boardOf(s){let out=new Map(STATUSES.map((k2)=>[k2,[]])),conn2=dbOf(s);if(!conn2)return out;try{let rows3=conn2.query(`SELECT ${taskColumns(colsOf(conn2))}
4112
+ The child returns whatever partial result it has so far.`,yes:"interrupt",danger:!0}))return;gw.request("subagent.interrupt",{subagent_id:r.subagent_id}).then((res)=>{toast.show(res.found?{variant:"success",message:`Interrupted ${r.subagent_id}`}:{variant:"info",message:"Already finished"}),loadDeleg()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,dialog,toast,loadDeleg]),create=import_react72.useCallback(()=>{openCreateProfile(dialog,{existing:live.current.profiles.map((p)=>p.name)}).then((r)=>{if(!r)return;let flags=[r.cloneFrom?`--clone --clone-from ${r.cloneFrom}`:"",r.alias?"":"--no-alias"].filter(Boolean).join(" ");return toast.show({variant:"info",message:`Creating '${r.name}'\u2026`}),sh(`hermes profile create ${r.name} ${flags}`.trim()).then(()=>{toast.show({variant:"success",message:`Created '${r.name}'`}),loadProfiles()})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,dialog,toast,loadProfiles]),install=import_react72.useCallback(()=>{openInstallDistribution(dialog,gw).then((r)=>{if(!r)return;let shq2=(s)=>`'${s.replace(/'/g,"'\\''")}'`,flags=[r.name?`--name ${shq2(r.name)}`:"",r.alias?"--alias":""].filter(Boolean).join(" ");return toast.show({variant:"info",message:`Installing '${r.manifest.name}'\u2026`}),sh(`hermes profile install ${shq2(r.source)} -y ${flags}`.trim()).then(()=>{let installed=r.name||r.manifest.name;toast.show({variant:"success",message:`Installed '${installed}'`}),loadProfiles();let reqs=r.manifest.env_requires.filter((e)=>e.required).map((e)=>e.name);if(reqs.length>0)toast.show({variant:"warning",title:"Env vars needed",message:`${reqs.join(", ")} \u2014 add to the profile's .env before using it`,duration:6000})})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,sh,dialog,toast,loadProfiles]),selected=profiles[pSel],statGen=import_react72.useRef(0);import_react72.useEffect(()=>{let path7=selected?.path;if(!path7||stats.has(path7))return;let g=++statGen.current;profileStats(path7).then((s)=>{if(statGen.current!==g)return;setStats((prev)=>new Map(prev).set(path7,s))})},[selected?.path,stats]);let dims=useTerminalDimensions(),wide=dims.width>=130,pWide=dims.width>=170||!wide&&dims.width>=90,pFollow=useFollow("prof"),dFollow=useFollow("deleg"),keys=useKeys();useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="tab")return setPane((p)=>p==="profiles"?"deleg":"profiles");if(keys.match("list.refresh",key2)){loadProfiles(),loadDeleg(),toast.show({variant:"info",message:"Reloaded",duration:1000});return}if(pane==="profiles"){if(key2.name==="escape"&&!pWide&&pView==="detail")return setPView("list");if(key2.name==="s")return void pSwitch(pSel);if(keys.match("agents.install",key2))return install();handleListKey(keys,key2,{count:profiles.length,setSel:setPSel,...pFollow.opts,onNew:create,onDelete:()=>pDelete(pSel),onActivate:()=>{if(!pWide&&pView==="list")return setPView("detail");pEnter(pSel)}});return}if(handleListKey(keys,key2,{count:active.length,setSel:setDSel,...dFollow.opts,onDelete:()=>dKill(dSel)}))return;if(keys.match("agents.kill",key2))return dKill(dSel);if(keys.match("agents.history",key2))return openSpawnHistory(dialog,gw,props.sessionId)});let showProfiles=wide||pane==="profiles",showDeleg=wide||pane==="deleg",showList=pWide||pView==="list",showDetail=pWide||pView==="detail",limits=deleg?`depth\u2264${deleg.max_spawn_depth} \xB7 conc\u2264${deleg.max_concurrent_children}`:"",dHint=active.length>0?`${spark(nodes)} ${summary(all)}`:limits,togglePause=import_react72.useCallback(()=>{let next=!deleg?.paused;gw.request("delegation.pause",{paused:next}).then((r)=>{setDeleg((d2)=>d2?{...d2,paused:r.paused}:d2),toast.show({variant:"info",message:r.paused?"Delegation paused":"Delegation resumed"})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast,deleg?.paused]);import_react72.useEffect(()=>cmd.register([{title:deleg?.paused?"Resume Delegation":"Pause Delegation",value:"deleg.pause",category:"Agents",onSelect:togglePause},{title:"Install Distribution\u2026",value:"profile.install",category:"Agents",description:"from git URL or local directory",onSelect:install}]),[cmd,togglePause,deleg?.paused,install]);let pair=(k2,v2)=>`[${k2}] ${v2}`,join10=(...parts2)=>parts2.filter(Boolean).join(" "),sw=props.onSwitchProfile?pair("s","switch"):"",profilesHint=`${pWide?join10("[\u2191\u2193] nav",pair(keys.print("list.activate"),"actions"),sw,pair(keys.print("list.new"),"new"),pair(keys.print("agents.install"),"install"),pair(keys.print("list.delete"),"delete"),pair(keys.print("list.refresh"),"refresh")):pView==="list"?join10("[\u2191\u2193] nav",pair(keys.print("list.activate"),"detail"),sw,pair(keys.print("list.new"),"new"),pair(keys.print("list.delete"),"delete")):join10(pair(keys.print("list.activate"),"actions"),sw,"[Esc] back",pair(keys.print("list.delete"),"delete"))} ${pair("Tab",wide?"\u2192 delegation":"\u2194 delegation")}`,delegKeys=join10("[\u2191\u2193] nav",pair(keys.print("agents.kill"),"interrupt"),pair(keys.print("agents.history"),"history"),pair(keys.print("list.refresh"),"refresh")),delegHint=dHint?`${delegKeys} \xB7 ${dHint}`:delegKeys,footerHint=wide?pane==="profiles"?`${profilesHint} \xB7 ${delegHint}`:`${delegHint} \xB7 ${profilesHint}`:pane==="profiles"?profilesHint:delegHint;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[showProfiles?$jsx(TabShell,{title:`Profiles (${profiles.length})${sticky?` \xB7 \u2605 ${sticky}`:""}`,error:err||null,focus:pane==="profiles",grow:3,children:$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,children:[showList?$jsx("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:14,children:$jsx("scrollbox",{ref:pFollow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:profiles.length===0?$jsx("box",{height:1,children:err?$jsx("text",{fg:theme.textMuted,children:"\u2014"}):$jsx(Spinner,{color:theme.textMuted,label:"scanning profiles\u2026"})}):profiles.map((p,i)=>$jsx(ProfileRow,{id:pFollow.id(i),p,idx:i,selected:i===pSel,onHover:pHover,onEnter:pEnter,onDelete:pDelete},p.name))})}):null,showList&&showDetail?$jsx("box",{width:2}):null,showDetail?$jsx("box",{flexDirection:"column",flexGrow:2,flexBasis:0,minWidth:0,children:selected?$jsx(ProfileDetail,{p:selected,stats:stats.get(selected.path)}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No profiles"})})}):null]})}):null,showDeleg?$jsxs(TabShell,{title:`Delegation (${active.length})`,focus:pane==="deleg",grow:2,children:[$jsxs("box",{height:1,flexDirection:"row",marginBottom:1,children:[$jsx("box",{flexShrink:0,paddingX:1,backgroundColor:deleg?.paused?theme.warning:theme.backgroundElement,onMouseDown:togglePause,children:$jsx("text",{fg:deleg?.paused?theme.background:theme.text,children:deleg?.paused?"\u23F8 paused":"\u25B6 active"})}),$jsx("box",{flexGrow:1}),$jsxs("text",{fg:theme.textMuted,children:["click to ",deleg?.paused?"resume":"pause"]})]}),active.length===0?$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:deleg?.paused?"Paused \u2014 new subagents will queue":"No subagents running \xB7 h for history"})},"empty"):$jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:[$jsx("scrollbox",{ref:dFollow.ref,scrollY:!0,flexGrow:3,flexBasis:0,verticalScrollbarOptions:VBAR,children:active.map((r,i)=>{let lv=liveMap.get(r.subagent_id),row=lv?{...r,tool_count:lv.tool_count}:r,h2=heat(aggOf.get(r.subagent_id)?.hot??0,hotPeak,HOT.length);return $jsx(DelegRow,{id:dFollow.id(i),r:row,idx:i,selected:i===dSel,now,hot:h2,onHover:dHover,onKill:dKill},r.subagent_id)})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(4)})}),$jsx("box",{flexGrow:2,flexBasis:0,minHeight:0,children:active[dSel]?$jsx(DelegDetail,{r:active[dSel],live:liveMap.get(active[dSel].subagent_id),agg:aggOf.get(active[dSel].subagent_id),now}):null})]},"body")]}):null]}),$jsx(HintBar,{raw:footerHint})]})});var import_react74=__toESM(require_react_production(),1);var normalize=(j2)=>({id:j2.job_id??j2.id??"",name:j2.name??"",prompt:j2.prompt??j2.prompt_preview??"",schedule:j2.schedule??"",enabled:j2.enabled??!0,state:j2.state??"scheduled",deliver:j2.deliver??"local",repeat:j2.repeat,last_run:j2.last_run_at,next_run:j2.next_run_at,last_status:j2.last_status==="ok"||j2.last_status==="error"?j2.last_status:void 0,last_error:j2.last_delivery_error,paused_reason:j2.paused_reason,model:j2.model,skills:j2.skills,workdir:j2.workdir,script:j2.script}),sec2=(iso2)=>iso2?new Date(iso2).getTime()/1000:null,last2=(iso2)=>{let t2=sec2(iso2);return t2?ago(t2):"\u2014"},next=(iso2)=>{let t2=sec2(iso2);return t2?until(t2):"\u2014"},JobRow=import_react74.memo((props)=>{let theme=useTheme().theme,j2=props.job,bg2=props.selected?theme.backgroundElement:void 0,glyph=j2.enabled?"\u25CF":"\u25CB",glyphColor=!j2.enabled?theme.textMuted:j2.last_status==="error"?theme.error:j2.last_status==="ok"?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphColor,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:j2.name||j2.id}),$jsx(Col,{w:18,fg:theme.textMuted,children:j2.schedule||"\u2014"}),$jsx(Col,{w:16,fg:theme.textMuted,children:`last: ${last2(j2.last_run)}`}),$jsx(Col,{w:16,fg:j2.enabled?theme.text:theme.textMuted,children:`next: ${j2.enabled?next(j2.next_run):"paused"}`})]})}),DetailPanel=import_react74.memo((props)=>{let theme=useTheme().theme,j2=props.job,[output,setOutput]=import_react74.useState(null);return import_react74.useEffect(()=>{let live=!0;return readCronOutput(j2.id,30).then((o)=>{if(live)setOutput(o)}),()=>{live=!1}},[j2.id,props.reloadKey]),$jsx(TabShell,{title:"Job Detail",grow:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:j2.name||j2.id})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["ID",j2.id],["State",j2.enabled?"active":"paused",j2.enabled?theme.success:theme.warning],["Schedule",j2.schedule||"\u2014"],["Repeat",j2.repeat],["Deliver",j2.deliver??"local"],["Last Run",j2.last_run?`${last2(j2.last_run)} \xB7 ${j2.last_status??"?"}`:"never",j2.last_status==="error"?theme.error:void 0],["Next Run",j2.enabled?next(j2.next_run):"paused"],["Model",j2.model],["Skills",j2.skills?.length?j2.skills.join(", "):void 0],["Workdir",j2.workdir],["Script",j2.script],["Paused",j2.paused_reason],["Error",j2.last_error,theme.error]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Prompt"})}),$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:j2.prompt})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Last Output",output?` \xB7 ${ago(output.at.getTime()/1000)}`:""]})}),output?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:output.text})}):$jsx("text",{fg:theme.textMuted,children:"(none yet)"})]})})})}),Cron=import_react74.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),[jobs,setJobs]=import_react74.useState([]),[sel,setSel]=import_react74.useState(0),[err,setErr]=import_react74.useState(null),[reloadKey,setReloadKey]=import_react74.useState(0),live=import_react74.useRef({jobs,sel});live.current={jobs,sel};let load3=import_react74.useCallback(()=>{gw.request("cron.manage",{action:"list"}).then((res)=>{setJobs((res.jobs??[]).map(normalize)),setErr(null),setReloadKey((k2)=>k2+1)}).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]);import_react74.useEffect(()=>{load3()},[load3]);let create=import_react74.useCallback(async()=>{let schedule=await openTextPrompt(dialog,{title:"New Cron Job",label:"Schedule (cron expr or 'every 30m')"});if(schedule===null)return;let prompt=await openTextPrompt(dialog,{title:"New Cron Job",label:"Prompt"});if(prompt===null)return;gw.request("cron.manage",{action:"add",name:"",schedule,prompt}).then(()=>{toast.show({variant:"success",message:"Job created"}),load3()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,dialog,toast,load3]),toggle=import_react74.useCallback(()=>{let j2=live.current.jobs[live.current.sel];if(!j2)return;let action=j2.enabled?"pause":"resume";gw.request("cron.manage",{action,name:j2.id}).then(()=>{toast.show({variant:"success",message:j2.enabled?"Paused":"Resumed"}),load3()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast,load3]),remove2=import_react74.useCallback(async()=>{let j2=live.current.jobs[live.current.sel];if(!j2)return;if(!await openConfirm(dialog,{title:"Delete Job?",body:`Delete "${j2.name||j2.id}"? This cannot be undone.`,yes:"delete",danger:!0}))return;gw.request("cron.manage",{action:"remove",name:j2.id}).then(()=>{toast.show({variant:"success",message:"Deleted"}),setSel((s)=>Math.max(0,Math.min(s,live.current.jobs.length-2))),load3()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,dialog,toast,load3]),follow=useFollow("cron"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:jobs.length,setSel,...follow.opts,onToggle:toggle,onDelete:remove2,onNew:create,onRefresh:()=>{load3(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),job=jobs[sel]??null,showDetail=dims.width>=120&&job!==null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Cron Jobs (${jobs.length})`,error:err,grow:3,children:jobs.length===0?$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:"No cron jobs. Press n to create one."})},"empty"):$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:18,fg:theme.textMuted,bold:!0,children:"Schedule"}),$jsx(Col,{w:16,fg:theme.textMuted,bold:!0,children:"Last"}),$jsx(Col,{w:16,fg:theme.textMuted,bold:!0,children:"Next"})]}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:jobs.map((j2,i)=>$jsx(JobRow,{id:follow.id(i),job:j2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},j2.id))})]},"table")}),showDetail?$jsx(DetailPanel,{job,reloadKey}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.new"),"new"],[keys.print("list.toggle"),"pause/resume"],[keys.print("list.delete"),"delete"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react79=__toESM(require_react_production(),1);import{Database as Database3}from"bun:sqlite";import{existsSync as existsSync11,readdirSync as readdirSync4,statSync as statSync3,openSync as openSync3,readSync as readSync3,closeSync as closeSync3,readFileSync as readFileSync4}from"fs";var STATUSES=["triage","todo","ready","running","blocked","done"],SEV=new Set(["warning","error","critical"]);function parseDiagnostics(stdout){let trimmed=stdout.trim();if(!trimmed)return[];let raw;try{raw=JSON.parse(trimmed)}catch{return[]}if(!Array.isArray(raw))return[];return raw.flatMap((r)=>{if(!r||typeof r!=="object")return[];let rec=r,id=rec.task_id;if(typeof id!=="string"||!id)return[];let diags=Array.isArray(rec.diagnostics)?rec.diagnostics:[];return[{task_id:id,title:typeof rec.title==="string"?rec.title:void 0,status:typeof rec.status==="string"?rec.status:void 0,assignee:typeof rec.assignee==="string"?rec.assignee:null,diagnostics:diags.flatMap(toDiag)}]})}var toDiag=(raw)=>{if(!raw||typeof raw!=="object")return[];let r=raw,sev=r.severity;if(typeof sev!=="string"||!SEV.has(sev))return[];let actions=Array.isArray(r.actions)?r.actions.flatMap(toAction):[];return[{kind:String(r.kind??""),severity:sev,title:String(r.title??""),detail:String(r.detail??""),actions,first_seen_at:Number(r.first_seen_at)||0,last_seen_at:Number(r.last_seen_at)||0,count:Number(r.count)||1,run_id:typeof r.run_id==="number"?r.run_id:null,data:r.data&&typeof r.data==="object"?r.data:{}}]},toAction=(raw)=>{if(!raw||typeof raw!=="object")return[];let r=raw,kind=r.kind,label=r.label;if(typeof kind!=="string"||typeof label!=="string")return[];return[{kind,label,payload:r.payload&&typeof r.payload==="object"?r.payload:{},suggested:r.suggested===!0}]},SEV_RANK={critical:3,error:2,warning:1},maxSeverity=(ds)=>{let best=null;for(let d2 of ds)if(!best||SEV_RANK[d2.severity]>SEV_RANK[best])best=d2.severity;return best},sortDiags=(ds)=>[...ds].sort((a,b2)=>SEV_RANK[b2.severity]-SEV_RANK[a.severity]||a.kind.localeCompare(b2.kind)),DEFAULT2="default",SLUG=/^[a-z0-9][a-z0-9_-]{0,63}$/,kanbanRoot=()=>{let pin=(process.env.HERMES_KANBAN_HOME??"").trim();if(pin)return pin.replace(/[\\/]+$/,"");return hermesPath("").replace(/[\\/]+$/,"").replace(/[\\/]profiles[\\/][^\\/]+$/,"")},kp=(rel2)=>`${kanbanRoot()}/${rel2}`,resolve6=()=>{let env2=(process.env.HERMES_KANBAN_BOARD??"").trim().toLowerCase();if(SLUG.test(env2))return env2;try{let txt=readFileSync4(kp("kanban/current"),"utf-8").trim().toLowerCase();if(SLUG.test(txt))return txt}catch{}return DEFAULT2},slug=resolve6(),handles=new Map,currentBoard=()=>slug,dbPath=(s)=>kp(s===DEFAULT2?"kanban.db":`kanban/boards/${s}/kanban.db`),logsDir=(s)=>kp(s===DEFAULT2?"kanban/logs":`kanban/boards/${s}/logs`),pair=(s)=>{let cached2=handles.get(s);if(cached2)return cached2;let next2={ro:null,rw:null};return handles.set(s,next2),next2},dbOf=(s)=>{let h2=pair(s);if(h2.ro)return h2.ro;try{h2.ro=new Database3(dbPath(s),{readwrite:!0,create:!1})}catch{h2.ro=null}return h2.ro},rwOf=(s)=>{let h2=pair(s);if(h2.rw)return h2.rw;if(!existsSync11(dbPath(s)))return null;try{let db=new Database3(dbPath(s));return db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON"),h2.rw=db,db}catch{return null}},resetKanban=()=>{for(let h2 of handles.values())h2.ro?.close(),h2.rw?.close();handles.clear(),slug=resolve6()};function listBoards(){let out=new Map([[DEFAULT2,"Default"]]),dir=kp("kanban/boards");if(existsSync11(dir))for(let e of readdirSync4(dir,{withFileTypes:!0})){if(!e.isDirectory()||!SLUG.test(e.name))continue;let name=e.name;try{let meta=JSON.parse(readFileSync4(`${dir}/${e.name}/board.json`,"utf-8")),n=typeof meta?.name==="string"?meta.name:typeof meta?.display_name==="string"?meta.display_name:null;if(n)name=n}catch{}out.set(e.name,name)}return[...out].map(([s,n])=>({slug:s,name:n})).sort((a,b2)=>a.slug===DEFAULT2?-1:b2.slug===DEFAULT2?1:a.slug.localeCompare(b2.slug))}var AT="COALESCE(completed_at, started_at, created_at)",cols=new WeakMap,colsOf=(conn2)=>{let cached2=cols.get(conn2);if(cached2)return cached2;let set2=new Set;try{for(let r of conn2.query("PRAGMA table_info(tasks)").all())set2.add(r.name)}catch{}return cols.set(conn2,set2),set2},selectCol=(have,name,alias)=>{let a=alias??name;return have.has(name)?`${name} AS ${a}`:`NULL AS ${a}`},taskColumns=(have)=>["id","title",selectCol(have,"body"),selectCol(have,"assignee"),"status","priority",selectCol(have,"tenant"),selectCol(have,"created_at"),selectCol(have,"completed_at"),selectCol(have,"result"),selectCol(have,"last_spawn_error"),selectCol(have,"worker_pid"),selectCol(have,"workspace_kind"),selectCol(have,"workspace_path"),selectCol(have,"skills"),selectCol(have,"max_runtime_seconds"),selectCol(have,"max_retries"),`${AT} AS updated_at`].join(", "),parseSkills=(raw)=>{if(typeof raw!=="string"||!raw)return[];try{let j2=JSON.parse(raw);return Array.isArray(j2)?j2.filter((v2)=>typeof v2==="string"&&!!v2):[]}catch{return[]}},toTask=(r)=>({id:String(r.id),title:String(r.title??""),body:r.body??null,assignee:r.assignee??null,status:r.status??"todo",priority:Number(r.priority)||0,created_at:Number(r.created_at)||0,updated_at:Number(r.updated_at)||0,completed_at:r.completed_at??null,result:r.result??null,error:r.last_spawn_error??null,tenant:r.tenant??null,pid:r.worker_pid??null,workspace_kind:r.workspace_kind??null,workspace_path:r.workspace_path??null,skills:parseSkills(r.skills),max_runtime_seconds:r.max_runtime_seconds??null,max_retries:r.max_retries??null}),toRun=(r)=>({id:Number(r.id),profile:r.profile??null,status:r.status??null,outcome:r.outcome??null,started_at:Number(r.started_at)||0,ended_at:r.ended_at??null,summary:r.summary??null,error:r.error??null,worker_pid:r.worker_pid??null}),toEvent=(r)=>{let raw=r.payload,payload=null;if(raw)try{payload=JSON.parse(raw)}catch{payload=raw}return{id:Number(r.id),kind:String(r.kind??""),payload,created_at:Number(r.created_at)||0,run_id:r.run_id??null}};function boardOf(s){let out=new Map(STATUSES.map((k2)=>[k2,[]])),conn2=dbOf(s);if(!conn2)return out;try{let rows3=conn2.query(`SELECT ${taskColumns(colsOf(conn2))}
4113
4113
  FROM tasks WHERE status != 'archived'
4114
4114
  ORDER BY priority DESC, updated_at DESC`).all();for(let r of rows3){let t2=toTask(r);out.get(t2.status)?.push(t2)}}catch{}return out}var EVENT_TAIL=20;function detailOf(s,id){let conn2=dbOf(s);if(!conn2)return null;try{let row=conn2.query(`SELECT ${taskColumns(colsOf(conn2))} FROM tasks WHERE id = ?`).get(id);if(!row)return null;let parents=conn2.query("SELECT parent_id FROM task_links WHERE child_id = ?").all(id).map((r)=>r.parent_id),children2=conn2.query("SELECT child_id FROM task_links WHERE parent_id = ?").all(id).map((r)=>r.child_id),comments=conn2.query("SELECT author, body, created_at FROM task_comments WHERE task_id = ? ORDER BY created_at").all(id).map((c)=>({author:c.author,body:c.body,at:c.created_at})),runs=runsOf(conn2,id),events=eventsOf(conn2,id),latest2=latestSummary(conn2,id);return{...toTask(row),parents,children:children2,comments,runs,events,latest_summary:latest2}}catch{return null}}var runsOf=(conn2,id)=>{try{return conn2.query(`SELECT id, profile, status, outcome, started_at, ended_at,
4115
4115
  summary, error, worker_pid
@@ -4117,9 +4117,9 @@ The child returns whatever partial result it has so far.`,yes:"interrupt",danger
4117
4117
  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
4118
4118
  WHERE task_id = ? AND summary IS NOT NULL AND summary != ''
4119
4119
  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(!existsSync11(path7))return null;try{let size=statSync3(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(`
4120
- `);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=hermesPath("profiles");if(existsSync11(dir)){for(let e of readdirSync4(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 writeTxn(conn2,fn){conn2.exec("BEGIN IMMEDIATE");try{let out=fn();return conn2.exec("COMMIT"),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_react76=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react76.memo((p)=>{let theme=useTheme().theme,bg2=p.state==="in"?theme.accent:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?theme.accent:theme.borderSubtle:p.selected?theme.accent:theme.text;return $jsx("box",{height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var import_react77=__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_react77.useRef(null),[bodyText,setBodyText]=import_react77.useState(""),[field,setField]=import_react77.useState("title"),[more,setMore]=import_react77.useState(!1),[picker,setPicker]=import_react77.useState(null),[title,setTitle]=import_react77.useState(""),[assignee,setAssignee]=import_react77.useState(null),[priority,setPriority]=import_react77.useState(0),[triage,setTriage]=import_react77.useState(!1),[tenant,setTenant]=import_react77.useState(""),[workspace,setWorkspace]=import_react77.useState({kind:"scratch"}),[maxRuntime,setMaxRuntime]=import_react77.useState(""),[catalog,setCatalog]=import_react77.useState([]),[skills,setSkills]=import_react77.useState([]),[filter,setFilter]=import_react77.useState(""),[matchIdx,setMatchIdx]=import_react77.useState(0);import_react77.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_react77.useMemo(()=>{if(!filter.trim())return[];let q4=filter.trim().toLowerCase(),picked=new Set(skills),hits=[];for(let s of catalog){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},[catalog,filter,skills]);import_react77.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,submit=()=>{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 submit();if(field!=="body")return submit();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 row=body.current?.logicalCursor.row??0,last3=(body.current?.lineCount??1)-1;if(row<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,text2)=>$jsx("box",{width:13,flexShrink:0,children:$jsxs("text",{fg:field===f?theme.accent:theme.textMuted,children:[field===f?"\u25B8 ":" ",text2]})}),textRow=(f,label,value,set2,placeholder)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:set2,onSubmit:submit,focused:field===f,placeholder,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field===f?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement},`field-${f}`)})]}),valRow=(f,label,value,hint)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label),$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($Fragment2,{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",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";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=load().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_react79.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($Fragment2,{children:[$jsx("span",{fg:sevColor(p.sev,theme),children:SEV_GLYPH[p.sev]})," "]}):null,p.t.title]})})}),Column=import_react79.memo((p)=>{let theme=useTheme().theme,box=import_react79.useRef(null),[hov,setHov]=import_react79.useState(-1),id=(i)=>`kb-${p.slug}-${p.status}-${i}`;import_react79.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==="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",{ref:box,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,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))})})]})}),FilterBar=import_react79.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 chip=$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[chip];return[$jsx("box",{height:1,flexShrink:0,marginLeft:1,children:$jsx("text",{fg:theme.borderSubtle,children:"|"})},`sep:${chipId(c)}`),chip]})})}),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_react79.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,label,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:label})}),$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,label,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:label})}),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??"\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.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.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.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($Fragment2,{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($Fragment2,{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(`
4120
+ `);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(existsSync11(dir)){for(let e of readdirSync4(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 writeTxn(conn2,fn){conn2.exec("BEGIN IMMEDIATE");try{let out=fn();return conn2.exec("COMMIT"),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_react76=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react76.memo((p)=>{let theme=useTheme().theme,bg2=p.state==="in"?theme.accent:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?theme.accent:theme.borderSubtle:p.selected?theme.accent:theme.text;return $jsx("box",{height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var import_react77=__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_react77.useRef(null),[bodyText,setBodyText]=import_react77.useState(""),[field,setField]=import_react77.useState("title"),[more,setMore]=import_react77.useState(!1),[picker,setPicker]=import_react77.useState(null),[title,setTitle]=import_react77.useState(""),[assignee,setAssignee]=import_react77.useState(null),[priority,setPriority]=import_react77.useState(0),[triage,setTriage]=import_react77.useState(!1),[tenant,setTenant]=import_react77.useState(""),[workspace,setWorkspace]=import_react77.useState({kind:"scratch"}),[maxRuntime,setMaxRuntime]=import_react77.useState(""),[catalog,setCatalog]=import_react77.useState([]),[skills,setSkills]=import_react77.useState([]),[filter,setFilter]=import_react77.useState(""),[matchIdx,setMatchIdx]=import_react77.useState(0);import_react77.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_react77.useMemo(()=>{if(!filter.trim())return[];let q4=filter.trim().toLowerCase(),picked=new Set(skills),hits=[];for(let s of catalog){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},[catalog,filter,skills]);import_react77.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,submit=()=>{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 submit();if(field!=="body")return submit();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 row=body.current?.logicalCursor.row??0,last3=(body.current?.lineCount??1)-1;if(row<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,text2)=>$jsx("box",{width:13,flexShrink:0,children:$jsxs("text",{fg:field===f?theme.accent:theme.textMuted,children:[field===f?"\u25B8 ":" ",text2]})}),textRow=(f,label,value,set2,placeholder)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:set2,onSubmit:submit,focused:field===f,placeholder,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field===f?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement},`field-${f}`)})]}),valRow=(f,label,value,hint)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label),$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($Fragment2,{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",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";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=load().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_react79.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($Fragment2,{children:[$jsx("span",{fg:sevColor(p.sev,theme),children:SEV_GLYPH[p.sev]})," "]}):null,p.t.title]})})}),Column=import_react79.memo((p)=>{let theme=useTheme().theme,box=import_react79.useRef(null),[hov,setHov]=import_react79.useState(-1),id=(i)=>`kb-${p.slug}-${p.status}-${i}`;import_react79.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==="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",{ref:box,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,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))})})]})}),FilterBar=import_react79.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 chip=$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[chip];return[$jsx("box",{height:1,flexShrink:0,marginLeft:1,children:$jsx("text",{fg:theme.borderSubtle,children:"|"})},`sep:${chipId(c)}`),chip]})})}),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_react79.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,label,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:label})}),$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,label,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:label})}),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??"\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.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.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.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($Fragment2,{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($Fragment2,{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(`
4121
4121
  `)[0].slice(0,200)}`}):null,r.error?$jsx("text",{wrapMode:"word",fg:theme.error,children:` \u2716 ${r.error.split(`
4122
- `)[0].slice(0,200)}`}):null]},r.id)})]}):null,d2.events.length>0?$jsxs($Fragment2,{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($Fragment2,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Comments (${d2.comments.length})`})}),d2.comments.map((c,i)=>$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${c.author} \xB7 ${ago(c.at)}`})}),$jsx("text",{wrapMode:"word",children:c.body})]},i))]}):null,p.on&&cur==="comment"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.accent,children:"Enter add comment"})}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.on?"Tab/\u2191\u2193 field Enter edit Esc grid a assign c comment l log":"Tab into pane a assign c comment u unblock d archive l log N child"})})]})}),Kanban=import_react79.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),keys=useKeys(),[boards,setBoards]=import_react79.useState(listBoards),[data2,setData]=import_react79.useState(()=>new Map(boards.map((b2)=>[b2.slug,boardOf(b2.slug)]))),[diags,setDiags]=import_react79.useState(()=>new Map),[masks,setMasks]=import_react79.useState(()=>maskFromPrefs(load().kanban?.masks)),[open2,setOpen]=import_react79.useState(()=>{let saved=load().kanban?.open;if(saved)return new Set(saved);let init=currentBoard();return new Set(listBoards().filter((b2)=>b2.slug===init||[...boardOf(b2.slug).values()].some((v2)=>v2.length>0)).map((b2)=>b2.slug))}),[at,setAt]=import_react79.useState(currentBoard),[tier,setTier]=import_react79.useState("grid"),[col,setCol]=import_react79.useState(0),[row,setRow]=import_react79.useState(0),[chip,setChip]=import_react79.useState(0),[paneSel,setPaneSel]=import_react79.useState(0),[pane,setPane]=import_react79.useState(null),outer=import_react79.useRef(null),load3=import_react79.useCallback(()=>{let bs=listBoards();setBoards(bs),setData(new Map(bs.map((b2)=>[b2.slug,boardOf(b2.slug)]))),setPane((p)=>p?.kind==="detail"?((d2)=>d2?{...p,d:d2}:null)(detailOf(p.slug,p.d.id)):p),Promise.all(bs.map((b2)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(b2.slug)} diagnostics --json`}).then((r)=>r.code===0?parseDiagnostics(r.stdout):[]).catch(()=>[]).then((rows3)=>[b2.slug,indexDiags(rows3)]))).then((pairs)=>setDiags(new Map(pairs)))},[gw]);import_react79.useEffect(load3,[load3]),import_react79.useEffect(()=>{persist(masks,open2)},[masks,open2]);let maskOf=(s)=>masks.get(s)??EMPTY2,wide=dims.width>=160,maxH=Math.max(8,dims.height-16),sections=import_react79.useMemo(()=>{let built=boards.map((b2)=>{let d2=data2.get(b2.slug)??new Map,flat=STATUSES.flatMap((s)=>d2.get(s)??[]),total=flat.length,who=[...new Set(flat.map((t2)=>t2.assignee).filter((v2)=>!!v2))].sort(),pri=[...new Set(flat.map((t2)=>t2.priority).filter((n)=>n>0))].sort((a,z2)=>z2-a),chips=[...who.map((v2)=>({kind:"who",v:v2})),...pri.map((v2)=>({kind:"pri",v:v2})),...STATUSES.map((v2)=>({kind:"status",v:v2}))],m2=maskOf(b2.slug),cols3=STATUSES.filter((s)=>admits(m2.status,s)).map((s)=>({status:s,tasks:(d2.get(s)??[]).filter((t2)=>pass(t2,m2))})).filter((c)=>wide||c.tasks.length>0),shown=cols3.reduce((a,c)=>a+c.tasks.length,0),tall=cols3.reduce((a,c)=>Math.max(a,c.tasks.length),0);return{board:b2,cols:cols3,chips,total,shown,running:d2.get("running")?.length??0,cap:Math.min(maxH,Math.max(5,3+2*tall))}});return[...built.filter((s)=>s.total>0),...built.filter((s)=>s.total===0)]},[boards,data2,masks,wide,maxH]),idx2=sections.findIndex((s)=>s.board.slug===at),sec3=sections[idx2]??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(row,Math.max(0,(cur?.tasks.length??1)-1))]:void 0,grand=sections.reduce((a,s)=>a+s.total,0),running2=sections.reduce((a,s)=>a+s.running,0);import_react79.useEffect(()=>{if(pane?.kind!=="detail")return;if(tier!=="grid"&&tier!=="pane"){setPane(null);return}if(!task){setPane(null);return}if(pane.slug===at&&pane.d.id===task.id)return;let d2=detailOf(at,task.id);setPane(d2?{kind:"detail",slug:at,d:d2}:null),setPaneSel(0)},[task?.id,at,tier]),import_react79.useEffect(()=>{if(!props.focused||running2===0)return;let t2=setInterval(load3,3000);return()=>clearInterval(t2)},[props.focused,running2,load3]),import_react79.useEffect(()=>{outer.current?.scrollChildIntoView(`kb-sec-${at}`)},[at,open2]);let sh=import_react79.useCallback((argv,ok)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(at)} ${argv}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());if(ok)toast.show({variant:"success",message:ok});return load3(),r.stdout}).catch((e)=>void toast.show({variant:"error",message:trunc4(e.message,120)})),[gw,toast,load3,at]),patchDirect=import_react79.useCallback((id,p,ok)=>{try{if(!patchTask(at,id,p))return void toast.show({variant:"error",message:`no such task: ${id}`});toast.show({variant:"success",message:ok}),load3()}catch(e){toast.show({variant:"error",message:trunc4(e.message,120)})}},[at,toast,load3]),enterTop=(s)=>{setAt(s.board.slug),setTier("head"),setChip(0),setRow(0)},enterBottom=(s)=>{if(setAt(s.board.slug),setChip(Math.max(0,s.chips.length-1)),open2.has(s.board.slug)&&s.shown>0){let nc=Math.min(col,Math.max(0,s.cols.length-1));setTier("grid"),setCol(nc),setRow(Math.max(0,(s.cols[nc]?.tasks.length??1)-1));return}if(open2.has(s.board.slug)){setTier("filter");return}setTier("head")},stepBoard=(d2)=>{let n=idx2+d2;return n<0||n>=sections.length?null:sections[n]},goBoard=import_react79.useCallback((d2)=>{let n=(idx2+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))},[idx2,sections]),flip=import_react79.useCallback((c)=>setMasks((m2)=>{let cur2=m2.get(at)??EMPTY2,who=new Map(cur2.who),pri=new Map(cur2.pri),status=new Map(cur2.status),g=c.kind==="who"?who:c.kind==="pri"?pri:status,next2=cycle(g.get(c.v)??"off");next2==="off"?g.delete(c.v):g.set(c.v,next2);let out=new Map(m2);return out.set(at,{who,pri,status}),setRow(0),out}),[at]),toggle=import_react79.useCallback((s)=>setOpen((o)=>{let n=new Set(o);return n.has(s)?n.delete(s):n.add(s),n}),[]),newBoard=import_react79.useCallback(()=>openTextPrompt(dialog,{title:"New board",label:"Slug (a-z, 0-9, -_)"}).then((v2)=>{if(!v2)return;return gw.request("shell.exec",{command:`hermes kanban boards create ${q3(v2)}`}).then((r)=>r.code===0?(toast.show({variant:"success",message:`Board '${v2}' created`}),resetKanban(),load3(),setAt(v2),setTier("head")):Promise.reject(Error((r.stderr||r.stdout).trim()))).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)}))}),[dialog,gw,toast,load3]),live=import_react79.useRef({task,at,sec:sec3});live.current={task,at,sec:sec3};let create=import_react79.useCallback((parent)=>openCreateTask(dialog,{assignees:assignees(live.current.at),parent:parent?{id:parent.id,title:parent.title}:void 0}).then((d2)=>{if(!d2)return;let ws=d2.workspace.kind==="scratch"?"":d2.workspace.kind==="worktree"?"--workspace worktree":`--workspace ${q3(`dir:${d2.workspace.path}`)}`,flags=[d2.assignee?`--assignee ${q3(d2.assignee)}`:"",d2.body?`--body ${q3(d2.body)}`:"",d2.priority?`--priority ${d2.priority}`:"",d2.parent?`--parent ${q3(d2.parent)}`:"",d2.triage?"--triage":"",d2.tenant?`--tenant ${q3(d2.tenant)}`:"",ws,d2.maxRuntime?`--max-runtime ${q3(d2.maxRuntime)}`:"",...d2.skills.map((s)=>`--skill ${q3(s)}`)].filter(Boolean).join(" ");return sh(`create ${q3(d2.title)} ${flags}`.trim(),`Created${d2.triage?" (triage)":""}${d2.assignee?` \u2192 ${d2.assignee}`:""}`)}),[dialog,sh]),assign=import_react79.useCallback((t2)=>{let opts=[{title:"(unassigned)",value:"none"},...assignees(live.current.at).map((n)=>({title:n,value:n}))];dialog.replace($jsx(DialogSelect,{title:`Assign ${t2.id}`,options:opts,current:t2.assignee??"none",placeholder:"Search profiles\u2026",onSelect:(o)=>{dialog.clear(),sh(`assign ${q3(t2.id)} ${q3(o.value)}`,o.value==="none"?`Unassigned ${t2.id}`:`${t2.id} \u2192 ${o.value}`)}}))},[dialog,sh]),comment=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:`Comment on ${t2.id}`,label:t2.title}).then((v2)=>v2&&sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`,"Comment added")),[dialog,sh]),unblock=import_react79.useCallback((t2)=>{if(t2.status!=="blocked")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not blocked`});return openTextPrompt(dialog,{title:`Unblock ${t2.id}`,label:"Answer (posted as comment, then task \u2192 ready)"}).then((v2)=>{if(v2)return sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`)}).then(()=>sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`))},[dialog,sh,toast]),archive=import_react79.useCallback((t2)=>openConfirm(dialog,{title:"Archive task?",danger:!0,yes:"archive",body:`${t2.id} \xB7 ${trunc4(t2.title,60)}
4122
+ `)[0].slice(0,200)}`}):null]},r.id)})]}):null,d2.events.length>0?$jsxs($Fragment2,{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($Fragment2,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Comments (${d2.comments.length})`})}),d2.comments.map((c,i)=>$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${c.author} \xB7 ${ago(c.at)}`})}),$jsx("text",{wrapMode:"word",children:c.body})]},i))]}):null,p.on&&cur==="comment"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.accent,children:"Enter add comment"})}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.on?"Tab/\u2191\u2193 field Enter edit Esc grid a assign c comment l log":"Tab into pane a assign c comment u unblock d archive l log N child"})})]})}),Kanban=import_react79.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),keys=useKeys(),[boards,setBoards]=import_react79.useState(listBoards),[data2,setData]=import_react79.useState(()=>new Map(boards.map((b2)=>[b2.slug,boardOf(b2.slug)]))),[diags,setDiags]=import_react79.useState(()=>new Map),[masks,setMasks]=import_react79.useState(()=>maskFromPrefs(load().kanban?.masks)),[open2,setOpen]=import_react79.useState(()=>{let saved=load().kanban?.open;if(saved)return new Set(saved);let init=currentBoard();return new Set(listBoards().filter((b2)=>b2.slug===init||[...boardOf(b2.slug).values()].some((v2)=>v2.length>0)).map((b2)=>b2.slug))}),[at,setAt]=import_react79.useState(currentBoard),[tier,setTier]=import_react79.useState("grid"),[col,setCol]=import_react79.useState(0),[row,setRow]=import_react79.useState(0),[chip,setChip]=import_react79.useState(0),[paneSel,setPaneSel]=import_react79.useState(0),[pane,setPane]=import_react79.useState(null),outer=import_react79.useRef(null),load3=import_react79.useCallback(()=>{let bs=listBoards();setBoards(bs),setData(new Map(bs.map((b2)=>[b2.slug,boardOf(b2.slug)]))),setPane((p)=>p?.kind==="detail"?((d2)=>d2?{...p,d:d2}:null)(detailOf(p.slug,p.d.id)):p),Promise.all(bs.map((b2)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(b2.slug)} diagnostics --json`}).then((r)=>r.code===0?parseDiagnostics(r.stdout):[]).catch(()=>[]).then((rows3)=>[b2.slug,indexDiags(rows3)]))).then((pairs)=>setDiags(new Map(pairs)))},[gw]);import_react79.useEffect(load3,[load3]),import_react79.useEffect(()=>{persist(masks,open2)},[masks,open2]);let maskOf=(s)=>masks.get(s)??EMPTY2,wide=dims.width>=160,maxH=Math.max(8,dims.height-16),sections=import_react79.useMemo(()=>{let built=boards.map((b2)=>{let d2=data2.get(b2.slug)??new Map,flat=STATUSES.flatMap((s)=>d2.get(s)??[]),total=flat.length,who=[...new Set(flat.map((t2)=>t2.assignee).filter((v2)=>!!v2))].sort(),pri=[...new Set(flat.map((t2)=>t2.priority).filter((n)=>n>0))].sort((a,z2)=>z2-a),chips=[...who.map((v2)=>({kind:"who",v:v2})),...pri.map((v2)=>({kind:"pri",v:v2})),...STATUSES.map((v2)=>({kind:"status",v:v2}))],m2=maskOf(b2.slug),cols3=STATUSES.filter((s)=>admits(m2.status,s)).map((s)=>({status:s,tasks:(d2.get(s)??[]).filter((t2)=>pass(t2,m2))})).filter((c)=>wide||c.tasks.length>0),shown=cols3.reduce((a,c)=>a+c.tasks.length,0),tall=cols3.reduce((a,c)=>Math.max(a,c.tasks.length),0);return{board:b2,cols:cols3,chips,total,shown,running:d2.get("running")?.length??0,cap:Math.min(maxH,Math.max(5,3+2*tall))}});return[...built.filter((s)=>s.total>0),...built.filter((s)=>s.total===0)]},[boards,data2,masks,wide,maxH]),idx2=sections.findIndex((s)=>s.board.slug===at),sec3=sections[idx2]??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(row,Math.max(0,(cur?.tasks.length??1)-1))]:void 0,grand=sections.reduce((a,s)=>a+s.total,0),running2=sections.reduce((a,s)=>a+s.running,0);import_react79.useEffect(()=>{if(pane?.kind!=="detail")return;if(tier!=="grid"&&tier!=="pane"){setPane(null);return}if(!task){setPane(null);return}if(pane.slug===at&&pane.d.id===task.id)return;let d2=detailOf(at,task.id);setPane(d2?{kind:"detail",slug:at,d:d2}:null),setPaneSel(0)},[task?.id,at,tier]),import_react79.useEffect(()=>{if(!props.focused||running2===0)return;let t2=setInterval(load3,3000);return()=>clearInterval(t2)},[props.focused,running2,load3]),import_react79.useEffect(()=>{outer.current?.scrollChildIntoView(`kb-sec-${at}`)},[at,open2]);let sh=import_react79.useCallback((argv,ok)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(at)} ${argv}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());if(ok)toast.show({variant:"success",message:ok});return resetKanban(),load3(),r.stdout}).catch((e)=>void toast.show({variant:"error",message:trunc4(e.message,120)})),[gw,toast,load3,at]),patchDirect=import_react79.useCallback((id,p,ok)=>{try{if(!patchTask(at,id,p))return void toast.show({variant:"error",message:`no such task: ${id}`});toast.show({variant:"success",message:ok}),load3()}catch(e){toast.show({variant:"error",message:trunc4(e.message,120)})}},[at,toast,load3]),enterTop=(s)=>{setAt(s.board.slug),setTier("head"),setChip(0),setRow(0)},enterBottom=(s)=>{if(setAt(s.board.slug),setChip(Math.max(0,s.chips.length-1)),open2.has(s.board.slug)&&s.shown>0){let nc=Math.min(col,Math.max(0,s.cols.length-1));setTier("grid"),setCol(nc),setRow(Math.max(0,(s.cols[nc]?.tasks.length??1)-1));return}if(open2.has(s.board.slug)){setTier("filter");return}setTier("head")},stepBoard=(d2)=>{let n=idx2+d2;return n<0||n>=sections.length?null:sections[n]},goBoard=import_react79.useCallback((d2)=>{let n=(idx2+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))},[idx2,sections]),flip=import_react79.useCallback((c)=>setMasks((m2)=>{let cur2=m2.get(at)??EMPTY2,who=new Map(cur2.who),pri=new Map(cur2.pri),status=new Map(cur2.status),g=c.kind==="who"?who:c.kind==="pri"?pri:status,next2=cycle(g.get(c.v)??"off");next2==="off"?g.delete(c.v):g.set(c.v,next2);let out=new Map(m2);return out.set(at,{who,pri,status}),setRow(0),out}),[at]),toggle=import_react79.useCallback((s)=>setOpen((o)=>{let n=new Set(o);return n.has(s)?n.delete(s):n.add(s),n}),[]),newBoard=import_react79.useCallback(()=>openTextPrompt(dialog,{title:"New board",label:"Slug (a-z, 0-9, -_)"}).then((v2)=>{if(!v2)return;return gw.request("shell.exec",{command:`hermes kanban boards create ${q3(v2)}`}).then((r)=>r.code===0?(toast.show({variant:"success",message:`Board '${v2}' created`}),resetKanban(),load3(),setAt(v2),setTier("head")):Promise.reject(Error((r.stderr||r.stdout).trim()))).catch((e)=>toast.show({variant:"error",message:trunc4(e.message,120)}))}),[dialog,gw,toast,load3]),live=import_react79.useRef({task,at,sec:sec3});live.current={task,at,sec:sec3};let create=import_react79.useCallback((parent)=>openCreateTask(dialog,{assignees:assignees(live.current.at),parent:parent?{id:parent.id,title:parent.title}:void 0}).then((d2)=>{if(!d2)return;let ws=d2.workspace.kind==="scratch"?"":d2.workspace.kind==="worktree"?"--workspace worktree":`--workspace ${q3(`dir:${d2.workspace.path}`)}`,flags=[d2.assignee?`--assignee ${q3(d2.assignee)}`:"",d2.body?`--body ${q3(d2.body)}`:"",d2.priority?`--priority ${d2.priority}`:"",d2.parent?`--parent ${q3(d2.parent)}`:"",d2.triage?"--triage":"",d2.tenant?`--tenant ${q3(d2.tenant)}`:"",ws,d2.maxRuntime?`--max-runtime ${q3(d2.maxRuntime)}`:"",...d2.skills.map((s)=>`--skill ${q3(s)}`)].filter(Boolean).join(" ");return sh(`create ${q3(d2.title)} ${flags}`.trim(),`Created${d2.triage?" (triage)":""}${d2.assignee?` \u2192 ${d2.assignee}`:""}`)}),[dialog,sh]),assign=import_react79.useCallback((t2)=>{let opts=[{title:"(unassigned)",value:"none"},...assignees(live.current.at).map((n)=>({title:n,value:n}))];dialog.replace($jsx(DialogSelect,{title:`Assign ${t2.id}`,options:opts,current:t2.assignee??"none",placeholder:"Search profiles\u2026",onSelect:(o)=>{dialog.clear(),sh(`assign ${q3(t2.id)} ${q3(o.value)}`,o.value==="none"?`Unassigned ${t2.id}`:`${t2.id} \u2192 ${o.value}`)}}))},[dialog,sh]),comment=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:`Comment on ${t2.id}`,label:t2.title}).then((v2)=>v2&&sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`,"Comment added")),[dialog,sh]),unblock=import_react79.useCallback((t2)=>{if(t2.status!=="blocked")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not blocked`});return openTextPrompt(dialog,{title:`Unblock ${t2.id}`,label:"Answer (posted as comment, then task \u2192 ready)"}).then((v2)=>{if(v2)return sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`)}).then(()=>sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`))},[dialog,sh,toast]),archive=import_react79.useCallback((t2)=>openConfirm(dialog,{title:"Archive task?",danger:!0,yes:"archive",body:`${t2.id} \xB7 ${trunc4(t2.title,60)}
4123
4123
 
4124
4124
  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(`
4125
4125
  `).flatMap((l)=>l.trim()?[JSON.parse(l)]:[]),specify=import_react79.useCallback((t2)=>{if(t2.status!=="triage")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not triage`});return sh(`specify ${q3(t2.id)} --json`).then((out)=>{if(out==null)return;let r=parseSpecify(out)[0];if(!r)return;if(!r.ok)return void toast.show({variant:"error",message:`specify ${r.task_id}: ${trunc4(r.reason??"failed",100)}`});toast.show({variant:"success",message:r.new_title?`Specified ${r.task_id} \u2192 ${trunc4(r.new_title,60)}`:`Specified ${r.task_id} \u2192 todo`})})},[sh,toast]),specifyAll=import_react79.useCallback(()=>{let triage=live.current.sec?.cols.find((c)=>c.status==="triage")?.tasks.length??0;if(triage===0)return void toast.show({variant:"info",message:`No 'triage' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Specify all \xB7 ${live.current.at}`,body:`${triage} task${triage===1?"":"s"} in 'triage'. Auxiliary LLM expands each body and promotes to todo.`,yes:"specify"}).then((go)=>{if(!go)return;return sh("specify --all --json").then((out)=>{if(out==null)return;let rows3=parseSpecify(out),ok=rows3.filter((r)=>r.ok).length,bad=rows3.length-ok;toast.show({variant:ok===0&&bad>0?"error":"success",message:`Specified ${ok}/${rows3.length}${bad?` (${bad} failed)`:""}`})})})},[dialog,sh,toast]),dispatch=import_react79.useCallback(()=>{let ready=live.current.sec?.cols.find((c)=>c.status==="ready")?.tasks.length??0;if(ready===0)return void toast.show({variant:"info",message:`No 'ready' tasks on ${live.current.at}`});return openConfirm(dialog,{title:`Dispatch \xB7 ${live.current.at}`,body:`${ready} task${ready===1?"":"s"} in 'ready'. Spawns one worker per task (one pass).`,yes:"dispatch"}).then((ok)=>{if(ok)sh("dispatch --json",`Dispatched (${ready} ready)`)})},[dialog,sh,toast]),showLog=import_react79.useCallback((t2)=>{let s=live.current.at,text2=tailLogOf(s,t2.id);if(text2==null)return void toast.show({variant:"info",message:`No worker log for ${t2.id}`});setPane({kind:"log",slug:s,id:t2.id,text:text2})},[toast]),editTitle=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit title",label:t2.id,initial:t2.title}).then((v2)=>v2!==null&&v2!==void 0&&patchDirect(t2.id,{title:v2},`Updated ${t2.id}`)),[dialog,patchDirect]),editBody=import_react79.useCallback((t2)=>openTextPrompt(dialog,{title:"Edit body",label:t2.id,initial:t2.body??""}).then((v2)=>{if(v2===null||v2===void 0)return;patchDirect(t2.id,{body:v2},`Updated ${t2.id}`)}),[dialog,patchDirect]),editPriority=import_react79.useCallback((t2)=>{let opts=Array.from({length:10},(_2,i)=>({title:i===0?"P0 (none)":`P${i}`,value:String(i)}));dialog.replace($jsx(DialogSelect,{title:`Priority for ${t2.id}`,options:opts,current:String(t2.priority),filterable:!1,onSelect:(o)=>{dialog.clear(),patchDirect(t2.id,{priority:Number(o.value)},`${t2.id} \u2192 P${o.value}`)}}))},[dialog,patchDirect]),editResult=import_react79.useCallback((t2)=>{if(t2.status!=="done")return void toast.show({variant:"info",message:`${t2.id} is not done`});return openTextPrompt(dialog,{title:"Edit result",label:t2.id,initial:t2.result??""}).then((v2)=>{if(v2==null)return;sh(`edit ${q3(t2.id)} --result ${q3(v2)}`,`Updated ${t2.id} result`)})},[dialog,sh,toast]),editStatus=import_react79.useCallback((t2)=>{let opts=[];if(t2.status!=="done")opts.push({title:"done",value:"complete",description:"mark complete (prompts for result)"});if(t2.status!=="blocked")opts.push({title:"blocked",value:"block",description:"mark blocked (prompts for reason)"});if(t2.status==="blocked")opts.push({title:"ready",value:"unblock",description:"return to ready"});opts.push({title:"archived",value:"archive",description:"archive (terminal)"}),dialog.replace($jsx(DialogSelect,{title:`Status for ${t2.id}`,options:opts,current:t2.status,filterable:!1,onSelect:async(o)=>{if(dialog.clear(),o.value==="complete"){let res=await openTextPrompt(dialog,{title:`Complete ${t2.id}`,label:"Result (optional)",initial:t2.result??""}),flag=res?` --result ${q3(res)}`:"";sh(`complete ${q3(t2.id)}${flag}`,`Completed ${t2.id}`);return}if(o.value==="block"){let r=await openTextPrompt(dialog,{title:`Block ${t2.id}`,label:"Reason (optional, posted as comment)"}),arg=r?` ${q3(r)}`:"";sh(`block ${q3(t2.id)}${arg}`,`Blocked ${t2.id}`);return}if(o.value==="unblock")return void sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`);if(o.value==="archive")return void archive(t2)}}))},[dialog,sh,archive]),editParents=import_react79.useCallback((t2)=>{let cur2=(pane?.kind==="detail"&&pane.d.id===t2.id?pane.d:detailOf(at,t2.id))?.parents??[],d2=data2.get(at)??new Map,opts=STATUSES.flatMap((s)=>d2.get(s)??[]).filter((x2)=>x2.id!==t2.id).map((x2)=>({title:x2.id,description:trunc4(x2.title,50),value:x2.id,category:cur2.includes(x2.id)?"linked":"available"}));dialog.replace($jsx(DialogSelect,{title:`Parents for ${t2.id}`,options:opts,placeholder:"Select to toggle link\u2026",onSelect:(o)=>{if(dialog.clear(),cur2.includes(o.value))sh(`unlink ${q3(o.value)} ${q3(t2.id)}`,`Unlinked ${o.value}`);else sh(`link ${q3(o.value)} ${q3(t2.id)}`,`Linked ${o.value}`)}}))},[dialog,sh,data2,at,pane]),openField=import_react79.useCallback((f,t2)=>{if(f==="title")return void editTitle(t2);if(f==="body")return void editBody(t2);if(f==="assignee")return assign(t2);if(f==="priority")return editPriority(t2);if(f==="status")return editStatus(t2);if(f==="parents")return editParents(t2);if(f==="result")return void editResult(t2);if(f==="comment")return void comment(t2)},[editTitle,editBody,assign,editPriority,editStatus,editParents,editResult,comment]),bumpPriority=import_react79.useCallback((t2,d2)=>{let next2=Math.max(0,Math.min(9,t2.priority+d2));if(next2===t2.priority)return;patchDirect(t2.id,{priority:next2},`${t2.id} \u2192 P${next2}`)},[patchDirect]),ACTS=import_react79.useMemo(()=>[{key:"n",title:"New task",when:()=>!0,run:()=>void create()},{key:"N",title:"New child",when:(t2)=>!!t2,run:(t2)=>void create(t2)},{key:"a",title:"Assign",when:(t2)=>!!t2,run:(t2)=>void assign(t2)},{key:"c",title:"Comment",when:(t2)=>!!t2,run:(t2)=>void comment(t2)},{key:"s",title:"Specify",when:(t2)=>t2?.status==="triage",run:(t2)=>void specify(t2)},{key:"S",title:"Specify all",when:()=>!0,run:()=>void specifyAll()},{key:"u",title:"Unblock",when:(t2)=>t2?.status==="blocked",run:(t2)=>void unblock(t2)},{key:"d",title:"Archive",when:(t2)=>!!t2,run:(t2)=>void archive(t2)},{key:"l",title:"Worker log",when:(t2)=>!!t2,run:(t2)=>showLog(t2)},{key:"b",title:"New board",when:()=>!0,run:()=>void newBoard()},{key:"D",title:"Dispatch",when:()=>!0,run:()=>void dispatch()}],[create,assign,comment,specify,specifyAll,unblock,archive,showLog,newBoard,dispatch]),isOpen=open2.has(at),paneOpen=pane?.kind==="detail",paneFields=paneOpen?fieldsFor(pane.d):[];useKeyboard((key2)=>{if(!props.focused||dialog.open())return;if(key2.name==="escape"&&pane){if(tier==="pane"){setTier("grid");return}return setPane(null)}if(keys.match("list.refresh",key2))return load3();if(key2.name==="tab"){if(paneOpen&&tier!=="pane"){setTier("pane"),setPaneSel(0);return}if(tier==="pane"){let n=paneFields.length;if(n===0)return;let d2=key2.shift?-1:1;setPaneSel((s)=>(s+d2+n)%n);return}return goBoard(key2.shift?-1:1)}if(tier==="pane"){let t3=live.current.task;if(!t3||!paneOpen)return;let f=paneFields[Math.min(paneSel,paneFields.length-1)];if(key2.name==="up"){if(f==="priority")return bumpPriority(t3,1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s-1+n)%n)}if(key2.name==="down"){if(f==="priority")return bumpPriority(t3,-1);let n=paneFields.length;if(n===0)return;return setPaneSel((s)=>(s+1)%n)}if(key2.name==="return")return openField(f,t3);let hit2=ACTS.find((a)=>a.key===key2.raw&&a.when(t3));if(hit2)return hit2.run(t3);return}if(key2.name==="space"||key2.name===" "){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip])return flip(sec3.chips[chip]);return}if(key2.name==="down"){if(tier==="head"){if(isOpen)return setTier("filter");let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(tier==="filter"){if(sec3&&sec3.shown>0){setTier("grid"),setRow(0);return}let n2=stepBoard(1);return n2?enterTop(n2):void 0}if(row<(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(row>0)return setRow((r)=>r-1);return setTier("filter")}if(key2.name==="left"){if(tier==="filter")return setChip((c)=>Math.max(0,c-1));if(tier==="grid")return setCol((c)=>{let n=Math.max(0,c-1);return setRow(0),n});return}if(key2.name==="right"){if(tier==="filter")return setChip((c)=>Math.min((sec3?.chips.length??1)-1,c+1));if(tier==="grid")return setCol((c)=>{let n=Math.min(cols2.length-1,c+1);return setRow(0),n});return}if(key2.name==="return"){if(tier==="head")return toggle(at);if(tier==="filter"&&sec3?.chips[chip])return flip(sec3.chips[chip]);if(task)return setPane((p)=>p?.kind==="detail"&&p.d.id===task.id?null:((d2)=>d2?{kind:"detail",slug:at,d:d2}:null)(detailOf(at,task.id)));return}let t2=live.current.task,hit=ACTS.find((a)=>a.key===key2.raw&&a.when(t2));if(hit)return hit.run(t2)});let hint=import_react79.useMemo(()=>{let t2=task;return[tier==="pane"?"Esc grid":"Tab board",tier==="head"?"\u2191\u2193 nav Space fold":tier==="filter"?"\u2190\u2192 chip Space toggle":tier==="pane"?"Tab/\u2191\u2193 field Enter edit Esc grid":"\u2190\u2192\u2191\u2193 nav Enter detail",...ACTS.filter((a)=>a.when(t2)).map((a)=>`${a.key} ${a.title.toLowerCase()}`),`${keys.print("list.refresh")} reload`].join(" ")},[ACTS,keys,task,tier]),onHead=import_react79.useCallback((s)=>{setAt(s),setTier("head"),toggle(s)},[toggle]),onChip=import_react79.useCallback((s,i,c)=>{setAt(s),setTier("filter"),setChip(i),flip(c)},[flip]),onPick=import_react79.useCallback((s,ci,ri,id)=>{setAt(s),setTier("grid"),setCol(ci),setRow(ri),setOpen((o)=>o.has(s)?o:new Set(o).add(s));let d2=detailOf(s,id);if(d2)setPane({kind:"detail",slug:s,d:d2})},[]);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Kanban \xB7 ${sections.length} board${sections.length===1?"":"s"} \xB7 ${grand} task${grand===1?"":"s"}${running2?` \xB7 ${running2} running`:""}`,children:$jsx("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:sections.map((s)=>{let on=s.board.slug===at,secOpen=open2.has(s.board.slug),m2=maskOf(s.board.slug),filt=m2.who.size+m2.pri.size+m2.status.size,dg=diags.get(s.board.slug)??EMPTY_DIAG;return $jsxs("box",{id:`kb-sec-${s.board.slug}`,flexDirection:"column",flexShrink:0,marginBottom:1,children:[$jsx("box",{height:1,onMouseDown:()=>onHead(s.board.slug),backgroundColor:on&&tier==="head"?theme.backgroundElement:void 0,children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:secOpen?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:on?theme.primary:theme.text,children:$jsx("strong",{children:s.board.name})}),$jsx("span",{fg:theme.textMuted,children:s.total===0?" \xB7 empty":` \xB7 ${filt?`${s.shown}/`:""}${s.total} task${s.total===1?"":"s"}${s.running?` \xB7 ${s.running} running`:""}`})]})}),secOpen?s.total===0?$jsx("box",{height:1,marginLeft:2,children:$jsxs("text",{fg:theme.textMuted,children:["no tasks \u2014 ",$jsx("span",{fg:theme.accent,children:"n"})," to create one here"]})}):$jsxs($Fragment2,{children:[$jsx(FilterBar,{chips:s.chips,mask:m2,on:on&&tier==="filter",sel:on?Math.min(chip,s.chips.length-1):-1,onPick:(i)=>onChip(s.board.slug,i,s.chips[i])}),s.cols.length>0?$jsx("box",{flexDirection:"row",height:s.cap,gap:1,children:s.cols.map((c,ci)=>$jsx(Column,{slug:s.board.slug,status:c.status,tasks:c.tasks,diags:dg,on:on&&(tier==="grid"||tier==="pane")&&ci===clampCol,sel:on?row:0,onPick:(ri)=>onPick(s.board.slug,ci,ri,c.tasks[ri].id)},c.status))}):$jsx("box",{height:1,marginLeft:2,children:$jsx("text",{fg:theme.textMuted,children:"all columns hidden"})})]}):null]},s.board.slug)})})})}),pane?$jsx(SidePane,{pane,on:tier==="pane",sel:paneSel,diags:pane.kind==="detail"?diags.get(pane.slug)?.get(pane.d.id)??EMPTY_DIAGS:EMPTY_DIAGS}):null]}),$jsx(HintBar,{raw:hint})]})});var Automation=import_react81.memo((props)=>{let keys=useKeys(),labels=SUB_TABS[AUTOMATION_TAB];import_react81.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} group \xB7 shift+\u2190/\u2192 sub`;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane2,{visible:props.sub===0,children:$jsx(Kanban,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane2,{visible:props.sub===1,children:$jsx(Agents,{focused:!!props.focused&&props.sub===1,sessionId:props.sessionId,onSwitchProfile:props.onSwitchProfile})}),$jsx(Pane2,{visible:props.sub===2,children:$jsx(Cron,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane2=({visible,children:children2})=>visible?$jsx("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:children2}):null;var import_react93=__toESM(require_react_production(),1);var import_react83=__toESM(require_react_production(),1);init_lane();var int=(lo,hi,what=`${lo}\u2013${hi}`)=>(raw)=>{let n=Number(raw);if(!Number.isInteger(n))return`expected integer ${what}`;if(n<lo||n>hi)return`expected ${what}`;return null},float=(lo,hi)=>(raw)=>{let n=Number(raw);if(!Number.isFinite(n))return`expected number ${lo}\u2013${hi}`;if(n<lo||n>hi)return`expected ${lo}\u2013${hi}`;return null},oneOf=(...opts)=>(raw)=>opts.includes(raw)?null:`expected one of: ${opts.join(" | ")}`,nonNeg=(raw)=>{let n=Number(raw);return Number.isFinite(n)&&n>=0?null:"expected \u2265 0"},RULES={"compression.threshold":float(0.1,0.95),"compression.target_ratio":float(0.05,0.9),"prompt_caching.cache_ttl":(raw)=>/^\d+[smhd]$/.test(raw.trim())?null:"expected duration e.g. 5m, 1h","prompt_caching.long_lived_ttl":(raw)=>/^\d+[smhd]$/.test(raw.trim())?null:"expected duration e.g. 5m, 1h","agent.max_turns":int(1,1e4),"delegation.max_iterations":int(1,1e4),"delegation.max_concurrent_children":int(1,64),"delegation.max_spawn_depth":int(1,3),"agent.gateway_timeout":nonNeg,"agent.gateway_timeout_warning":nonNeg,"agent.gateway_notify_interval":nonNeg,"agent.restart_drain_timeout":nonNeg,"delegation.child_timeout_seconds":int(30,86400),"browser.command_timeout":int(1,600),"approvals.timeout":int(1,3600),"security.tirith_timeout":int(1,120),"agent.api_max_retries":int(0,20),"tool_output.max_bytes":int(1024,1e7),"tool_output.max_lines":int(10,1e5),"sessions.retention_days":int(1,3650),"sessions.min_interval_hours":int(1,720),"agent.service_tier":oneOf("","fast","standard"),"display.busy_input_mode":oneOf("queue","steer","interrupt"),"display.details_mode":oneOf("hidden","collapsed","expanded"),"display.thinking_mode":oneOf("collapsed","truncated","full"),"display.tool_progress":oneOf("off","new","all","verbose"),"display.final_response_markdown":oneOf("render","strip","raw"),"logging.level":oneOf("DEBUG","INFO","WARNING","ERROR"),"approvals.mode":oneOf("manual","ask","yolo","deny"),"code_execution.mode":oneOf("project","strict")},check=(key2,raw)=>RULES[key2]?.(raw)??null;init_schema();init_lane();var SELECTS={"terminal.backend":["local","docker","ssh","modal","daytona","singularity","vercel_sandbox"],"tts.provider":["edge","elevenlabs","openai","neutts","xai","mistral"],"display.skin":[...SKINS],"logging.level":["DEBUG","INFO","WARNING","ERROR"],"agent.reasoning_effort":["","none","minimal","low","medium","high","xhigh"],"display.busy_input_mode":["queue","steer","interrupt"],"display.details_mode":["hidden","collapsed","expanded"],"display.thinking_mode":["collapsed","truncated","full"],"display.tool_progress":["off","new","all","verbose"],"approvals.mode":["manual","ask","yolo","deny"]},get3=(obj,path7)=>{let cur=obj;for(let p of path7.split("."))if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},classify2=(key2,t2)=>{if(route(key2).via==="readonly")return"readonly";if(SELECTS[key2])return"select";if(t2==="bool")return"boolean";if(t2==="int"||t2==="float")return"number";return"string"},labelOf=(key2)=>{let raw=SCHEMA[key2]?.group??key2.split(".")[0];return key2.startsWith(`${raw}.`)?key2.slice(raw.length+1):key2},buildFields=(user)=>{let seen=new Set,out=[];for(let key2 of SCHEMA_KEYS){let s=SCHEMA[key2],uv=get3(user,key2),set2=uv!==void 0;out.push({key:key2,label:labelOf(key2),type:classify2(key2,s.type),value:set2?uv:s.default,set:set2,doc:s.doc,effect:s.effect,options:SELECTS[key2]}),seen.add(key2)}let walk=(obj,prefix="")=>{for(let[k2,v2]of Object.entries(obj)){let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2)){if(SCHEMA[key2]?.type==="dict"){seen.add(key2);continue}walk(v2,key2);continue}if(seen.has(key2))continue;out.push({key:key2,label:labelOf(key2),type:Array.isArray(v2)?"readonly":typeof v2==="boolean"?"boolean":typeof v2==="number"?"number":"string",value:v2,set:!0,doc:"",effect:"live"})}};return walk(user),out},MERGE={approvals:"security",privacy:"security",checkpoints:"agent",context:"agent",cron:"agent",network:"agent",model_catalog:"general",onboarding:"general",human_delay:"display",dashboard:"display",tool_output:"agent",prompt_caching:"compression",code_execution:"terminal",slack:"platforms",telegram:"platforms",mattermost:"platforms",discord:"platforms",whatsapp:"platforms",matrix:"platforms"},rawGroupOf=(key2)=>SCHEMA[key2]?.group??(key2.includes(".")?key2.split(".")[0]:"general"),groupOf=(key2)=>{let raw=rawGroupOf(key2);return MERGE[raw]??raw},sections=(group,fields)=>{let by=new Map;for(let f of fields){let r=rawGroupOf(f.key);if(!by.has(r))by.set(r,[]);by.get(r).push(f)}if(by.size<=1)return[{head:null,items:fields}];return[...by.keys()].sort((a,b2)=>a===group?-1:b2===group?1:a.localeCompare(b2)).map((r)=>({head:r,items:by.get(r)}))},GROUPS=(()=>{let g=new Set(["general"]);for(let k2 of SCHEMA_KEYS)g.add(groupOf(k2));return[...g]})(),EFFECT_GLYPH={live:"",session:"\u21BB",restart:"\u27F3"};init_lane();var AUX_TASKS=[{key:"vision",label:"Vision",hint:"Image analysis"},{key:"web_extract",label:"Web Extract",hint:"Page summarization"},{key:"compression",label:"Compression",hint:"Context compaction"},{key:"session_search",label:"Session Search",hint:"Recall queries"},{key:"skills_hub",label:"Skills Hub",hint:"Skill search"},{key:"approval",label:"Approval",hint:"Smart auto-approve"},{key:"mcp",label:"MCP",hint:"MCP tool routing"},{key:"title_generation",label:"Title Gen",hint:"Session titles"},{key:"curator",label:"Curator",hint:"Skill-usage review"}],dig=(o,...path7)=>path7.reduce((c,p)=>c&&typeof c==="object"?c[p]:void 0,o),str2=(v2)=>typeof v2==="string"?v2:"",readSlots=(raw)=>{let main2={kind:"main",key:"main",label:"Main model",hint:"Primary agent model",provider:str2(dig(raw,"model","provider")),model:str2(dig(raw,"model","default"))||str2(dig(raw,"model","name")),auto:!1},aux=AUX_TASKS.map((t2)=>{let p=str2(dig(raw,"auxiliary",t2.key,"provider"));return{kind:"aux",key:t2.key,label:t2.label,hint:t2.hint,provider:p,model:str2(dig(raw,"auxiliary",t2.key,"model")),auto:p===""||p==="auto"}});return[main2,...aux]},assign=async(gw,slot,provider,model)=>{if(slot==="main"){let r=await gw.request("config.set",{key:"model",value:`${model} --provider ${provider} --global`,session_id:void 0});return{ok:["model.default","model.provider"],failed:[],warnings:[],warning:r.warning}}return writeConfig(gw,[{key:`auxiliary.${slot}.provider`,to:provider},{key:`auxiliary.${slot}.model`,to:model}])},resetAux=(gw,slot)=>{let keys=slot==="all"?AUX_TASKS.map((t2)=>t2.key):[slot];return writeConfig(gw,keys.flatMap((k2)=>[{key:`auxiliary.${k2}.provider`,to:"auto"},{key:`auxiliary.${k2}.model`,to:""}]))};var import_react82=__toESM(require_react_production(),1);var ModelPickerDialog=(props)=>{let dialog=useDialog(),toast=useToast(),theme=useTheme().theme,[data2,setData]=import_react82.useState(null),[step,setStep]=import_react82.useState("provider"),[provider,setProvider]=import_react82.useState(null),[global2,setGlobal]=import_react82.useState(!1);import_react82.useEffect(()=>{props.gw.request("model.options").then(setData).catch(()=>setData({providers:[]}))},[props.gw]);let apply=import_react82.useCallback((model,prov)=>{if(props.onApply)return void props.onApply(prov,model).catch((e)=>toast.show({variant:"error",message:e.message}));let value=`${model} --provider ${prov}${global2?" --global":""}`;props.gw.request("config.set",global2?{key:"model",value,session_id:void 0}:{key:"model",value}).then((r)=>{if(toast.show({variant:"success",message:`model \u2192 ${r.value??model}${global2?" (global)":""}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[props.gw,props.onApply,global2,toast]),onKey=import_react82.useCallback((k2)=>{if(k2.name==="tab"&&!props.onApply)return setGlobal((g)=>!g),!0;if(k2.name==="left"&&step==="model")return setStep("provider"),!0;return!1},[step,props.onApply]),footer=props.onApply?$jsx("text",{fg:theme.textMuted,children:step==="model"?"\u2190: providers":" "}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{children:"Scope: "}),$jsx("span",{fg:global2?theme.warning:theme.accent,children:global2?"global (persists to config)":"this session"}),$jsxs("span",{children:[" \xB7 Tab: toggle",step==="model"?" \xB7 \u2190: providers":""]})]});if(!data2)return $jsx("box",{width:50,padding:1,children:$jsx("text",{children:"Loading models\u2026"})});if(step==="provider"){let options2=(data2.providers??[]).map((p2)=>({title:p2.name,value:p2.slug,description:p2.total_models?`${p2.total_models} models`:void 0,category:p2.is_current?"Current":"Available"}));return $jsx(DialogSelect,{title:props.title??"Switch Provider",options:options2,current:data2.provider,onSelect:(o)=>{setProvider(o.value),setStep("model")},onKey,placeholder:"Search providers...",footer})}let p=data2.providers?.find((pp)=>pp.slug===provider),options=(p?.models??[]).map((m2)=>({title:m2,value:m2}));return $jsx(DialogSelect,{title:props.title?`${props.title} \xB7 ${p?.name??provider}`:`Switch Model (${p?.name??provider})`,options,current:data2.model,onSelect:(o)=>{if(provider)apply(o.value,provider);dialog.clear()},onKey,placeholder:"Search models...",footer})},openModelPicker=(dialog,gw,opts)=>{dialog.replace($jsx(ModelPickerDialog,{gw,title:opts?.title,onApply:opts?.onApply}))};var flatten=(obj,prefix="")=>Object.entries(obj).flatMap(([k2,v2])=>{let key2=prefix?`${prefix}.${k2}`:k2;if(v2&&typeof v2==="object"&&!Array.isArray(v2))return flatten(v2,key2);return[[key2,v2]]}),setNested=(obj,path7,val)=>{let parts2=path7.split("."),cur=obj;for(let i=0;i<parts2.length-1;i++){if(!cur[parts2[i]]||typeof cur[parts2[i]]!=="object")cur[parts2[i]]={};cur=cur[parts2[i]]}cur[parts2[parts2.length-1]]=val},getNested=(obj,path7)=>{let parts2=path7.split("."),cur=obj;for(let p of parts2)if(cur&&typeof cur==="object"&&!Array.isArray(cur))cur=cur[p];else return;return cur},FieldRow=import_react83.memo((props)=>{let theme=useTheme().theme,f=props.field,bg2=props.active?theme.backgroundElement:void 0,indicator=props.active?"\u25B8 ":" ",mark2=props.changed?"\u25CF ":f.set?"\xB7":" ",markFg=props.changed?theme.warning:theme.textMuted,display=()=>{if(props.editing)return props.buf+"\u2588";if(f.type==="readonly"){let n=Array.isArray(f.value)?f.value.length:f.value&&typeof f.value==="object"?Object.keys(f.value).length:0;return n===0?"\u2014":`${n} item${n===1?"":"s"}`}if(f.type==="boolean")return f.value?"\u2713 ON":"\u2717 OFF";return String(f.value??"")},hint=()=>{if(props.readonly||f.type==="readonly")return"\uD83D\uDD12";if(f.type==="boolean")return"[space]";if(f.type==="select")return"[h/l]";return"[enter]"},ro=props.readonly||f.type==="readonly",valFg=ro||!f.set?theme.textMuted:f.type==="boolean"?f.value?theme.success:theme.error:theme.text,labelFg=ro?theme.textMuted:props.active?theme.accent:theme.text,lead=4+(props.badge!==void 0?12:0),glyph=props.active?EFFECT_GLYPH[f.effect]:"";return $jsxs("box",{id:props.id,flexDirection:"column",backgroundColor:bg2,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:2,fg:markFg,children:mark2}),$jsx(Col,{w:2,fg:props.active?theme.primary:theme.text,children:indicator}),props.badge!==void 0?$jsx(Col,{w:12,fg:theme.textMuted,children:props.badge}):null,$jsx(Col,{w:40,fg:labelFg,children:f.label}),$jsx(Col,{grow:!0,min:6,fg:valFg,children:display()}),$jsx(Col,{w:2,fg:theme.textMuted,children:glyph}),$jsx(Col,{w:9,fg:theme.textMuted,right:!0,children:props.active?hint():""})]}),props.error?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx(Col,{w:lead+40,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:6,fg:theme.error,children:`\u2717 ${props.error}`})]}):props.active&&f.doc?$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:lead,flexShrink:0}),$jsx("box",{width:40,flexShrink:0,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:f.doc})})]}):null]})}),SlotRow=import_react83.memo((p)=>{let theme=useTheme().theme,main2=p.s.kind==="main",val=main2?`${p.s.provider||"(unset)"} \xB7 ${p.s.model||"(unset)"}`:p.s.auto?"auto (use main model)":`${p.s.provider} \xB7 ${p.s.model||"(provider default)"}`;return $jsxs("box",{id:p.id,flexDirection:"row",height:1,backgroundColor:p.on?theme.backgroundElement:void 0,children:[$jsx(Col,{w:2,fg:p.on?theme.primary:theme.text,children:p.on?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:main2?theme.primary:theme.textMuted,children:main2?"\u2605":" "}),$jsx(Col,{w:16,fg:p.on?theme.accent:theme.text,children:p.s.label}),$jsx(Col,{w:22,fg:theme.textMuted,children:p.s.hint}),$jsx(Col,{grow:!0,min:10,fg:p.s.auto?theme.textMuted:theme.text,children:val}),$jsx(Col,{w:14,fg:theme.textMuted,right:!0,children:p.on?main2?"[enter]":"[enter] [x]":""})]})}),Config=import_react83.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),toast=useToast(),dialog=useDialog(),[raw,setRaw]=import_react83.useState({}),[original,setOriginal]=import_react83.useState({}),[yaml,setYaml]=import_react83.useState(""),[mode,setMode]=import_react83.useState("form"),[cat,setCat]=import_react83.useState(0),[cursor,setCursor]=import_react83.useState(0),[editing,setEditing]=import_react83.useState(!1),[buf,setBuf]=import_react83.useState(""),[err,setErr]=import_react83.useState({}),[searching,setSearching]=import_react83.useState(!1),[query,setQuery]=import_react83.useState(""),[focus,setFocus]=import_react83.useState("categories"),[managed,setManaged]=import_react83.useState(null);import_react83.useEffect(()=>{managedSystem().then(setManaged)},[]);let load3=import_react83.useCallback(()=>{gw.request("config.get",{key:"full"}).then((res)=>{let parsed=res.config??{};setRaw(structuredClone(parsed)),setOriginal(structuredClone(parsed)),setYaml($stringify(parsed)),setErr({})}).catch(()=>{setRaw({}),setOriginal({}),setYaml("")})},[gw]);import_react83.useEffect(()=>{load3()},[load3]);let all=buildFields(raw),grouped=all.reduce((map,f)=>{let g=groupOf(f.key);if(!map.has(g))map.set(g,[]);return map.get(g).push(f),map},new Map(GROUPS.map((g)=>[g,[]]))),groups=[...grouped.keys()];groups.splice(1,0,"models");let active=groups[cat]??groups[0],onSlots=active==="models"&&!searching,slots=readSlots(raw),secs=searching&&query.trim()?[{head:null,items:all.filter((f)=>f.key.toLowerCase().includes(query.toLowerCase()))}]:sections(active,grouped.get(active)??[]),fields=secs.flatMap((s)=>s.items),count3=onSlots?slots.length:fields.length,follow=useFollow("cfg"),catFollow=useFollow("cfg-cat"),changed=(key2)=>JSON.stringify(getNested(raw,key2))!==JSON.stringify(getNested(original,key2)),nChanged=all.reduce((n,f)=>n+(changed(f.key)?1:0),0),update=(key2,val)=>{let next2=structuredClone(raw);setNested(next2,key2,val),setRaw(next2),setYaml($stringify(next2))},fmt3=(v2)=>v2===void 0?"\u2014":Array.isArray(v2)?v2.join(", "):String(v2),save2=async()=>{if(managed){toast.show({variant:"error",message:`Managed by ${managed} \u2014 edit configuration.nix`});return}let nErr=Object.keys(err).length;if(nErr>0){toast.show({variant:"error",message:`${nErr} invalid field${nErr===1?"":"s"}`});return}let target=mode==="yaml"?$parse(yaml)??{}:raw,diffs=flatten(target).filter(([key2])=>JSON.stringify(getNested(target,key2))!==JSON.stringify(getNested(original,key2))).map(([key2,val])=>({key:key2,from:getNested(original,key2),to:val}));if(diffs.length===0){toast.show({variant:"info",message:"No changes"});return}let body=diffs.map((d2)=>`${d2.key}: ${fmt3(d2.from)} \u2192 ${fmt3(d2.to)}`).join(`
@@ -4157,7 +4157,7 @@ Usage:
4157
4157
  *[interrupted]*`,usage:p?.usage};return{kind:"message.complete",text:p?.text??void 0,usage:p?.usage}}case"tool.start":return{kind:"tool.start",id:ev.payload.tool_id,name:ev.payload.name??"unknown",preview:ev.payload.context};case"tool.progress":return{kind:"tool.progress",name:ev.payload.name,preview:ev.payload.preview};case"tool.generating":return{kind:"tool.generating",name:ev.payload.name};case"tool.complete":return{kind:"tool.complete",id:ev.payload.tool_id,summary:ev.payload.summary,error:ev.payload.error,inline_diff:ev.payload.inline_diff};case"thinking.delta":return side.onStatus?.(ev.payload?.text??""),null;case"reasoning.delta":case"reasoning.available":{let text2=ev.payload?.text;if(!text2)return null;return{kind:"thinking",text:text2,final:ev.type==="reasoning.available"}}case"subagent.start":case"subagent.thinking":case"subagent.tool":case"subagent.progress":case"subagent.complete":{let sub2=ev.type.slice(9);return record(sub2,ev.payload),{kind:"subagent",event:sub2,payload:ev.payload}}case"error":return{kind:"error",text:ev.payload?.message??"Unknown error"};case"clarify.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"clarify",...ev.payload}};case"approval.request":return{kind:"prompt",id:`approval-${pid()}`,req:{variant:"approval",...ev.payload}};case"sudo.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"sudo",...ev.payload}};case"secret.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"secret",...ev.payload}};case"background.complete":return side.onBackground?.(ev.payload.task_id,ev.payload.text),null;case"review.summary":{let text2=String(ev.payload?.text??"").trim();if(!text2)return null;return{kind:"system",text:text2}}case"btw.complete":return side.onBtw?.(ev.payload.text),null;case"gateway.stderr":{let line3=ev.payload.line;if(/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i.test(line3))return{kind:"system",text:line3.slice(0,200)};return null}case"skin.changed":return side.onSkin?.(ev.payload),null;case"gateway.start_timeout":return{kind:"error",text:`gateway startup timed out (${ev.payload?.python??"python"} @ ${ev.payload?.cwd??"?"})`};case"gateway.protocol_error":return{kind:"system",text:`protocol error: ${ev.payload?.preview??"?"}`};case"browser.progress":{let text2=ev.payload?.message??"";if(!text2)return null;return ev.payload?.level==="error"?{kind:"error",text:text2}:{kind:"system",text:`\xB7 ${text2}`}}case"status.update":{let kind=ev.payload?.kind,text2=ev.payload?.text??"";if(side.onStatus?.(text2),!kind||kind==="status")return null;return{kind:"system",text:text2}}}return null}var import_react115=__toESM(require_react_production(),1);init_sessions_db();var normalize2=(sid)=>sid.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),resume=import_react115.useCallback(async(sid)=>{let target=normalize2(sid),res=await gw.request("session.resume",{session_id:target}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages}},[gw]),create=import_react115.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),res.session_id},[gw]),close=import_react115.useCallback(async(sid)=>{if(!sid)return;try{await gw.request("session.close",{session_id:sid})}catch{}},[gw]),boot2=import_react115.useCallback(async(launch)=>{let fresh=async(note)=>({id:await create(),messages:[],note});if(launch.mode==="resume"){let target=launch.sid??lastReal()?.id;if(!target)return fresh("no prior session to resume \u2014 starting fresh");try{return await resume(target)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh(`resume ${target} failed: ${msg} \u2014 starting fresh`)}}let last3=get("lastSessionId"),tip2=last3?chainTip(last3):null;if(tip2&&byId(tip2)?.message_count===0)try{return await resume(tip2)}catch{}return fresh()},[create,resume]),interrupt=import_react115.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react115.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react115.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react115.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react115.useMemo(()=>({boot:boot2,create,resume,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,close,interrupt,branch2,compress,undo])}var import_react117=__toESM(require_react_production(),1);import{tmpdir as tmpdir2}from"os";import{join as join16}from"path";import{rm}from"fs/promises";async function editInEditor(renderer,seed){let cmd=process.env.VISUAL||process.env.EDITOR;if(!cmd)return;let path7=join16(tmpdir2(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text2=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text2.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text2.trim()||void 0}function redraw(renderer){resolveRenderLib().clearTerminal(renderer.rendererPtr),renderer.currentRenderBuffer.clear(RGBA.fromValues(0,0,0,0)),renderer.requestRender()}var INTERRUPT_MS=5000,DOUBLE_TAB_MS=400;function useAppKeys(o){let renderer=useRenderer(),keys=useKeys(),lastEsc=import_react117.useRef(0),lastTab=import_react117.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react117.useEffect(()=>{let found=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found.length===0)return;let first=found[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found.length>1?` (+${found.length-1} more)`:""))},[keys.table]),useKeyboard((key2)=>{let c=o.composer.current;if(keys.match("input.clear",key2)&&c&&!c.isEmpty()){c.set(""),key2.stopPropagation();return}if(keys.match("app.exit",key2))return o.onQuit();if(keys.match("app.suspend",key2)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key2)){redraw(renderer),key2.stopPropagation();return}if(keys.match("app.sidebar",key2)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(keys.match("queue.flush",key2)&&o.streaming&&o.queued>0){o.onFlushQueue(),key2.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key2.ctrl&&!key2.meta&&key2.eventType!=="release"){if(o.onPromptKey(key2)){key2.stopPropagation();return}}if(keys.match("editor.open",key2)&&!o.streaming){let seed=c?.value()??"";editInEditor(renderer,seed).then((out)=>{if(out===void 0){if(!process.env.VISUAL&&!process.env.EDITOR)o.onNotice("Set $EDITOR or $VISUAL to use the external editor");return}c?.set(out),o.setFocusRegion("input")});return}if(keys.match("tab.prev",key2)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key2)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key2.shift&&!key2.ctrl&&!key2.meta&&key2.eventType!=="release"){if(key2.name==="left"){o.cycleSub(-1),key2.stopPropagation();return}if(key2.name==="right"){o.cycleSub(1),key2.stopPropagation();return}}if(keys.leader&&!key2.ctrl&&!key2.meta&&!key2.shift&&key2.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key2.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key2.stopPropagation();return}}if(key2.meta&&!key2.ctrl&&!key2.shift&&key2.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key2.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key2.stopPropagation();return}}if(c?.popOpen()){if(key2.name==="escape")return c.popCancel();if(key2.name==="up"){c.popNav(-1),key2.stopPropagation();return}if(key2.name==="down"){c.popNav(1),key2.stopPropagation();return}if(key2.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key2)&&!o.streaming){if(o.tab===o.chatTab){o.setFocusRegion((r)=>r==="input"?"content":"input");return}if(o.focusRegion==="input"){o.setFocusRegion("content");return}let now2=Date.now();if(now2-lastTab.current<DOUBLE_TAB_MS)o.setFocusRegion("input"),lastTab.current=0,key2.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key2)){if(!o.streaming&&o.onEscape?.())return;if(o.streaming){let now2=Date.now();if(now2-lastEsc.current<INTERRUPT_MS){o.onInterrupt(),lastEsc.current=0;return}lastEsc.current=now2,o.onInterruptNotice();return}if(o.tab===o.chatTab&&o.focusRegion==="content")o.setFocusRegion("input");return}if(keys.match("reply.copy",key2))return o.onCopyLast();if(keys.match("clipboard.attach",key2)){o.onAttachClipboard(),key2.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if(key2.name==="up")return void c?.historyUp();if(key2.name==="down")return void c?.historyDown();if(key2.name==="backspace"&&!key2.ctrl&&!key2.meta&&c?.isEmpty()&&o.onDetachLast()){key2.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key2.ctrl&&!key2.meta&&key2.eventType!=="release"){if(key2.name.length===1&&key2.name!==" "){let ch=key2.shift&&/[a-z]/.test(key2.name)?key2.name.toUpperCase():key2.name;o.setFocusRegion("input"),c?.insert(ch),key2.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY&&sid){let t2=title?` \u2014 ${title.slice(0,60)}`:"";writeSync(1,`
4158
4158
  continue herm --resume ${sid}${t2}
4159
4159
 
4160
- `)}process.exit(0)}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache2.clear(),resetKanban(),reload(),home2.reset()}var import_react118=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react118.useState(p.seconds);import_react118.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid)=>{if(!sid)return;io.goalState(sid).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid)===s.goal)return;fired.set(sid,s.goal);let list=s.checklist??[],done2=list.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list.length)}).catch(()=>{})}}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),cmd=useCommand(),toast=useToast(),renderer=useRenderer(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react121.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react121.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react121.useState(!1),[sid,setSid]=import_react121.useState(""),sidRef=import_react121.useRef(sid);sidRef.current=sid;let[tab,setTab]=import_react121.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react121.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0})),setSub=import_react121.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react121.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react121.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react121.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react121.useState(!1),[usage,setUsage]=import_react121.useState(void 0),[info2,setInfo]=import_react121.useState(null),[title,setTitle]=import_react121.useState(""),[focusRegion,setFocusRegion]=import_react121.useState("input"),goToTab=import_react121.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react121.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react121.useState(""),[eikon,setEikon]=import_react121.useState(void 0),[queue,setQueue]=import_react121.useState([]),[busy,setBusy]=import_react121.useState("queue"),turnRef=import_react121.useRef(turn);turnRef.current=turn;let queueRef=import_react121.useRef(queue);queueRef.current=queue;let launchRef=import_react121.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react121.useState(launch.splash!==!1),[switching,setSwitching]=import_react121.useState(!1),summoned=import_react121.useRef(!1),[composing,setComposing]=import_react121.useState(!1),splashLast=import_react121.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react121.useMemo(()=>info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,[info2?.version,info2?.update_behind,info2?.model]),splashLastProp=import_react121.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react121.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react121.useState([]),[cloudH,setCloudH]=import_react121.useState(CLOUD_MIN),[pick,setPick]=import_react121.useState(void 0),[skin,setSkin]=import_react121.useState(()=>deriveSkin(void 0)),inflight=import_react121.useRef(!1),interrupted=import_react121.useRef(!1),sessionStart=import_react121.useRef(Date.now()),composer2=import_react121.useRef(null),promptRef=import_react121.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react121.useRef(cmds);cmdsRef.current=cmds;let[errorPulse,setErrorPulse]=import_react121.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react121.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react121.useMemo(()=>pending(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react121.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react121.useRef(turn.streaming);import_react121.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react121.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react121.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react121.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react121.useRef(()=>{}),onEnqueue=import_react121.useCallback((t2)=>{if(busy==="steer"){gw.request("session.steer",{text:t2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"steered \u2014 lands on next tool result"});setQueue((q4)=>[...q4,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q4)=>[...q4,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q4)=>[t2,...q4]);setQueue((q4)=>[...q4,t2])},[busy,gw,toast]),onAttach=import_react121.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),reset=import_react121.useCallback(()=>{interrupted.current=!1,dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[]),newSession=import_react121.useCallback(async()=>{let prev=sidRef.current;if(reset(),summoned.current=!0,setSplash(!0),prev)session.close(prev);try{setSid(await session.create()),sessionStart.current=Date.now()}catch{}},[reset,session]),switchSession=import_react121.useCallback(async(target)=>{let prev=sidRef.current;reset(),summoned.current=!0,setSplash(!0),setSwitching(!0),goToTab(CHAT_TAB);try{let res=await session.resume(target);if(setSid(res.id),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev);setSplash(!1),summoned.current=!1}catch(err){dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset,session,goToTab]),switchProfile=import_react121.useCallback((newHome,name)=>{rehome(newHome),reset(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset,goToTab,gwRestart,toast,gw]),runCompress=import_react121.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await session.compress();if(!r)return;if(r.info)setInfo(r.info);if(r.usage)setUsage(r.usage);if(Array.isArray(r.messages))dispatch({kind:"load",messages:transcriptToMessages(r.messages)});if(!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines2=[s.headline,s.token_line,s.note].filter(Boolean).join(`
4160
+ `)}process.exit(0)}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache2.clear(),resetKanban(),reload(),home2.reset()}var import_react118=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react118.useState(p.seconds);import_react118.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid)=>{if(!sid)return;io.goalState(sid).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid)===s.goal)return;fired.set(sid,s.goal);let list=s.checklist??[],done2=list.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list.length)}).catch(()=>{})}}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),cmd=useCommand(),toast=useToast(),renderer=useRenderer(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react121.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react121.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react121.useState(!1),[sid,setSid]=import_react121.useState(""),sidRef=import_react121.useRef(sid);sidRef.current=sid;let[tab,setTab]=import_react121.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react121.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0})),setSub=import_react121.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react121.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react121.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react121.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react121.useState(!1),[usage,setUsage]=import_react121.useState(void 0),[info2,setInfo]=import_react121.useState(null),[title,setTitle]=import_react121.useState(""),[focusRegion,setFocusRegion]=import_react121.useState("input"),goToTab=import_react121.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react121.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react121.useState(""),[eikon,setEikon]=import_react121.useState(void 0),[queue,setQueue]=import_react121.useState([]),[busy,setBusy]=import_react121.useState("queue"),turnRef=import_react121.useRef(turn);turnRef.current=turn;let queueRef=import_react121.useRef(queue);queueRef.current=queue;let launchRef=import_react121.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react121.useState(launch.splash!==!1),[switching,setSwitching]=import_react121.useState(!1),summoned=import_react121.useRef(!1),[composing,setComposing]=import_react121.useState(!1),splashLast=import_react121.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react121.useMemo(()=>info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,[info2?.version,info2?.update_behind,info2?.model]),splashLastProp=import_react121.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react121.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react121.useState([]),[cloudH,setCloudH]=import_react121.useState(CLOUD_MIN),[pick,setPick]=import_react121.useState(void 0),[skin,setSkin]=import_react121.useState(()=>deriveSkin(void 0)),inflight=import_react121.useRef(!1),interrupted=import_react121.useRef(!1),sessionStart=import_react121.useRef(Date.now()),composer2=import_react121.useRef(null),promptRef=import_react121.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react121.useRef(cmds);cmdsRef.current=cmds;let[errorPulse,setErrorPulse]=import_react121.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react121.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react121.useMemo(()=>pending(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react121.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react121.useRef(turn.streaming);import_react121.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react121.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react121.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react121.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react121.useRef(()=>{}),onEnqueue=import_react121.useCallback((t2)=>{if(busy==="steer"){gw.request("session.steer",{text:t2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"steered \u2014 lands on next tool result"});setQueue((q4)=>[...q4,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q4)=>[...q4,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q4)=>[t2,...q4]);setQueue((q4)=>[...q4,t2])},[busy,gw,toast]),onAttach=import_react121.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),reset=import_react121.useCallback(()=>{interrupted.current=!1,dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[]),newSession=import_react121.useCallback(async()=>{let prev=sidRef.current;if(reset(),summoned.current=!0,setSplash(!0),prev)session.close(prev);try{setSid(await session.create()),sessionStart.current=Date.now()}catch{}},[reset,session]),switchSession=import_react121.useCallback(async(target)=>{let prev=sidRef.current;reset(),summoned.current=!0,setSplash(!0),setSwitching(!0),goToTab(CHAT_TAB);try{let res=await session.resume(target);if(setSid(res.id),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev);setSplash(!1),summoned.current=!1}catch(err){dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset,session,goToTab]),switchProfile=import_react121.useCallback((newHome,name)=>{rehome(newHome),reset(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset,goToTab,gwRestart,toast,gw]),runCompress=import_react121.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await session.compress();if(!r)return;if(r.info)setInfo(r.info);if(setUsage((u3)=>{let base2=r.usage??u3,max=r.usage?.context_max??u3?.context_max;if(typeof r.after_tokens!=="number"||typeof max!=="number")return base2;return{...base2??{input:0,output:0,total:0},context_used:r.after_tokens,context_max:max}}),Array.isArray(r.messages))dispatch({kind:"load",messages:transcriptToMessages(r.messages)});if(!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines2=[s.headline,s.token_line,s.note].filter(Boolean).join(`
4161
4161
  `);if(lines2)dispatch({kind:"system",text:lines2});toast.show({variant:"success",message:s.headline??`Compressed ${r.before_messages??0}\u2192${r.after_messages??0} messages`})},[session,toast,dispatch]),loadEikon=import_react121.useCallback((path7)=>{Bun.file(path7).text().then((t2)=>setEikon(parseEikon(t2))).catch(()=>{})},[]),eikonPath=usePref("eikonPath");import_react121.useEffect(()=>{let p=eikonPath||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonPath,skin.skin?.name,loadEikon]);let pickEikon=import_react121.useCallback(()=>{openEikonPicker(dialog,(path7)=>set("eikonPath",path7))},[dialog]),applyTitle=import_react121.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{setTitle(r.title),dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),editTitle=import_react121.useCallback(()=>{openTextPrompt(dialog,{title:"Session Title",initial:title}).then((v2)=>{if(v2)applyTitle(v2)})},[dialog,title,applyTitle]),turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react121.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text2),setFocusRegion("input")},[gw]),fork=import_react121.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await switchSession(res.session_id),composer2.current?.set(text2),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,switchSession]),msgMenu=import_react121.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork})},[dialog,rewind,fork]),attachClipboard=import_react121.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),cfg=useHome("config"),destructive=import_react121.useCallback((arg,opts,action)=>{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",bypass=!(cfg?.approvals?.destructive_slash_confirm??!0)||process.env.HERMES_TUI_NO_CONFIRM==="1",persist2=a==="always",fire=()=>{if(persist2)Promise.resolve().then(() => (init_lane(),exports_lane)).then(({writeConfig:writeConfig2})=>writeConfig2(gw,[{key:"approvals.destructive_slash_confirm",to:!1}]).then((r)=>{if(r.failed.length){toast.show({variant:"warning",message:`couldn't persist: ${r.failed[0].err}`});return}home2.invalidate("config"),toast.show({variant:"success",message:`${opts.yes} \xB7 future runs silent`})}).catch((e)=>toast.show({variant:"error",message:e.message})));action()};if(skip||bypass)return fire();openConfirm(dialog,{title:opts.title,body:opts.body,yes:opts.yes,danger:!0}).then((ok)=>{if(ok)fire()})},[cfg,dialog,gw,toast]),sendRef=import_react121.useRef(()=>{}),slash=import_react121.useCallback((c,arg="")=>{if(c.target==="local")switch(c.name){case"clear":destructive(arg,{title:"Clear session?",body:"Discards the in-memory transcript. Your session on disk is unchanged; reload to restore.",yes:"clear"},()=>dispatch({kind:"reset"}));return;case"new":destructive(arg,{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{newSession()});return;case"theme":openThemePicker(dialog,themeCtx);return;case"help":dialog.replace($jsx(HelpDialog,{}));return;case"keys":openKeys(dialog);return;case"logs":openLogs(dialog);return;case"eikon":pickEikon();return;case"title":arg?applyTitle(arg):editTitle();return;case"rollback":openRollback(dialog,gw,toast);return;case"history":openHistory(dialog,gw);return;case"status":openStatus(dialog,info2,sid);return;case"usage":openUsage(dialog,gw);return;case"profile":openProfile(dialog);return;case"chafa":if(!arg.trim()){toast.show({variant:"info",message:"usage: /chafa <path>"});return}openChafa(dialog,arg.trim());return;case"splash":summoned.current=!0,setSplash(!0);return;case"skin":{let name=arg.trim();if(!name){dispatch({kind:"system",text:`skin: ${skin.skin?.name??"\u2014"}
4162
4162
  ${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikonPath",void 0),dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){switchSession(arg);return}goTo(TAB_SLASH.sessions.tab,TAB_SLASH.sessions.sub);return;case"branch":session.branch(arg||void 0).then((id)=>id?void switchSession(id):toast.show({variant:"error",message:"branch failed"}));return;case"compress":runCompress();return;case"undo":destructive(arg,{title:"Undo last turn?",body:"Pops the last user + assistant pair from the transcript. Cannot be undone.",yes:"undo"},()=>{session.undo().then(()=>gw.request("session.history").then((r)=>dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}))});return;case"retry":{let last3=[...turnRef.current.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}rewind(last3).then(()=>sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,sid,title,gw);return;case"queue":if(!arg){dispatch({kind:"system",text:`${queueRef.current.length} queued`});return}setQueue((q4)=>[...q4,arg]);return;case"copy":{let all=turnRef.current.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all.length):all.length,m2=all[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":gw.request("voice.toggle",{action:(arg||"status").toLowerCase()}).then((r)=>dispatch({kind:"system",text:`voice ${r.enabled?"on":"off"}${r.tts?" \xB7 tts on":""}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"compact":case"setup":dispatch({kind:"system",text:`/${c.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text2)=>gw.request("session.steer",{text:text2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text2)=>{if(text2)fire(text2)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c.target!=="gateway"||!ready)return;let jump=TAB_SLASH[c.name];if(jump!==void 0&&!arg){goTo(jump.tab,jump.sub);return}let full=`/${c.name}${arg?" "+arg:""}`;if(turnRef.current.streaming){setQueue((q4)=>[...q4,full]);return}dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c.name,arg}).then((d2)=>{if(d2.notice)dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c.name}`});return void sendRef.current(d2.message)}dispatch({kind:"system",text:`/${c.name}: unknown`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`}))})},[ready,dialog,themeCtx,newSession,gw,pickEikon,editTitle,applyTitle,toast,info2,sid,title,switchSession,session,runCompress,rewind,renderer,attachClipboard,goTo,skin,destructive]),send=import_react121.useCallback(async(raw)=>{let m2=raw.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve7(cmdsRef.current,name);if("hit"in r)return slash(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text2=raw;if(hasInterp(raw))setStatus("interpolating\u2026"),text2=await interpolate(gw,raw),setStatus("");interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text2].filter(Boolean).join(`
4163
4163
  `):text2;dispatch({kind:"user",text:withMedia}),setAttachments([]),gw.request("prompt.submit",{text:text2}).catch(()=>{inflight.current=!1}),setTab(CHAT_TAB)},[gw,slash,attachments]);sendRef.current=send;let onSend=import_react121.useCallback((raw)=>{return setSplash(!1),send(raw)},[send]),onEmptyEnter=import_react121.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react121.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react121.useEffect(()=>{if(turn.streaming||inflight.current||!ready||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[turn.streaming,ready,queue,send]);let dequeue=import_react121.useCallback((i)=>{let item=queueRef.current[i];if(item===void 0)return;setQueue((q4)=>q4.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[]),copyLast=import_react121.useCallback(()=>{let msgs=turnRef.current.messages;for(let i=msgs.length-1;i>=0;i--){let m2=msgs[i];if(m2.role!=="assistant")continue;let text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");if(!text2)continue;return process.stdout.write(`\x1B]52;c;${Buffer.from(text2).toString("base64")}\x07`),!0}return!1},[]),deltas=import_react121.useRef({text:"",think:"",timer:null}),flush2=import_react121.useCallback(()=>{let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;if(d2.think)dispatch({kind:"thinking",text:d2.think,final:!1}),d2.think="";if(d2.text)dispatch({kind:"message.delta",chunk:d2.text}),d2.text=""},[]),STREAM_EVENTS=import_react121.useRef(new Set(["message.start","message.delta","reasoning.delta","reasoning.available","thinking.delta","tool.start","tool.progress","tool.generating"])).current,handle2=import_react121.useCallback((ev)=>{if(interrupted.current){if(STREAM_EVENTS.has(ev.type))return;if(ev.type==="status.update"&&ev.payload?.kind==="lifecycle")return}let action=mapEvent(ev,{onReady:()=>{session.boot(launchRef.current).then((r)=>{if(setSid(r.id),sessionStart.current=Date.now(),r.messages.length)dispatch({kind:"load",messages:r.messages});if(r.note)toast.show({variant:"info",message:r.note})})},onSessionInfo:(si)=>{if(setInfo(si),setReady(!0),si.session_id)setSid(si.session_id);let bad=(si.mcp_servers??[]).filter((s)=>!s.connected);if(bad.length)dispatch({kind:"system",text:`MCP: ${bad.length} server(s) failed to connect \u2014 ${bad.map((s)=>s.name+(s.error?` (${s.error})`:"")).join(", ")}`});gw.request("session.title").then((r)=>{if(setTitle(r.title??""),r.session_key)set("lastSessionId",r.session_key)}).catch(()=>{}),gw.request("config.get",{key:"busy"}).then((r)=>{let m2=r.value;if(m2==="queue"||m2==="steer"||m2==="interrupt")setBusy(m2)}).catch(()=>{})},onUsage:(u3)=>setUsage(u3),onTurnComplete:()=>{setStatus(""),flush(gw,sidRef.current),goalHook.check(sidRef.current)},onBackground:(tid,text2)=>{let head=text2.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herm-tui",
3
- "version": "1.3.0-dev.13",
3
+ "version": "1.3.0-dev.14",
4
4
  "description": "A modern TUI for Hermes Agent",
5
5
  "license": "MIT",
6
6
  "repository": {