herm-tui 1.9.0-dev.32 → 1.9.0-dev.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/db.worker.js +7 -4
  2. package/index.js +15 -12
  3. package/package.json +1 -1
package/db.worker.js CHANGED
@@ -22,12 +22,15 @@ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defP
22
22
  ORDER BY c.started_at DESC LIMIT 1`)?.get(sid);return{...pred&&{continuesFrom:pred},...succ&&{compressedTo:succ}}}finally{end()}}function tip(sid){let step=q(`SELECT c.id FROM sessions c
23
23
  JOIN sessions p ON p.id = c.parent_session_id
24
24
  WHERE p.id = ? AND ${CONT("c")}
25
- ORDER BY c.started_at DESC LIMIT 1`),cur=sid;for(let i=0;i<100;i++){let next=step?.get(cur);if(!next)return cur;cur=next.id}return cur}function peek(sid,n=60){let end=mark("io:sessions.peek");try{let ext=[hasMsgCol("platform_message_id")?"platform_message_id":"NULL AS platform_message_id",hasMsgCol("observed")?"observed":"NULL AS observed"];return(q(`SELECT role, SUBSTR(content,1,400) AS content, tool_name,
25
+ ORDER BY c.started_at DESC LIMIT 1`),cur=sid;for(let i=0;i<100;i++){let next=step?.get(cur);if(!next)return cur;cur=next.id}return cur}function peek(sid,_n=4){let end=mark("io:sessions.peek");try{let ext=[hasMsgCol("platform_message_id")?"platform_message_id":"NULL AS platform_message_id",hasMsgCol("observed")?"observed":"NULL AS observed"];return(q(`SELECT role, SUBSTR(content,1,400) AS content, tool_name,
26
26
  SUBSTR(tool_calls,1,400) AS tool_calls, timestamp AS at,
27
27
  ${ext.join(", ")}
28
- FROM (SELECT * FROM messages WHERE session_id = ?
29
- ORDER BY id DESC LIMIT ?)
30
- ORDER BY id ASC`)?.all(sid,n)??[]).map((r)=>({role:r.role,content:r.content,tool_name:r.tool_name,tool_calls:r.tool_calls,...r.platform_message_id!==null&&{platform_message_id:r.platform_message_id},...r.observed!==null&&{observed:r.observed},at:r.at}))}finally{end()}}function goalState(sid){let row=q("SELECT value FROM state_meta WHERE key = ?")?.get(`goal:${sid}`);if(!row)return null;try{let j=JSON.parse(row.value),checklist=(Array.isArray(j.checklist)?j.checklist:[]).map(parseItem).filter((x)=>x!==null),subgoals=(Array.isArray(j.subgoals)?j.subgoals:[]).map((s)=>typeof s==="string"?s.trim():"").filter((s)=>s.length>0);return{goal:String(j.goal??""),status:j.status??"active",turn_count:typeof j.turn_count==="number"?j.turn_count:void 0,max_turns:j.max_turns??null,checklist:checklist.length>0?checklist:void 0,subgoals:subgoals.length>0?subgoals:void 0,decomposed:j.decomposed===!0?!0:void 0}}catch{return null}}function search(query,limit=30){let m=fts(query);if(!m)return[];let end=mark("io:sessions.search");try{let raw=q(`SELECT m.session_id, m.role,
28
+ FROM (
29
+ SELECT * FROM (SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC LIMIT 2)
30
+ UNION
31
+ SELECT * FROM (SELECT * FROM messages WHERE session_id = ? ORDER BY id DESC LIMIT 2)
32
+ )
33
+ ORDER BY id ASC`)?.all(sid,sid)??[]).map((r)=>({role:r.role,content:r.content,tool_name:r.tool_name,tool_calls:r.tool_calls,...r.platform_message_id!==null&&{platform_message_id:r.platform_message_id},...r.observed!==null&&{observed:r.observed},at:r.at}))}finally{end()}}function goalState(sid){let row=q("SELECT value FROM state_meta WHERE key = ?")?.get(`goal:${sid}`);if(!row)return null;try{let j=JSON.parse(row.value),checklist=(Array.isArray(j.checklist)?j.checklist:[]).map(parseItem).filter((x)=>x!==null),subgoals=(Array.isArray(j.subgoals)?j.subgoals:[]).map((s)=>typeof s==="string"?s.trim():"").filter((s)=>s.length>0);return{goal:String(j.goal??""),status:j.status??"active",turn_count:typeof j.turn_count==="number"?j.turn_count:void 0,max_turns:j.max_turns??null,checklist:checklist.length>0?checklist:void 0,subgoals:subgoals.length>0?subgoals:void 0,decomposed:j.decomposed===!0?!0:void 0}}catch{return null}}function search(query,limit=30){let m=fts(query);if(!m)return[];let end=mark("io:sessions.search");try{let raw=q(`SELECT m.session_id, m.role,
31
34
  snippet(messages_fts, 0, '>>>', '<<<', '...', 40) AS snippet,
32
35
  s.source, s.model, s.started_at,
33
36
  COALESCE(s.title, SUBSTR(m.content, 1, 120)) AS title
package/index.js CHANGED
@@ -3301,12 +3301,15 @@ ${closingIndent}}`}default:return"any"}}function formatFunctionDefinitions(funct
3301
3301
  ORDER BY c.started_at DESC LIMIT 1`)?.get(sid);return{...pred&&{continuesFrom:pred},...succ&&{compressedTo:succ}}}finally{end()}}function tip(sid){let step=q2(`SELECT c.id FROM sessions c
3302
3302
  JOIN sessions p ON p.id = c.parent_session_id
3303
3303
  WHERE p.id = ? AND ${CONT("c")}
3304
- ORDER BY c.started_at DESC LIMIT 1`),cur=sid;for(let i=0;i<100;i++){let next=step?.get(cur);if(!next)return cur;cur=next.id}return cur}function peek4(sid,n=60){let end=mark("io:sessions.peek");try{let ext=[hasMsgCol("platform_message_id")?"platform_message_id":"NULL AS platform_message_id",hasMsgCol("observed")?"observed":"NULL AS observed"];return(q2(`SELECT role, SUBSTR(content,1,400) AS content, tool_name,
3304
+ ORDER BY c.started_at DESC LIMIT 1`),cur=sid;for(let i=0;i<100;i++){let next=step?.get(cur);if(!next)return cur;cur=next.id}return cur}function peek4(sid,_n=4){let end=mark("io:sessions.peek");try{let ext=[hasMsgCol("platform_message_id")?"platform_message_id":"NULL AS platform_message_id",hasMsgCol("observed")?"observed":"NULL AS observed"];return(q2(`SELECT role, SUBSTR(content,1,400) AS content, tool_name,
3305
3305
  SUBSTR(tool_calls,1,400) AS tool_calls, timestamp AS at,
3306
3306
  ${ext.join(", ")}
3307
- FROM (SELECT * FROM messages WHERE session_id = ?
3308
- ORDER BY id DESC LIMIT ?)
3309
- ORDER BY id ASC`)?.all(sid,n)??[]).map((r)=>({role:r.role,content:r.content,tool_name:r.tool_name,tool_calls:r.tool_calls,...r.platform_message_id!==null&&{platform_message_id:r.platform_message_id},...r.observed!==null&&{observed:r.observed},at:r.at}))}finally{end()}}function goalState(sid){let row3=q2("SELECT value FROM state_meta WHERE key = ?")?.get(`goal:${sid}`);if(!row3)return null;try{let j2=JSON.parse(row3.value),checklist=(Array.isArray(j2.checklist)?j2.checklist:[]).map(parseItem).filter((x2)=>x2!==null),subgoals=(Array.isArray(j2.subgoals)?j2.subgoals:[]).map((s)=>typeof s==="string"?s.trim():"").filter((s)=>s.length>0);return{goal:String(j2.goal??""),status:j2.status??"active",turn_count:typeof j2.turn_count==="number"?j2.turn_count:void 0,max_turns:j2.max_turns??null,checklist:checklist.length>0?checklist:void 0,subgoals:subgoals.length>0?subgoals:void 0,decomposed:j2.decomposed===!0?!0:void 0}}catch{return null}}function search(query,limit=30){let m2=fts(query);if(!m2)return[];let end=mark("io:sessions.search");try{let raw=q2(`SELECT m.session_id, m.role,
3307
+ FROM (
3308
+ SELECT * FROM (SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC LIMIT 2)
3309
+ UNION
3310
+ SELECT * FROM (SELECT * FROM messages WHERE session_id = ? ORDER BY id DESC LIMIT 2)
3311
+ )
3312
+ ORDER BY id ASC`)?.all(sid,sid)??[]).map((r)=>({role:r.role,content:r.content,tool_name:r.tool_name,tool_calls:r.tool_calls,...r.platform_message_id!==null&&{platform_message_id:r.platform_message_id},...r.observed!==null&&{observed:r.observed},at:r.at}))}finally{end()}}function goalState(sid){let row3=q2("SELECT value FROM state_meta WHERE key = ?")?.get(`goal:${sid}`);if(!row3)return null;try{let j2=JSON.parse(row3.value),checklist=(Array.isArray(j2.checklist)?j2.checklist:[]).map(parseItem).filter((x2)=>x2!==null),subgoals=(Array.isArray(j2.subgoals)?j2.subgoals:[]).map((s)=>typeof s==="string"?s.trim():"").filter((s)=>s.length>0);return{goal:String(j2.goal??""),status:j2.status??"active",turn_count:typeof j2.turn_count==="number"?j2.turn_count:void 0,max_turns:j2.max_turns??null,checklist:checklist.length>0?checklist:void 0,subgoals:subgoals.length>0?subgoals:void 0,decomposed:j2.decomposed===!0?!0:void 0}}catch{return null}}function search(query,limit=30){let m2=fts(query);if(!m2)return[];let end=mark("io:sessions.search");try{let raw=q2(`SELECT m.session_id, m.role,
3310
3313
  snippet(messages_fts, 0, '>>>', '<<<', '...', 40) AS snippet,
3311
3314
  s.source, s.model, s.started_at,
3312
3315
  COALESCE(s.title, SUBSTR(m.content, 1, 120)) AS title
@@ -3683,7 +3686,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
3683
3686
  \u2026`;if(raw[i]===`
3684
3687
  `&&++n>LINES)return`${raw.slice(0,i).trimEnd()}
3685
3688
  \u2026`}return raw}function lines2(s){let n=1;for(let i=0;i<s.length;i++)if(s[i]===`
3686
- `&&++n>=5)return 6;return n+1}var Inline=import_react21.memo(({branch,details,tool})=>{let s=spec(tool.name),body=tool.preview&&!isDiff(tool.preview)?short(tool.preview):"",label=s.verb&&body?`${s.verb} ${body}`:body||s.verb||tool.name;return $jsx(InlineTool,{branch,part:tool,complete:!!body||tool.status!=="running",details,children:label})});function visible(tool,mode){return mode!=="hidden"||tool.status==="running"}function details(tool,mode){let full=tool.verboseResult&&!isDiff(tool.verboseResult)?tool.verboseResult:void 0,sum=tool.result&&!isDiff(tool.result)?tool.result:void 0,err=tool.status==="error"&&(full||sum)?{label:"Error",text:cap(full??sum),tone:"error"}:void 0;if(mode!=="expanded")return err?[err]:[];let out=[];if(tool.verboseArgs)out.push({label:"Args",text:cap(tool.verboseArgs)});if(err)out.push(err);if(tool.verboseResult&&tool.status!=="error"&&!isDiff(tool.verboseResult))out.push({label:"Result",text:cap(tool.verboseResult)});return out}function cost(tool,mode){if(!visible(tool,mode))return 0;if(tool.trail)return 2+Math.min(tool.trail.length,TRAIL);if(tool.name==="delegate_task")return 2;return 1+details(tool,mode).reduce((n,d2)=>n+lines2(d2.text),0)}var Tool=import_react21.memo(({branch,tool,detail="expanded"})=>{let list=import_react21.useMemo(()=>details(tool,detail),[tool,detail]);if(!visible(tool,detail))return null;if(tool.trail||tool.name==="delegate_task")return $jsx(Subagent,{branch,tool});return $jsx(Inline,{branch,details:list,tool})});var CLOUD_MIN=12,CLOUD_MAX=24,CLOUD={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2504",vertical:"\u2506",topT:"\u2504",bottomT:"\u2504",leftT:"\u2506",rightT:"\u2506",cross:"\u253C"},SLOTS=[["\u256D\u2504\u2504\u256E ","\u2570\u2504\u2504\u256F "],[" \u256D\u256E "," \u2570\u256F "],[" \u2576 "," "]],BLANK=" ",ORDER=[2,1,0,-1],Tail=import_react22.memo((props)=>{let theme=useTheme().theme,refs=import_react22.useRef([]),paint=(lit)=>{SLOTS.forEach((slot,i)=>slot.forEach((l,j2)=>{let node=refs.current[i*2+j2];if(node)node.children=[lit===null||lit===i?l:BLANK]}))};return import_react22.useEffect(()=>{if(!props.run){paint(null);return}let f=0;paint(ORDER[0]);let t2=setInterval(()=>{f=(f+1)%ORDER.length,paint(ORDER[f])},160);return()=>{clearInterval(t2),paint(null)}},[props.run]),$jsx("box",{flexDirection:"column",children:SLOTS.flatMap((slot,i)=>slot.map((l,j2)=>$jsx("text",{fg:theme.hermAvatar,children:$jsx("span",{ref:(el)=>{refs.current[i*2+j2]=el},children:l})},`${i}-${j2}`)))})});function parts(m2){return m2?.parts.filter((p)=>p.type==="thinking"||p.type==="tool")??[]}function latest(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="assistant")return messages[i];return}function rows(list,detail){return list.reduce((n,p)=>n+(p.type==="thinking"?Math.ceil(p.content.length/80)||1:p.type==="tool"?cost(p,detail):1),0)}var ThoughtCloud=import_react22.memo((props)=>{let{theme,syntaxStyle}=useTheme(),detail=usePref("toolDetails")??"expanded",src=props.pick??latest(props.messages),all=parts(src),think=all.filter((p)=>p.type==="thinking"),seen=all.filter((p)=>p.type==="tool").filter((t2)=>visible(t2,detail)),[pane,setPane]=import_react22.useState("reasoning");import_react22.useEffect(()=>{if(pane==="reasoning"&&think.length===0&&seen.length>0)setPane("tools");if(pane==="tools"&&seen.length===0&&think.length>0)setPane("reasoning")},[pane,think.length,seen.length]);let body=pane==="reasoning"?think:seen,manual=import_react22.useRef(!1),want=Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,rows(body,detail)+3)),resize=props.onResize;import_react22.useEffect(()=>{if(!manual.current)resize(want)},[want,resize]);let drag=import_react22.useRef(null),grab=(e)=>{drag.current={y:e.y,h:props.height},manual.current=!0,e.stopPropagation()},move=(e)=>{let d2=drag.current;if(!d2)return;resize(Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,d2.h+(e.y-d2.y))))},drop=()=>{drag.current=null},pill=(id,label,n)=>{let on=pane===id;return $jsx("box",{height:1,marginRight:2,onMouseDown:(e)=>{e.stopPropagation(),setPane(id)},children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:on?$jsx("strong",{children:label}):label}),n!==null&&n>0?$jsx("span",{fg:theme.textMuted,children:` ${n}`}):null]})})};return $jsxs("box",{height:props.height,flexDirection:"column",position:"relative",marginLeft:1,border:!0,borderColor:theme.hermAvatar,customBorderChars:CLOUD,backgroundColor:theme.backgroundPanel,paddingX:1,children:[$jsxs("box",{height:1,flexShrink:0,flexDirection:"row",children:[pill("reasoning","reasoning",null),pill("tools","tools",seen.length),$jsx("box",{flexGrow:1}),detail!=="expanded"?$jsx("box",{marginRight:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u27E8",detail,"\u27E9"]})}):null,props.onClose?$jsx("box",{width:1,onMouseDown:props.onClose,children:$jsx("text",{fg:theme.textMuted,children:"\xD7"})}):null]}),$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:body.map((p,i)=>p.type==="thinking"?$jsx("box",{minHeight:1,width:"100%",flexShrink:0,children:$jsx("markdown",{content:p.content,fg:theme.markdownText,syntaxStyle})},p.key??`th-${i}`):$jsx("box",{width:"100%",flexShrink:0,children:$jsx(Tool,{branch:i===body.length-1?"last":"mid",tool:p,detail})},p.id||`t-${i}`))})}),$jsx("box",{position:"absolute",left:0,right:0,bottom:0,height:1,onMouseDown:grab,onMouseDrag:move,onMouseUp:drop,onMouseDragEnd:drop})]})});var import_react28=__toESM(require_react_production(),1);var import_react23=__toESM(require_react_production(),1);var def=(chord,desc,scope)=>({chord,desc,scope}),DEFAULTS2={leader:def("ctrl+x","Leader prefix","global"),"app.exit":def("ctrl+c","Quit","global"),"input.clear":def("ctrl+c","Clear input","global"),"app.suspend":def("ctrl+z","Suspend to shell","global"),"app.redraw":def("ctrl+l","Clear & force-repaint terminal","global"),"app.sidebar":def("<leader>b","Toggle sidebar","global"),"palette.open":def("ctrl+k","Command palette","global"),"help.open":def("f1","Keyboard shortcuts","global"),"tab.next":def("alt+right","Next tab","global"),"tab.prev":def("alt+left","Previous tab","global"),"focus.cycle":def("tab","Cycle focus (double-tap \u2192 composer)","global"),"editor.open":def("<leader>e,ctrl+g","Open $EDITOR on prompt","global"),"reply.copy":def("<leader>y,ctrl+y","Copy last assistant reply","global"),"clipboard.attach":def("ctrl+v","Attach clipboard image","global"),"queue.flush":def("<leader>u","Interrupt and send queued now","global"),"session.interrupt":def("escape","Interrupt (double-tap while streaming)","global"),"session.new":def("<leader>n","New session","global"),"session.redo":def("<leader>r","Redo last undo","global"),"session.compress":def("<leader>c","Compress context","global"),"session.steer":def("<leader>s","Steer active turn","global"),"input.stash":def("<leader>p","Stash prompt draft","global"),"session.timeline":def("<leader>g","Session timeline","global"),"theme.pick":def("<leader>t","Switch theme","global"),"model.pick":def("<leader>m","Switch model","global"),"status.open":def("<leader>i","Show status","global"),"list.up":def("up","Move selection up","list"),"list.down":def("down","Move selection down","list"),"list.pageUp":def("pageup","Page up","list"),"list.pageDown":def("pagedown","Page down","list"),"list.home":def("home","First item","list"),"list.end":def("end","Last item","list"),"list.activate":def("return","Activate / open","list"),"list.delete":def("d,delete","Delete item","list"),"list.refresh":def("r","Reload","list"),"list.new":def("n","Create","list"),"list.search":def("/","Filter","list"),"list.toggle":def("space","Toggle item","list"),"dialog.accept":def("return","Accept","dialog"),"dialog.cancel":def("escape","Cancel / close","dialog"),"dialog.confirm":def("y","Yes","dialog"),"dialog.deny":def("n","No","dialog"),"dialog.copy":def("c","Copy body","dialog"),"input.submit":def("return","Send","composer"),"input.newline":def("shift+return,ctrl+return,alt+return,ctrl+j","Insert newline","composer"),"sessions.rename":def("ctrl+r","Retitle session","sessions"),"sessions.prev":def("left","Previous source filter","sessions"),"sessions.next":def("right","Next source filter","sessions"),"agents.kill":def("k","Kill subagent","agents"),"agents.history":def("h","Spawn history","agents"),"agents.install":def("i","Install distribution","agents"),"config.save":def("ctrl+s","Write config","config"),"config.mode":def("m","Toggle form \u2194 YAML","config"),"eikon.save":def("ctrl+s","Save eikon","eikon")};var TAB_SCOPES=new Set(["sessions","cron","env","agents","skills","config","eikon"]);function scopesOverlap(a,b2){if(a===b2)return!0;if(a==="global"||b2==="global")return!0;if(a==="list")return TAB_SCOPES.has(b2);if(b2==="list")return TAB_SCOPES.has(a);return!1}var ALIAS={esc:"escape",enter:"return",del:"delete",ins:"insert",space:"space"," ":"space"};function parse2(spec2){if(!spec2||spec2==="none")return[];return spec2.split(",").map(one)}function one(combo){let c={name:"",ctrl:!1,meta:!1,shift:!1,super:!1,leader:!1};for(let raw of combo.replace(/<leader>/g,"leader+").toLowerCase().split("+")){let p=raw.trim();if(!p)continue;if(p==="ctrl")c.ctrl=!0;else if(p==="alt"||p==="meta"||p==="option")c.meta=!0;else if(p==="shift")c.shift=!0;else if(p==="super"||p==="cmd")c.super=!0;else if(p==="leader")c.leader=!0;else c.name=ALIAS[p]??p}return c}function from(key,leader=!1){return{name:key.name===" "?"space":key.name,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super??!1,leader}}function eq(a,b2){return a.name===b2.name&&a.ctrl===b2.ctrl&&a.meta===b2.meta&&a.shift===b2.shift&&a.super===b2.super&&a.leader===b2.leader}function match(list,key,leader=!1){if(list.length===0)return!1;let k2=from(key,leader);return list.some((c)=>eq(c,k2))}function print(list,lead2){let c=list[0];if(!c)return"";let mods=[];if(c.ctrl)mods.push("Ctrl");if(c.meta)mods.push("Alt");if(c.super)mods.push("Super");if(c.shift)mods.push("Shift");let name=LABEL[c.name]??cap2(c.name),body=[...mods,name].join("+");if(!c.leader)return body;return lead2?`${lead2} ${body}`:`<leader> ${body}`}var LABEL={return:"Enter",escape:"Esc",space:"Space",delete:"Del",backspace:"\u232B",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",pageup:"PgUp",pagedown:"PgDn",home:"Home",end:"End",tab:"Tab"};function cap2(s){return s.length===1?s.toUpperCase():s.charAt(0).toUpperCase()+s.slice(1)}function toBindings(list,action){return list.map((c)=>({name:c.name,ctrl:c.ctrl||void 0,meta:c.meta||void 0,shift:c.shift||void 0,super:c.super||void 0,action}))}function key(c){return`${c.leader?"L":""}${c.ctrl?"C":""}${c.meta?"M":""}${c.shift?"S":""}${c.super?"W":""}-${c.name}`}var LEADER_MS=2000,Ctx2=import_react23.createContext(null),NO_OVERRIDES=Object.freeze({}),KeysProvider=({children,overrides:fixedOverrides})=>{let renderer=useRenderer(),prefOverrides=usePref("keys"),overrides=fixedOverrides??prefOverrides??NO_OVERRIDES,table=import_react23.useMemo(()=>{let t2=new Map;for(let id of Object.keys(DEFAULTS2))t2.set(id,parse2(overrides[id]??DEFAULTS2[id].chord));return t2},[overrides]),lead2=table.get("leader"),leadLabel=print(lead2),armed=import_react23.useRef(!1),stolen=import_react23.useRef(null),timer2=import_react23.useRef(null),[,bump]=import_react23.useState(0),disarm=import_react23.useCallback(()=>{if(!armed.current)return;if(armed.current=!1,timer2.current)clearTimeout(timer2.current),timer2.current=null;let f=stolen.current;if(stolen.current=null,f&&!f.isDestroyed&&!renderer.currentFocusedRenderable)f.focus();bump((n)=>n+1)},[renderer]),arm=import_react23.useCallback(()=>{if(armed.current=!0,stolen.current=renderer.currentFocusedRenderable??null,stolen.current?.blur(),timer2.current)clearTimeout(timer2.current);timer2.current=setTimeout(disarm,LEADER_MS),bump((n)=>n+1)},[renderer,disarm]);useKeyboard((key2)=>{if(!armed.current&&match(lead2,key2)){arm(),key2.stopPropagation();return}if(armed.current)queueMicrotask(disarm)});let value=import_react23.useMemo(()=>({get leader(){return armed.current},match:(id,key2)=>match(table.get(id)??[],key2,armed.current),print:(id)=>print(table.get(id)??[],leadLabel),chord:(id)=>table.get(id)??[],all:(scope)=>Object.keys(DEFAULTS2).filter((id)=>DEFAULTS2[id].scope===scope).map((id)=>({id,desc:DEFAULTS2[id].desc,scope,chord:table.get(id)??[]})),table}),[table,leadLabel]);return $jsx(Ctx2.Provider,{value,children})},useKeys=makeUse(Ctx2,"useKeys");var import_react25=__toESM(require_react_production(),1);function handleListKey(keys,key2,o){let move=(next)=>{o.setSel((p)=>{let n=Math.max(0,Math.min(o.count-1,next(p)));return o.scrollTo?.(n),n})},pg=o.page??10;if(keys.match("list.up",key2))return move((p)=>p-1),!0;if(keys.match("list.down",key2))return move((p)=>p+1),!0;if(keys.match("list.pageUp",key2))return move((p)=>p-pg),!0;if(keys.match("list.pageDown",key2))return move((p)=>p+pg),!0;if(keys.match("list.home",key2))return move(()=>0),!0;if(keys.match("list.end",key2))return move(()=>o.count-1),!0;if(o.onActivate&&keys.match("list.activate",key2))return o.onActivate(),!0;if(o.onDelete&&keys.match("list.delete",key2))return o.onDelete(),!0;if(o.onRefresh&&keys.match("list.refresh",key2))return o.onRefresh(),!0;if(o.onNew&&keys.match("list.new",key2))return o.onNew(),!0;if(o.onToggle&&keys.match("list.toggle",key2))return o.onToggle(),!0;if(o.onSearch&&keys.match("list.search",key2))return o.onSearch(),!0;return!1}function useListKeys(o){let keys=useKeys();return useKeyboard((key2)=>{if(!(typeof o.active==="function"?o.active():o.active))return;if(handleListKey(keys,key2,o))return;o.also?.(key2,keys)}),keys}function useFollow(prefix,key2){let ref=import_react25.useRef(null),id=(i)=>`${prefix}-row-${key2?.(i)??i}`;return{ref,id,opts:{scrollTo:(n)=>ref.current?.scrollChildIntoView(id(n)),get page(){return Math.max(1,(ref.current?.viewport.height??10)-1)}}}}function conflicts(table){let buckets=new Map;for(let[id,chords]of table)for(let c of chords){let k2=key(c),b2=buckets.get(k2);if(b2)b2.push([id,c]);else buckets.set(k2,[[id,c]])}let out=[];for(let bucket of buckets.values()){if(bucket.length<2)continue;for(let i=0;i<bucket.length;i++)for(let j2=i+1;j2<bucket.length;j2++){let[a,c]=bucket[i],[b2]=bucket[j2];if(scopesOverlap(DEFAULTS2[a].scope,DEFAULTS2[b2].scope))out.push({chord:c,a,b:b2})}}return out}function conflictsWith(table,id){let mine=new Set((table.get(id)??[]).map(key));if(mine.size===0)return[];let scope=DEFAULTS2[id].scope,out=[];for(let[other,chords]of table){if(other===id)continue;if(!scopesOverlap(scope,DEFAULTS2[other].scope))continue;if(chords.some((c)=>mine.has(key(c))))out.push(other)}return out}var import_react27=__toESM(require_react_production(),1);var TabStrip=import_react27.memo(({tabs,active,onChange,hint})=>{let theme=useTheme().theme;return $jsxs("box",{width:"100%",flexDirection:"row",height:1,overflow:"hidden",children:[tabs.map((name,i)=>$jsx("box",{onMouseDown:()=>onChange(i),paddingX:2,marginRight:1,flexShrink:0,backgroundColor:i===active?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===active?theme.primary:theme.textMuted,children:$jsx("strong",{children:name})})},i)),$jsx("box",{flexGrow:1,minWidth:0}),hint?$jsx("box",{paddingX:1,flexShrink:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.borderSubtle,children:hint})}):null]})});var TabBar=import_react28.memo(({tabs,activeTab,onTabChange})=>{let keys=useKeys(),hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} or ${keys.print("leader")} N`;return $jsx(TabStrip,{tabs:tabs.map((t2)=>t2.name),active:activeTab,onChange:onTabChange,hint})});var import_react32=__toESM(require_react_production(),1);var import_react29=__toESM(require_react_production(),1);var default_default=`{"type":"header","asset":{"version":"2.0","minVersion":"2.0","width":48,"height":24,"mediaType":"application/vnd.eikon.stream+jsonl"},"name":"nous-girl"}
3689
+ `&&++n>=5)return 6;return n+1}var Inline=import_react21.memo(({branch,details,tool})=>{let s=spec(tool.name),body=tool.preview&&!isDiff(tool.preview)?short(tool.preview):"",label=s.verb&&body?`${s.verb} ${body}`:body||s.verb||tool.name;return $jsx(InlineTool,{branch,part:tool,complete:!!body||tool.status!=="running",details,children:label})});function visible(tool,mode){return mode!=="hidden"||tool.status==="running"}function details(tool,mode){let full=tool.verboseResult&&!isDiff(tool.verboseResult)?tool.verboseResult:void 0,sum=tool.result&&!isDiff(tool.result)?tool.result:void 0,err=tool.status==="error"&&(full||sum)?{label:"Error",text:cap(full??sum),tone:"error"}:void 0;if(mode!=="expanded")return err?[err]:[];let out=[];if(tool.verboseArgs)out.push({label:"Args",text:cap(tool.verboseArgs)});if(err)out.push(err);if(tool.verboseResult&&tool.status!=="error"&&!isDiff(tool.verboseResult))out.push({label:"Result",text:cap(tool.verboseResult)});return out}function cost(tool,mode){if(!visible(tool,mode))return 0;if(tool.trail)return 2+Math.min(tool.trail.length,TRAIL);if(tool.name==="delegate_task")return 2;return 1+details(tool,mode).reduce((n,d2)=>n+lines2(d2.text),0)}var Tool=import_react21.memo(({branch,tool,detail="expanded"})=>{let list=import_react21.useMemo(()=>details(tool,detail),[tool,detail]);if(!visible(tool,detail))return null;if(tool.trail||tool.name==="delegate_task")return $jsx(Subagent,{branch,tool});return $jsx(Inline,{branch,details:list,tool})});var CLOUD_MIN=12,CLOUD_MAX=24,CLOUD={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2504",vertical:"\u2506",topT:"\u2504",bottomT:"\u2504",leftT:"\u2506",rightT:"\u2506",cross:"\u253C"},SLOTS=[["\u256D\u2504\u2504\u256E ","\u2570\u2504\u2504\u256F "],[" \u256D\u256E "," \u2570\u256F "],[" \u2576 "," "]],BLANK=" ",ORDER=[2,1,0,-1],Tail=import_react22.memo((props)=>{let theme=useTheme().theme,refs=import_react22.useRef([]),paint=(lit)=>{SLOTS.forEach((slot,i)=>slot.forEach((l,j2)=>{let node=refs.current[i*2+j2];if(node)node.children=[lit===null||lit===i?l:BLANK]}))};return import_react22.useEffect(()=>{if(!props.run){paint(null);return}let f=0;paint(ORDER[0]);let t2=setInterval(()=>{f=(f+1)%ORDER.length,paint(ORDER[f])},160);return()=>{clearInterval(t2),paint(null)}},[props.run]),$jsx("box",{flexDirection:"column",children:SLOTS.flatMap((slot,i)=>slot.map((l,j2)=>$jsx("text",{fg:theme.hermAvatar,children:$jsx("span",{ref:(el)=>{refs.current[i*2+j2]=el},children:l})},`${i}-${j2}`)))})});function parts(m2){return m2?.parts.filter((p)=>p.type==="thinking"||p.type==="tool")??[]}function latest(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="assistant")return messages[i];return}function rows(list,detail){return list.reduce((n,p)=>n+(p.type==="thinking"?Math.ceil(p.content.length/80)||1:p.type==="tool"?cost(p,detail):1),0)}var ThoughtCloud=import_react22.memo((props)=>{let{theme,syntaxStyle}=useTheme(),detail=usePref("toolDetails")??"expanded",src=props.pick??latest(props.messages),all=parts(src),think=all.filter((p)=>p.type==="thinking"),seen=all.filter((p)=>p.type==="tool").filter((t2)=>visible(t2,detail)),[pane,setPane]=import_react22.useState("reasoning");import_react22.useEffect(()=>{if(pane==="reasoning"&&think.length===0&&seen.length>0)setPane("tools");if(pane==="tools"&&seen.length===0&&think.length>0)setPane("reasoning")},[pane,think.length,seen.length]);let body=pane==="reasoning"?think:seen,manual=import_react22.useRef(!1),want=Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,rows(body,detail)+3)),resize=props.onResize;import_react22.useEffect(()=>{if(!manual.current)resize(want)},[want,resize]);let drag=import_react22.useRef(null),grab=(e)=>{drag.current={y:e.y,h:props.height},manual.current=!0,e.stopPropagation()},move=(e)=>{let d2=drag.current;if(!d2)return;resize(Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,d2.h+(e.y-d2.y))))},drop=()=>{drag.current=null},pill=(id,label,n)=>{let on=pane===id;return $jsx("box",{height:1,marginRight:2,onMouseDown:(e)=>{e.stopPropagation(),setPane(id)},children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:on?$jsx("strong",{children:label}):label}),n!==null&&n>0?$jsx("span",{fg:theme.textMuted,children:` ${n}`}):null]})})};return $jsxs("box",{height:props.height,flexDirection:"column",position:"relative",marginLeft:1,border:!0,borderColor:theme.hermAvatar,customBorderChars:CLOUD,backgroundColor:theme.backgroundPanel,paddingX:1,children:[$jsxs("box",{height:1,flexShrink:0,flexDirection:"row",children:[pill("reasoning","reasoning",null),pill("tools","tools",seen.length),$jsx("box",{flexGrow:1}),detail!=="expanded"?$jsx("box",{marginRight:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u27E8",detail,"\u27E9"]})}):null,props.onClose?$jsx("box",{width:1,onMouseDown:props.onClose,children:$jsx("text",{fg:theme.textMuted,children:"\xD7"})}):null]}),$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:body.map((p,i)=>p.type==="thinking"?$jsx("box",{minHeight:1,width:"100%",flexShrink:0,children:$jsx("markdown",{content:p.content,fg:theme.markdownText,syntaxStyle})},p.key??`th-${i}`):$jsx("box",{width:"100%",flexShrink:0,children:$jsx(Tool,{branch:i===body.length-1?"last":"mid",tool:p,detail})},p.id||`t-${i}`))})}),$jsx("box",{position:"absolute",left:0,right:0,bottom:0,height:1,onMouseDown:grab,onMouseDrag:move,onMouseUp:drop,onMouseDragEnd:drop})]})});var import_react28=__toESM(require_react_production(),1);var import_react23=__toESM(require_react_production(),1);var def=(chord,desc,scope)=>({chord,desc,scope}),DEFAULTS2={leader:def("ctrl+x","Leader prefix","global"),"app.exit":def("ctrl+c","Quit","global"),"input.clear":def("ctrl+c","Clear input","global"),"app.suspend":def("ctrl+z","Suspend to shell","global"),"app.redraw":def("ctrl+l","Clear & force-repaint terminal","global"),"app.sidebar":def("<leader>b","Toggle sidebar","global"),"palette.open":def("ctrl+k","Command palette","global"),"help.open":def("f1","Keyboard shortcuts","global"),"tab.next":def("alt+right","Next tab","global"),"tab.prev":def("alt+left","Previous tab","global"),"focus.cycle":def("tab","Cycle focus (double-tap \u2192 composer)","global"),"editor.open":def("<leader>e,ctrl+g","Open $EDITOR on prompt","global"),"reply.copy":def("<leader>y,ctrl+y","Copy last assistant reply","global"),"clipboard.attach":def("ctrl+v","Attach clipboard image","global"),"queue.flush":def("<leader>u","Interrupt and send queued now","global"),"session.interrupt":def("escape","Interrupt (double-tap while streaming)","global"),"session.new":def("<leader>n","New session","global"),"session.redo":def("<leader>r","Redo last undo","global"),"session.compress":def("<leader>c","Compress context","global"),"session.steer":def("<leader>s","Steer active turn","global"),"input.stash":def("<leader>p","Stash prompt draft","global"),"session.timeline":def("<leader>g","Session timeline","global"),"theme.pick":def("<leader>t","Switch theme","global"),"model.pick":def("<leader>m","Switch model","global"),"status.open":def("<leader>i","Show status","global"),"list.up":def("up","Move selection up","list"),"list.down":def("down","Move selection down","list"),"list.pageUp":def("pageup","Page up","list"),"list.pageDown":def("pagedown","Page down","list"),"list.home":def("home","First item","list"),"list.end":def("end","Last item","list"),"list.activate":def("return","Activate / open","list"),"list.delete":def("d,delete","Delete item","list"),"list.refresh":def("r","Reload","list"),"list.new":def("n","Create","list"),"list.search":def("/","Filter","list"),"list.toggle":def("space","Toggle item","list"),"dialog.accept":def("return","Accept","dialog"),"dialog.cancel":def("escape","Cancel / close","dialog"),"dialog.confirm":def("y","Yes","dialog"),"dialog.deny":def("n","No","dialog"),"dialog.copy":def("c","Copy body","dialog"),"input.submit":def("return","Send","composer"),"input.newline":def("shift+return,ctrl+return,alt+return,ctrl+j","Insert newline","composer"),"sessions.rename":def("ctrl+r","Retitle session","sessions"),"sessions.prev":def("left","Previous source filter","sessions"),"sessions.next":def("right","Next source filter","sessions"),"sessions.sort":def("s","Toggle sort","sessions"),"agents.kill":def("k","Kill subagent","agents"),"agents.history":def("h","Spawn history","agents"),"agents.install":def("i","Install distribution","agents"),"config.save":def("ctrl+s","Write config","config"),"config.mode":def("m","Toggle form \u2194 YAML","config"),"eikon.save":def("ctrl+s","Save eikon","eikon")};var TAB_SCOPES=new Set(["sessions","cron","env","agents","skills","config","eikon"]);function scopesOverlap(a,b2){if(a===b2)return!0;if(a==="global"||b2==="global")return!0;if(a==="list")return TAB_SCOPES.has(b2);if(b2==="list")return TAB_SCOPES.has(a);return!1}var ALIAS={esc:"escape",enter:"return",del:"delete",ins:"insert",space:"space"," ":"space"};function parse2(spec2){if(!spec2||spec2==="none")return[];return spec2.split(",").map(one)}function one(combo){let c={name:"",ctrl:!1,meta:!1,shift:!1,super:!1,leader:!1};for(let raw of combo.replace(/<leader>/g,"leader+").toLowerCase().split("+")){let p=raw.trim();if(!p)continue;if(p==="ctrl")c.ctrl=!0;else if(p==="alt"||p==="meta"||p==="option")c.meta=!0;else if(p==="shift")c.shift=!0;else if(p==="super"||p==="cmd")c.super=!0;else if(p==="leader")c.leader=!0;else c.name=ALIAS[p]??p}return c}function from(key,leader=!1){return{name:key.name===" "?"space":key.name,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super??!1,leader}}function eq(a,b2){return a.name===b2.name&&a.ctrl===b2.ctrl&&a.meta===b2.meta&&a.shift===b2.shift&&a.super===b2.super&&a.leader===b2.leader}function match(list,key,leader=!1){if(list.length===0)return!1;let k2=from(key,leader);return list.some((c)=>eq(c,k2))}function print(list,lead2){let c=list[0];if(!c)return"";let mods=[];if(c.ctrl)mods.push("Ctrl");if(c.meta)mods.push("Alt");if(c.super)mods.push("Super");if(c.shift)mods.push("Shift");let name=LABEL[c.name]??cap2(c.name),body=[...mods,name].join("+");if(!c.leader)return body;return lead2?`${lead2} ${body}`:`<leader> ${body}`}var LABEL={return:"Enter",escape:"Esc",space:"Space",delete:"Del",backspace:"\u232B",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",pageup:"PgUp",pagedown:"PgDn",home:"Home",end:"End",tab:"Tab"};function cap2(s){return s.length===1?s.toUpperCase():s.charAt(0).toUpperCase()+s.slice(1)}function toBindings(list,action){return list.map((c)=>({name:c.name,ctrl:c.ctrl||void 0,meta:c.meta||void 0,shift:c.shift||void 0,super:c.super||void 0,action}))}function key(c){return`${c.leader?"L":""}${c.ctrl?"C":""}${c.meta?"M":""}${c.shift?"S":""}${c.super?"W":""}-${c.name}`}var LEADER_MS=2000,Ctx2=import_react23.createContext(null),NO_OVERRIDES=Object.freeze({}),KeysProvider=({children,overrides:fixedOverrides})=>{let renderer=useRenderer(),prefOverrides=usePref("keys"),overrides=fixedOverrides??prefOverrides??NO_OVERRIDES,table=import_react23.useMemo(()=>{let t2=new Map;for(let id of Object.keys(DEFAULTS2))t2.set(id,parse2(overrides[id]??DEFAULTS2[id].chord));return t2},[overrides]),lead2=table.get("leader"),leadLabel=print(lead2),armed=import_react23.useRef(!1),stolen=import_react23.useRef(null),timer2=import_react23.useRef(null),[,bump]=import_react23.useState(0),disarm=import_react23.useCallback(()=>{if(!armed.current)return;if(armed.current=!1,timer2.current)clearTimeout(timer2.current),timer2.current=null;let f=stolen.current;if(stolen.current=null,f&&!f.isDestroyed&&!renderer.currentFocusedRenderable)f.focus();bump((n)=>n+1)},[renderer]),arm=import_react23.useCallback(()=>{if(armed.current=!0,stolen.current=renderer.currentFocusedRenderable??null,stolen.current?.blur(),timer2.current)clearTimeout(timer2.current);timer2.current=setTimeout(disarm,LEADER_MS),bump((n)=>n+1)},[renderer,disarm]);useKeyboard((key2)=>{if(!armed.current&&match(lead2,key2)){arm(),key2.stopPropagation();return}if(armed.current)queueMicrotask(disarm)});let value=import_react23.useMemo(()=>({get leader(){return armed.current},match:(id,key2)=>match(table.get(id)??[],key2,armed.current),print:(id)=>print(table.get(id)??[],leadLabel),chord:(id)=>table.get(id)??[],all:(scope)=>Object.keys(DEFAULTS2).filter((id)=>DEFAULTS2[id].scope===scope).map((id)=>({id,desc:DEFAULTS2[id].desc,scope,chord:table.get(id)??[]})),table}),[table,leadLabel]);return $jsx(Ctx2.Provider,{value,children})},useKeys=makeUse(Ctx2,"useKeys");var import_react25=__toESM(require_react_production(),1);function handleListKey(keys,key2,o){let move=(next)=>{o.setSel((p)=>{let n=Math.max(0,Math.min(o.count-1,next(p)));return o.scrollTo?.(n),n})},pg=o.page??10;if(keys.match("list.up",key2))return move((p)=>p-1),!0;if(keys.match("list.down",key2))return move((p)=>p+1),!0;if(keys.match("list.pageUp",key2))return move((p)=>p-pg),!0;if(keys.match("list.pageDown",key2))return move((p)=>p+pg),!0;if(keys.match("list.home",key2))return move(()=>0),!0;if(keys.match("list.end",key2))return move(()=>o.count-1),!0;if(o.onActivate&&keys.match("list.activate",key2))return o.onActivate(),!0;if(o.onDelete&&keys.match("list.delete",key2))return o.onDelete(),!0;if(o.onRefresh&&keys.match("list.refresh",key2))return o.onRefresh(),!0;if(o.onNew&&keys.match("list.new",key2))return o.onNew(),!0;if(o.onToggle&&keys.match("list.toggle",key2))return o.onToggle(),!0;if(o.onSearch&&keys.match("list.search",key2))return o.onSearch(),!0;return!1}function useListKeys(o){let keys=useKeys();return useKeyboard((key2)=>{if(!(typeof o.active==="function"?o.active():o.active))return;if(handleListKey(keys,key2,o))return;o.also?.(key2,keys)}),keys}function useFollow(prefix,key2){let ref=import_react25.useRef(null),id=(i)=>`${prefix}-row-${key2?.(i)??i}`;return{ref,id,opts:{scrollTo:(n)=>ref.current?.scrollChildIntoView(id(n)),get page(){return Math.max(1,(ref.current?.viewport.height??10)-1)}}}}function conflicts(table){let buckets=new Map;for(let[id,chords]of table)for(let c of chords){let k2=key(c),b2=buckets.get(k2);if(b2)b2.push([id,c]);else buckets.set(k2,[[id,c]])}let out=[];for(let bucket of buckets.values()){if(bucket.length<2)continue;for(let i=0;i<bucket.length;i++)for(let j2=i+1;j2<bucket.length;j2++){let[a,c]=bucket[i],[b2]=bucket[j2];if(scopesOverlap(DEFAULTS2[a].scope,DEFAULTS2[b2].scope))out.push({chord:c,a,b:b2})}}return out}function conflictsWith(table,id){let mine=new Set((table.get(id)??[]).map(key));if(mine.size===0)return[];let scope=DEFAULTS2[id].scope,out=[];for(let[other,chords]of table){if(other===id)continue;if(!scopesOverlap(scope,DEFAULTS2[other].scope))continue;if(chords.some((c)=>mine.has(key(c))))out.push(other)}return out}var import_react27=__toESM(require_react_production(),1);var TabStrip=import_react27.memo(({tabs,active,onChange,hint})=>{let theme=useTheme().theme;return $jsxs("box",{width:"100%",flexDirection:"row",height:1,overflow:"hidden",children:[tabs.map((name,i)=>$jsx("box",{onMouseDown:()=>onChange(i),paddingX:2,marginRight:1,flexShrink:0,backgroundColor:i===active?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===active?theme.primary:theme.textMuted,children:$jsx("strong",{children:name})})},i)),$jsx("box",{flexGrow:1,minWidth:0}),hint?$jsx("box",{paddingX:1,flexShrink:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.borderSubtle,children:hint})}):null]})});var TabBar=import_react28.memo(({tabs,activeTab,onTabChange})=>{let keys=useKeys(),hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} or ${keys.print("leader")} N`;return $jsx(TabStrip,{tabs:tabs.map((t2)=>t2.name),active:activeTab,onChange:onTabChange,hint})});var import_react32=__toESM(require_react_production(),1);var import_react29=__toESM(require_react_production(),1);var default_default=`{"type":"header","asset":{"version":"2.0","minVersion":"2.0","width":48,"height":24,"mediaType":"application/vnd.eikon.stream+jsonl"},"name":"nous-girl"}
3687
3690
  {"type":"clip","name":"idle","fps":16,"frameCount":64,"loopFrom":0}
3688
3691
  {"type":"frame","clip":"idle","index":0,"rows":["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28C0\u28C0\u28E0\u28E4\u28E4\u28C0\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28C0\u28E4\u28E4\u28EC\u28E5\u28C4\u28C0\u2800\u2809\u2819\u283B\u28FF\u28FF\u28FF\u28FF\u28F7\u28F6\u28E4\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E4\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E6\u2840\u2800\u2808\u283B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28E4\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u287F\u28A6\u2840\u2800\u2808\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BF\u2857\u2804\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2870\u28FB\u28FF\u28FF\u28FF\u288F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2819\u280F\u2800\u2800\u28EE\u2873\u2800\u2800\u2808\u28BF\u28BF\u283B\u283F\u284F\u2801\u2801\u28F8\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u280C\u2808\u2809\u28BA\u283B\u2883\u280A\u2819\u281B\u28A0\u2840\u2880\u2819\u2801\u2801\u2800\u2858\u28F6\u28F7\u28FF\u28F7\u28FE\u2800\u2800\u2808\u28F6\u28C6\u28F3\u28F6\u28EE\u2894\u28FF\u28FF\u2846\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u287C\u28F4\u28B6\u28E4\u28F6\u28FE\u28FC\u28FF\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FE\u28F6\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2847\u28C0\u28E0\u28F8\u28FF\u28F7\u28FB\u28FF\u28FF\u28FF\u28FF\u28F7\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B0\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u285F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28AF\u28FF\u28DA\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FF\u28D7\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FF\u2858\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2827\u283B\u281F\u28FB\u281F\u2853\u2808\u281B\u281B\u281B\u281B\u281B\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F9\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u283B\u28FF\u287F\u28FF\u28FF\u28C9\u28C1\u2800\u2800\u2800\u2800\u2838\u28BB\u28FF\u2877\u28A6\u2844\u2800\u2800\u2800\u28B9\u28FF\u28FF\u28FF\u28FF\u289F\u28DB\u287B\u28FF\u28FF\u28FF\u28EF\u28FF\u28FF\u28FF\u28FF\u28FF\u2840\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2808\u2819\u280A\u28BB\u28CF\u28BF\u2807\u2800\u2800\u2800\u2800\u282C\u283F\u2825\u280A\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287C\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28F8\u28EF\u280A\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28BF\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u2847\u2820\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u28FF\u28FF\u28FF\u28FF\u2847\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28C7\u2830\u28C4\u28C4\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28FF\u28FF\u28FF\u28FF\u28FF\u2840\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B0\u28FF\u28FF\u2846\u2823\u2804\u2808\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u28FF\u28FF\u28FF\u283B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FC\u28FF\u28FF\u28B9\u28FF\u28C7\u2800\u2800\u2800\u2800","\u2800\u2800\u28A0\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u284F\u2888\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2804\u28FF\u28FF\u2840\u2800\u2800\u2800","\u2800\u2800\u28DF\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28E6\u28C0\u28C0\u28C0\u28C0\u28E0\u28C4\u2840\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u287E\u281F\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2801\u28F9\u28FF\u2847\u2810\u2844\u2800","\u2800\u2880\u28FF\u28E6\u28C0\u28E0\u28FC\u28FF\u28FF\u28FB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28C4\u2800\u28F8\u28FF\u28FF\u28EF\u2840\u28C0\u28FC\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2880\u28FF\u28FF\u2847\u2800\u28F7\u2800","\u2800\u2818\u28DC\u283F\u28FF\u28FF\u283F\u280B\u28F1\u28FF\u28FF\u28FB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u280B\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E3\u28FE\u28FF\u28FF\u2847\u28A0\u28FF\u2800","\u2800\u2800\u2819\u283F\u28F6\u28E4\u28F6\u28FE\u28FF\u28FF\u288B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u281B\u288B\u2860\u2886\u2800\u2819\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u28A0\u28FF\u280F\u2800","\u2800\u2800\u2800\u2800\u2800\u2809\u28AF\u28C9\u28C9\u28E1\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E7\u2840\u288B\u281D\u2803\u28C0\u28F4\u281F\u282B\u289B\u28ED\u287F\u281A\u280B\u2809\u2801\u2812\u282B\u28DD\u283B\u28FF\u28FF\u28FF\u289F\u28F5\u287F\u280B\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u281B\u283F\u283F\u281B\u2881\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E4\u2876\u281F\u2809\u2800\u2880\u28F4\u285F\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2833\u28DC\u28BF\u287F\u281F\u280B\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28E0\u28FE\u28FF\u28FF\u28FF\u28FF\u283F\u28FF\u28AF\u287E\u280B\u2800\u2800\u2880\u2854\u2800\u287E\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u282E\u2805\u2800\u2800\u2800\u2800\u2800\u2800"]}
3689
3692
  {"type":"frame","clip":"idle","index":1,"rows":["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E0\u28E0\u28C0\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E4\u28E4\u28E4\u28E5\u28E4\u28C0\u2800\u2809\u2809\u283B\u28BF\u28FF\u28FF\u28FF\u28F7\u28F6\u28E4\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28E4\u28F6\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F6\u28C4\u2800\u2800\u2819\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28E0\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28DF\u287F\u28B7\u2840\u2800\u2808\u28BB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E7\u2880\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u28EB\u287F\u28FF\u28FF\u289F\u28FE\u28FF\u285F\u28FF\u28FF\u28FF\u28FF\u28FF\u280E\u281F\u2800\u2800\u28B4\u287B\u2804\u2800\u2800\u28BB\u28FF\u283F\u28BF\u28FF\u2803\u2809\u28A0\u28E4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2814\u2804\u2800\u2819\u2833\u280B\u280E\u2809\u281A\u2881\u28C4\u28C0\u28B8\u2809\u2801\u2800\u2848\u28B6\u28FE\u28FF\u28F7\u28FE\u2840\u2800\u2800\u28B6\u28E6\u2874\u28E6\u28F6\u28C2\u28E6\u28BF\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u28F8\u28F5\u28E6\u28E7\u28F6\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28C7\u2880\u28C0\u2878\u28FF\u28FF\u28FB\u28FF\u28F7\u28BE\u28FF\u28FF\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28A0\u28F7\u28FF\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28CF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28CC\u28FF\u28F0\u28BF\u28FF\u28F7\u28BF\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FF\u285C\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u285F\u28FF\u28FF\u28FF\u28FF\u28FF\u2843\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2818\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u2807\u2819\u281B\u287B\u289F\u28CB\u2809\u281B\u281B\u281B\u281B\u281B\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F9\u28FF\u28FF\u28FF\u28FF\u28F7\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2819\u28BF\u28DF\u28BF\u28FF\u28C1\u28D0\u2800\u2800\u2800\u2800\u2818\u28BB\u28FF\u2877\u28A6\u2844\u2800\u2800\u2800\u28F8\u28FF\u28FF\u28FF\u28FF\u281F\u281B\u283B\u28FF\u28FF\u28FF\u28EF\u28FF\u28FF\u28FF\u28FF\u28FF\u2844\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u2803\u28B9\u28CF\u28BB\u2807\u2800\u2800\u2800\u2800\u2828\u283D\u2825\u280A\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F9\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28CF\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28BF\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FC\u2807\u2820\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u28FF\u28FF\u28FF\u28FF\u2847\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28C7\u2838\u28C4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28CF\u28FF\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B0\u28FF\u28FF\u2846\u282B\u2800\u2808\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28B9\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BB\u28FF\u2847\u2800\u2800\u2800\u2800","\u2800\u2800\u2860\u2800\u2800\u2800\u2800\u28F8\u28FF\u28FF\u28FF\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FC\u28FF\u28FF\u28FF\u2803\u2898\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2808\u28FF\u28FF\u2800\u2800\u2800\u2800","\u2800\u28A0\u28E7\u2800\u2800\u2800\u2880\u28FF\u28FF\u28FF\u28FF\u28FF\u28E6\u28C0\u28C0\u28C0\u28C0\u28E0\u28C4\u2840\u2800\u2800\u28FF\u28FF\u28FF\u28EF\u2876\u281F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2801\u28B9\u28FF\u2847\u28A0\u2800\u2800","\u2800\u2808\u28FF\u28F6\u28E4\u28E4\u28FE\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28C4\u2800\u28FF\u28FF\u28FF\u28CF\u2800\u28E0\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2880\u28FF\u28FF\u2847\u2800\u28E7\u2800","\u2800\u2818\u28CC\u287B\u283F\u283F\u281F\u288B\u28FC\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u281B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E3\u28FE\u28FF\u28FF\u2847\u28B0\u28FF\u2800","\u2800\u2800\u2818\u283B\u28F7\u28F6\u28FE\u28FF\u28FF\u287F\u28B3\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u281B\u288B\u2860\u2886\u2808\u283B\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u28A0\u28FF\u2807\u2800","\u2800\u2800\u2800\u2800\u2800\u2808\u28EF\u28C9\u28C1\u28F4\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E7\u2840\u288B\u281D\u2803\u28C0\u28F4\u281F\u283B\u289B\u28ED\u287F\u281A\u280B\u2809\u2801\u2812\u282B\u28D9\u283B\u28FF\u28FF\u28FF\u285F\u28F1\u28FF\u280B\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u281B\u281B\u281B\u280B\u28F0\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E4\u2876\u281F\u2809\u2800\u2880\u28F4\u281F\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2833\u28DC\u28BF\u28FF\u283F\u280B\u2801\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28F0\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u28FF\u28AF\u287E\u280B\u2800\u2800\u2880\u2854\u2880\u287E\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u283A\u2805\u2800\u2800\u2800\u2800\u2800\u2800"]}
@@ -4104,8 +4107,8 @@ tell application "System Events" to get value of property list item "CFBundleNam
4104
4107
  `).length,onCopy=()=>{copy2(props.code),toast.show({variant:"success",message:`Copied ${lines3} line${lines3===1?"":"s"}`})};return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsxs("box",{flexDirection:"row",height:1,backgroundColor:theme.backgroundElement,onMouseDown:onCopy,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:[$jsx("box",{flexGrow:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:props.lang||"text"})}),$jsx("box",{paddingRight:1,children:$jsx("text",{fg:hover?theme.accent:theme.textMuted,children:hover?"\u29C9 copy":`${lines3} ln`})})]}),$jsx("box",{paddingX:1,paddingY:ft?0:1,children:ft?$jsx("code",{content:props.code,filetype:ft,syntaxStyle,fg:theme.text,wrapMode:"none",streaming:props.streaming}):$jsx("text",{fg:theme.text,children:props.code})})]})});var import_react37=__toESM(require_react_production(),1);var PATH_KEY=/"(?:path|file_path|filename|target|file)"\s*:\s*"((?:\\.|[^"\\])*)"/,DIFF_HEAD_ARROW=/(?:^|\s)a\/+\S.*?\s*\u2192\s*b\/+(\S.+?)\s*$/m,DIFF_HEAD_NEW=/^\+\+\+ b?\/+(\S.*?)\s*$/m,DIFF_HEAD_OLD=/^--- a?\/+(\S.*?)\s*$/m;function pathFor(t2){let args=t2.args;if(args&&/^\s*\{/.test(args)){let m2=sanitize(args).match(PATH_KEY);if(m2)return m2[1]}let sources=[t2.diff,t2.preview].filter((s)=>!!s);for(let s of sources){let c=sanitize(s),m2=c.match(DIFF_HEAD_ARROW)||c.match(DIFF_HEAD_NEW)||c.match(DIFF_HEAD_OLD);if(m2)return m2[1]}return sanitize(t2.preview??t2.name)}var STRIPS=[/^\s*\u250A.*$/,/^\s*[+-]\d+\s*\/\s*[-+]\d+\s*$/,/^\s*\u2026/,/a\/+\S.*?\s*\u2192\s*b\/+\S/];function sanitizeDiff(s){return sanitize(s).split(`
4105
4108
  `).filter((l)=>!STRIPS.some((re2)=>re2.test(l))).join(`
4106
4109
  `)}var base=(p)=>p.split(/[\\/]/).filter(Boolean).pop()??p,parent=(p)=>{let parts2=p.split(/[\\/]/).filter(Boolean);return parts2.length>=2?parts2[parts2.length-2]:""},trunc2=(s,n)=>s.length<=n?s:"\u2026"+s.slice(-(n-1));function buildTabs(tools){let raw=tools.flatMap((t2)=>{let rawDiff=t2.diff??(isDiff(t2.result)?t2.result:void 0);if(!rawDiff)return[];return[{tool:t2,path:pathFor(t2),diff:sanitizeDiff(rawDiff)}]}),counts=new Map;return raw.forEach((r)=>counts.set(base(r.path),(counts.get(base(r.path))??0)+1)),raw.map(({tool,path:path7,diff})=>{let b2=base(path7),dup=(counts.get(b2)??0)>1&&parent(path7),label=trunc2(dup?`${parent(path7)}/${b2}`:b2,24),lines3=diff.split(`
4107
- `),add=lines3.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines3.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add,del}})}var DiffTabs=import_react37.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react37.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react37.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react38=__toESM(require_react_production(),1);var group="approval";function question(req){return(req.description||"Shell command").trim()}function subject(req){if(req.pattern_keys?.length)return req.pattern_keys.join("|");return req.command.trim()}function mkApproval(req){return{...req,group,question:question(req),subject:subject(req)}}function shouldRemember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);return cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject)}function remember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);if(cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject))return;set("neverPrompts",[...cur,{group:p.group,question:p.question,subject:p.subject}])}var MaskInput=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:props.value,onInput:props.input,onSubmit:props.submit,focused:!0,flexGrow:1,textColor:theme.backgroundElement,cursorColor:theme.accent,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{position:"absolute",left:2,top:0,height:1,children:$jsx("text",{fg:theme.text,bg:theme.backgroundElement,children:"\u2022".repeat(props.value.length)})})]})};function digit(name){let n=parseInt(name,10);return Number.isFinite(n)?n:null}var Frame=(p)=>{let theme=useTheme().theme;return $jsx("box",{flexDirection:"column",border:["left"],borderColor:p.tint,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,marginBottom:1,children:p.children})},Pill=(p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,paddingX:1,backgroundColor:p.on?theme.primary:void 0,onMouseDown:p.onPick,children:$jsxs("text",{children:[$jsxs("span",{fg:p.on?theme.background:theme.textMuted,children:[p.hot," "]}),$jsx("span",{fg:p.on?theme.background:theme.text,children:p.label})]})})},CHOICES=["once","session","never","deny"],LABELS={once:"Allow once",session:"Allow this session",never:"Never ask",deny:"Deny"},RESPOND={once:"once",session:"session",never:"always",deny:"deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),[steering,setSteering]=import_react38.useState(!1),[custom,setCustom]=import_react38.useState(""),[note,setNote]=import_react38.useState(""),done=import_react38.useRef(!1),prompt=mkApproval(p.req),send=(c)=>{if(done.current)return;if(done.current=!0,c==="never")remember(prompt);gw.request("approval.respond",{choice:RESPOND[c]}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text3)=>{let body=text3.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react38.useImperativeHandle(ref,()=>({masked:steering,feed:(key3)=>{if(steering){if(key3.name==="escape")return setSteering(!1),!0;return!1}if(key3.name==="s")return setSteering(!0),setNote(""),!0;if(key3.name==="left"||key3.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key3.name==="right"||key3.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key3.name==="return")return send(CHOICES[sel]),!0;if(key3.name==="escape")return send("deny"),!0;let n=digit(key3.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"}),$jsxs("text",{fg:theme.textMuted,children:["\xB7 ",prompt.question]})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["subject: ",prompt.subject]})}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react38.useState(0),[typing,setTyping]=import_react38.useState(choices.length===0),[custom,setCustom]=import_react38.useState(""),done=import_react38.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react38.useImperativeHandle(ref,()=>({masked:typing,feed:(key3)=>{if(typing){if(key3.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key3.name==="escape")return send(""),!0;if(key3.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key3.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key3.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key3.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react38.useState(""),done=import_react38.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react38.useImperativeHandle(ref,()=>({masked:!0,feed:(key3)=>{if(key3.name==="escape")return go(""),!0;return!1}}),[]),$jsx(Frame,{tint:theme.warning,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})}),$jsx("text",{fg:theme.text,children:p.note}),$jsx("box",{height:1}),$jsx(MaskInput,{value,input:setValue,submit:()=>go(value)}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync10,statSync as statSync5}from"fs";function parseChafaLine(line){let out=[],fg2=null,bg2=null,reverse2=!1,i=0,N2=line.length;while(i<N2){if(line.charCodeAt(i)===27&&line.charCodeAt(i+1)===91){let end=line.indexOf("m",i+2);if(end<0){i=N2;break}let params=line.slice(i+2,end).split(";").map((x2)=>parseInt(x2,10)||0),p=0;while(p<params.length){let n=params[p];if(n===0){fg2=null,bg2=null,reverse2=!1,p++;continue}if(n===7){reverse2=!0,p++;continue}if(n===27){reverse2=!1,p++;continue}if(n===38&&params[p+1]===2){fg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===48&&params[p+1]===2){bg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===39){fg2=null,p++;continue}if(n===49){bg2=null,p++;continue}p++}i=end+1;continue}let cp=line.codePointAt(i),ch=String.fromCodePoint(cp);i+=ch.length;let efg=reverse2?bg2:fg2,ebg=reverse2?fg2:bg2;out.push({ch,fg:efg,bg:ebg})}return out}function parseChafa(text3){return text3.split(`
4108
- `).filter((s)=>s.length>0).map(parseChafaLine)}function hex(c){if(!c)return;return`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`}var CHAFA_PATHS=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa","/home/linuxbrew/.linuxbrew/bin/chafa"],cachedBin=void 0;function chafaBin(){if(cachedBin!==void 0)return cachedBin;for(let p of CHAFA_PATHS)if(existsSync10(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync10(full)?full:null}var CACHE=new Map,CACHE_CAP=50;function cacheGet(k2){let v2=CACHE.get(k2);if(!v2)return;return CACHE.delete(k2),CACHE.set(k2,v2),v2}function cachePut(k2,v2){if(CACHE.size>=CACHE_CAP)CACHE.delete(CACHE.keys().next().value);CACHE.set(k2,v2)}function renderChafa(path7,width,height){let bin=chafaBin();if(!bin)return{err:"chafa not installed"};let full=resolveImage(path7);if(!full)return{err:`not found: ${path7}`};let mtime=0;try{mtime=statSync5(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key3=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key3);if(cached2)return{rows:cached2};let r=spawnSync(bin,[`--size=${width}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8",timeout:5000});if(r.error)return{err:r.error.message};if(r.status!==0)return{err:(r.stderr||`chafa exit ${r.status}`).trim()};let rows2=parseChafa(r.stdout);return cachePut(key3,rows2),{rows:rows2}}var basename8=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react39.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react39.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react39.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row3,i)=>$jsx("text",{children:row3.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,onMouseDown:(e)=>{e.stopPropagation(),openFile(path7)},children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.accent,children:"\u25C9 "}),$jsx("span",{fg:theme.text,children:basename8(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react40=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react40.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react40.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react40.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function mix(a,b2,n=0.5){return RGBA.fromValues(a.r+(b2.r-a.r)*n,a.g+(b2.g-a.g)*n,a.b+(b2.b-a.b)*n,a.a+(b2.a-a.a)*n)}function darken(c,n=0.95){return RGBA.fromValues(c.r*n,c.g*n,c.b*n,c.a)}function lighten(c,n=0.05){return RGBA.fromValues(c.r+(1-c.r)*n,c.g+(1-c.g)*n,c.b+(1-c.b)*n,c.a)}var TOP_RULE={topLeft:"\u2594",topRight:"\u2594",horizontal:"\u2594",bottomLeft:"",bottomRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},BOTTOM_RULE={bottomLeft:"\u2581",bottomRight:"\u2581",horizontal:"\u2581",topLeft:"",topRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""};function useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let ctx=useTheme(),theme=ctx.theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),fill=import_react41.useMemo(()=>ctx.mode==="dark"?mix(theme.background,theme.backgroundElement):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),edge=import_react41.useMemo(()=>ctx.mode==="dark"?darken(theme.background):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,border:["bottom"],customBorderChars:BOTTOM_RULE,borderColor:edge}),$jsx("box",{backgroundColor:hover?fill:theme.backgroundElement,paddingLeft:1,paddingRight:1,paddingY:1,flexDirection:"column",minHeight:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:message.parts.map((p,i)=>{let seg=segs[i];if(!seg)return null;let k2=p.key??i;return seg.map((s,j2)=>{if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang},`${k2}-c${j2}`);return $jsx("text",{fg:theme.text,wrapMode:"word",children:s.md},`${k2}-${j2}`)})})}),$jsx("box",{height:1,border:["top"],customBorderChars:TOP_RULE,borderColor:edge})]})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),rail2=import_react41.useMemo(()=>ctx.mode==="dark"?lighten(theme.background):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsxs("box",{flexDirection:"row",marginBottom:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:[$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]}),$jsxs("box",{width:3,flexShrink:0,flexDirection:"row",children:[$jsx("box",{width:2}),$jsx("box",{width:1,backgroundColor:hover?rail2:void 0})]})]})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant";return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsx("box",{flexDirection:"column",children:$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react62=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync11}from"fs";import{homedir as homedir4}from"os";import{join as join11}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join11(homedir4(),".hermes"),entry=()=>{let js=join11(import.meta.dirname,"db.worker.js");return new URL(existsSync11(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn2=()=>{if(state.w)return state.w;let w2=new Worker(entry());return w2.onmessage=(e)=>{let r=e.data;state.pending.get(r.id)?.(r),state.pending.delete(r.id)},w2.onerror=(ev)=>{let err=`io worker: ${ev.message}`;for(let res of state.pending.values())res({id:-1,ok:!1,err});state.pending.clear()},state.w=w2},call=(fn,args)=>{if(INLINE)return state.inline??=Promise.resolve().then(() => (init_fns(),exports_fns)).then((m2)=>m2.FNS),state.inline.then((f)=>f[fn](...args));return new Promise((resolve4,reject)=>{let id=++state.seq;state.pending.set(id,(r)=>r.ok?resolve4(r.v):reject(Error(r.err))),spawn2().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react45=__toESM(require_react_production(),1);var Ctx5=import_react45.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react45.useState([]),gate=import_react45.useRef(!1),gen=import_react45.useRef(0),prev=import_react45.useRef(null),refocus=import_react45.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react45.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react45.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react45.useCallback(()=>gate.current,[]),onError=import_react45.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key3)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key3))clear()});let value=import_react45.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react45.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react45.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,overflow:"hidden",flexDirection:"row",children:[$jsx("box",{flexShrink:0,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.titleRight?$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",justifyContent:"flex-end",children:props.titleRight}):null]}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react47=__toESM(require_react_production(),1);var HintBar=import_react47.memo((props)=>{let theme=useTheme().theme,text3=props.pairs?props.pairs.map((p)=>`[${p[0]}] ${p[1]}`).join(" ")+(props.suffix?` \xB7 ${props.suffix}`:""):props.raw??"";return $jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text3})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react48=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text3=p.children,box=import_react48.useRef(null),node=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react48.useState(!1);import_react48.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text3.length>w2),!animate){tn.scrollX=0;return}let id,period=text3.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text3.length<=cur){tn.scrollX=0;return}tn.scrollX=(tn.scrollX+1)%period},p.speed??180)},p.hold??600);return()=>{if(clearTimeout(hold),id)clearInterval(id);if(node.current)node.current.scrollX=0}},[animate,text3,p.speed,p.hold]);let body=wraps?text3+GAP+text3:text3;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,children:body})})})},GAP=" ";var import_react49=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react49.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var import_react50=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react50.memo((p)=>{let theme=useTheme().theme,color=p.color??theme.accent,text3=p.textColor??theme.text,bg2=p.state==="in"?color:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?color:theme.borderSubtle:p.selected?color:text3;return $jsx("box",{id:p.id,height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.onConfirm();if(keys.match("dialog.deny",key3))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="s")return props.onPick("save");if(key3.name==="d")return props.onPick("discard");if(key3.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react52=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react52.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost2=(c)=>c==null?"\u2014":`$${c.toFixed(2)}`,clock=(d2)=>d2.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:h12()}),stamp=(ts)=>{let d2=new Date(ts*1000);return d2.toDateString()===new Date().toDateString()?clock(d2):d2.toLocaleDateString(void 0,{month:"short",day:"numeric"})},rel=(ts)=>{let s=Math.floor(Date.now()/1000-ts);if(s<60)return"just now";if(s<3600)return`${Math.floor(s/60)}m ago`;if(s<86400)return`${Math.floor(s/3600)}h ago`;return`${Math.floor(s/86400)}d ago`},ago=(ts)=>abs()?stamp(ts):rel(ts),until=(ts)=>{if(abs())return ts<=Date.now()/1000?"due":stamp(ts);let s=Math.floor(ts-Date.now()/1000);if(s<=0)return"due";if(s<60)return`in ${s}s`;if(s<3600)return`in ${Math.floor(s/60)}m`;if(s<86400)return`in ${Math.floor(s/3600)}h`;return`in ${Math.floor(s/86400)}d`},when=(ts)=>{let d2=new Date(ts*1000);return`${d2.toLocaleDateString()} ${clock(d2)}`},span=(start,end)=>{let s=Math.round(end-start);if(s<0)return"\u2014";if(s>=3600)return`${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m`;if(s>=60)return`${Math.floor(s/60)}m`;return`${s}s`},dur2=(s)=>s>=3600?`${Math.floor(s/3600)}h${Math.floor(s%3600/60)}m`:s>=60?`${Math.floor(s/60)}m${Math.floor(s%60)}s`:`${Math.floor(s)}s`;var import_react53=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync13,statSync as statSync6}from"fs";import{dirname as dirname9,basename as basename9}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync,readSync,closeSync,readdirSync as readdirSync6,readFileSync as readFileSync8,existsSync as existsSync12}from"fs";import{homedir as homedir5}from"os";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,$YAMLError=errors.YAMLError,$YAMLParseError=errors.YAMLParseError,$YAMLWarning=errors.YAMLWarning,$Alias=Alias.Alias,$isAlias=identity.isAlias,$isCollection=identity.isCollection,$isDocument=identity.isDocument,$isMap=identity.isMap,$isNode=identity.isNode,$isPair=identity.isPair,$isScalar=identity.isScalar,$isSeq=identity.isSeq,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,$parse=publicApi.parse,$parseAllDocuments=publicApi.parseAllDocuments,$parseDocument=publicApi.parseDocument,$stringify=publicApi.stringify,$visit=visit.visit,$visitAsync=visit.visitAsync;init_sessions_db();var HOME3=process.env.HOME||homedir5(),home={path:process.env.HERMES_HOME||`${HOME3}/.hermes`},setHome2=(h2)=>{home.path=h2},hermesPath=(relative5)=>`${home.path}/${relative5}`,managedSystem=async()=>{let env2=(process.env.HERMES_MANAGED??"").trim();if(env2){let norm=env2.toLowerCase();if(norm==="1"||norm==="true"||norm==="yes"||norm==="on")return"NixOS";return{homebrew:"Homebrew",nix:"NixOS",nixos:"NixOS"}[norm]??env2}return await Bun.file(hermesPath(".managed")).exists()?"NixOS":null},makeSource=(relative5,label)=>({file:hermesPath(relative5),relative:relative5,label:label??relative5.split("/").pop()??relative5});function readSkillFrontmatter(source){try{let fd=openSync(source.file,"r"),buf=Buffer.alloc(2048),n=readSync(fd,buf,0,2048,0);closeSync(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
4110
+ `),add=lines3.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines3.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add,del}})}var DiffTabs=import_react37.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react37.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react37.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react38=__toESM(require_react_production(),1);var group="approval";function question(req){return(req.description||"Shell command").trim()}function subject(req){if(req.pattern_keys?.length)return req.pattern_keys.join("|");return req.command.trim()}function mkApproval(req){return{...req,group,question:question(req),subject:subject(req)}}function shouldRemember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);return cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject)}function remember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);if(cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject))return;set("neverPrompts",[...cur,{group:p.group,question:p.question,subject:p.subject}])}var MaskInput=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:props.value,onInput:props.input,onSubmit:props.submit,focused:!0,flexGrow:1,textColor:theme.backgroundElement,cursorColor:theme.accent,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{position:"absolute",left:2,top:0,height:1,children:$jsx("text",{fg:theme.text,bg:theme.backgroundElement,children:"\u2022".repeat(props.value.length)})})]})};function digit(name){let n=parseInt(name,10);return Number.isFinite(n)?n:null}var Frame=(p)=>{let theme=useTheme().theme;return $jsx("box",{flexDirection:"column",border:["left"],borderColor:p.tint,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,marginBottom:1,children:p.children})},Pill=(p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,paddingX:1,backgroundColor:p.on?theme.primary:void 0,onMouseDown:p.onPick,children:$jsxs("text",{children:[$jsxs("span",{fg:p.on?theme.background:theme.textMuted,children:[p.hot," "]}),$jsx("span",{fg:p.on?theme.background:theme.text,children:p.label})]})})},CHOICES=["once","session","never","deny"],LABELS={once:"Allow once",session:"Allow this session",never:"Never ask",deny:"Deny"},RESPOND={once:"once",session:"session",never:"always",deny:"deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),[steering,setSteering]=import_react38.useState(!1),[custom,setCustom]=import_react38.useState(""),[note,setNote]=import_react38.useState(""),done=import_react38.useRef(!1),prompt=mkApproval(p.req),send=(c)=>{if(done.current)return;if(done.current=!0,c==="never")remember(prompt);gw.request("approval.respond",{choice:RESPOND[c]}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text3)=>{let body=text3.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react38.useImperativeHandle(ref,()=>({masked:steering,feed:(key3)=>{if(steering){if(key3.name==="escape")return setSteering(!1),!0;return!1}if(key3.name==="s")return setSteering(!0),setNote(""),!0;if(key3.name==="left"||key3.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key3.name==="right"||key3.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key3.name==="return")return send(CHOICES[sel]),!0;if(key3.name==="escape")return send("deny"),!0;let n=digit(key3.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"}),$jsxs("text",{fg:theme.textMuted,children:["\xB7 ",prompt.question]})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["subject: ",prompt.subject]})}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react38.useState(0),[typing,setTyping]=import_react38.useState(choices.length===0),[custom,setCustom]=import_react38.useState(""),done=import_react38.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react38.useImperativeHandle(ref,()=>({masked:typing,feed:(key3)=>{if(typing){if(key3.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key3.name==="escape")return send(""),!0;if(key3.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key3.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key3.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key3.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react38.useState(""),done=import_react38.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react38.useImperativeHandle(ref,()=>({masked:!0,feed:(key3)=>{if(key3.name==="escape")return go(""),!0;return!1}}),[]),$jsx(Frame,{tint:theme.warning,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})}),$jsx("text",{fg:theme.text,children:p.note}),$jsx("box",{height:1}),$jsx(MaskInput,{value,input:setValue,submit:()=>go(value)}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})});function same(a,b2){return Boolean(a&&b2&&b2.toLowerCase().includes(a.toLowerCase()))}function cap3(s,n=160){return s.length<=n?s:s.slice(0,n-1)+"\u2026"}function question2(part){let a=part.answered?.question;if(a)return a;if(part.req.variant==="clarify")return part.req.question;if(part.req.variant==="approval")return mkApproval(part.req).question;if(part.req.variant==="sudo")return"Sudo required";return part.req.env_var?`Secret: ${part.req.env_var}`:"Secret required"}function outcome(part){let a=part.answered;if(part.variant==="clarify"){let q2=cap3(question2(part)),body=cap3(a.label);return same(q2,a.label)?{head:body}:{head:q2,body}}if(part.variant==="approval"){let q2=cap3(question2(part),96);return{head:a.label,body:q2}}if(part.variant==="sudo")return{head:`sudo ${a.label}`};return{head:`${part.req.env_var??"secret"} ${a.label}`}}var Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,text3=outcome(part);return $jsxs("box",{flexDirection:"row",paddingLeft:3,marginBottom:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:fg2,children:glyph})}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:text3.head}),text3.body?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:text3.body}):null]})]})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync10,statSync as statSync5}from"fs";function parseChafaLine(line){let out=[],fg2=null,bg2=null,reverse2=!1,i=0,N2=line.length;while(i<N2){if(line.charCodeAt(i)===27&&line.charCodeAt(i+1)===91){let end=line.indexOf("m",i+2);if(end<0){i=N2;break}let params=line.slice(i+2,end).split(";").map((x2)=>parseInt(x2,10)||0),p=0;while(p<params.length){let n=params[p];if(n===0){fg2=null,bg2=null,reverse2=!1,p++;continue}if(n===7){reverse2=!0,p++;continue}if(n===27){reverse2=!1,p++;continue}if(n===38&&params[p+1]===2){fg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===48&&params[p+1]===2){bg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===39){fg2=null,p++;continue}if(n===49){bg2=null,p++;continue}p++}i=end+1;continue}let cp=line.codePointAt(i),ch=String.fromCodePoint(cp);i+=ch.length;let efg=reverse2?bg2:fg2,ebg=reverse2?fg2:bg2;out.push({ch,fg:efg,bg:ebg})}return out}function parseChafa(text3){return text3.split(`
4111
+ `).filter((s)=>s.length>0).map(parseChafaLine)}function hex(c){if(!c)return;return`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`}var CHAFA_PATHS=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa","/home/linuxbrew/.linuxbrew/bin/chafa"],cachedBin=void 0;function chafaBin(){if(cachedBin!==void 0)return cachedBin;for(let p of CHAFA_PATHS)if(existsSync10(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync10(full)?full:null}var CACHE=new Map,CACHE_CAP=50;function cacheGet(k2){let v2=CACHE.get(k2);if(!v2)return;return CACHE.delete(k2),CACHE.set(k2,v2),v2}function cachePut(k2,v2){if(CACHE.size>=CACHE_CAP)CACHE.delete(CACHE.keys().next().value);CACHE.set(k2,v2)}function renderChafa(path7,width,height){let bin=chafaBin();if(!bin)return{err:"chafa not installed"};let full=resolveImage(path7);if(!full)return{err:`not found: ${path7}`};let mtime=0;try{mtime=statSync5(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key3=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key3);if(cached2)return{rows:cached2};let r=spawnSync(bin,[`--size=${width}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8",timeout:5000});if(r.error)return{err:r.error.message};if(r.status!==0)return{err:(r.stderr||`chafa exit ${r.status}`).trim()};let rows2=parseChafa(r.stdout);return cachePut(key3,rows2),{rows:rows2}}var basename8=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react39.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react39.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react39.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row3,i)=>$jsx("text",{children:row3.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,onMouseDown:(e)=>{e.stopPropagation(),openFile(path7)},children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.accent,children:"\u25C9 "}),$jsx("span",{fg:theme.text,children:basename8(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react40=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react40.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react40.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react40.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function mix(a,b2,n=0.5){return RGBA.fromValues(a.r+(b2.r-a.r)*n,a.g+(b2.g-a.g)*n,a.b+(b2.b-a.b)*n,a.a+(b2.a-a.a)*n)}function darken(c,n=0.95){return RGBA.fromValues(c.r*n,c.g*n,c.b*n,c.a)}function lighten(c,n=0.05){return RGBA.fromValues(c.r+(1-c.r)*n,c.g+(1-c.g)*n,c.b+(1-c.b)*n,c.a)}var TOP_RULE={topLeft:"\u2594",topRight:"\u2594",horizontal:"\u2594",bottomLeft:"",bottomRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},BOTTOM_RULE={bottomLeft:"\u2581",bottomRight:"\u2581",horizontal:"\u2581",topLeft:"",topRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""};function useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let ctx=useTheme(),theme=ctx.theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),fill=import_react41.useMemo(()=>ctx.mode==="dark"?mix(theme.background,theme.backgroundElement):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),edge=import_react41.useMemo(()=>ctx.mode==="dark"?darken(theme.background):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,border:["bottom"],customBorderChars:BOTTOM_RULE,borderColor:edge}),$jsx("box",{backgroundColor:hover?fill:theme.backgroundElement,paddingLeft:1,paddingRight:1,paddingY:1,flexDirection:"column",minHeight:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:message.parts.map((p,i)=>{let seg=segs[i];if(!seg)return null;let k2=p.key??i;return seg.map((s,j2)=>{if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang},`${k2}-c${j2}`);return $jsx("text",{fg:theme.text,wrapMode:"word",children:s.md},`${k2}-${j2}`)})})}),$jsx("box",{height:1,border:["top"],customBorderChars:TOP_RULE,borderColor:edge})]})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),rail2=import_react41.useMemo(()=>ctx.mode==="dark"?lighten(theme.background):darken(theme.backgroundElement),[ctx.mode,theme.background,theme.backgroundElement]),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsxs("box",{flexDirection:"row",marginBottom:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:[$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]}),$jsxs("box",{width:3,flexShrink:0,flexDirection:"row",children:[$jsx("box",{width:2}),$jsx("box",{width:1,backgroundColor:hover?rail2:void 0})]})]})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant";return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsx("box",{flexDirection:"column",children:$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react62=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync11}from"fs";import{homedir as homedir4}from"os";import{join as join11}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join11(homedir4(),".hermes"),entry=()=>{let js=join11(import.meta.dirname,"db.worker.js");return new URL(existsSync11(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn2=()=>{if(state.w)return state.w;let w2=new Worker(entry());return w2.onmessage=(e)=>{let r=e.data;state.pending.get(r.id)?.(r),state.pending.delete(r.id)},w2.onerror=(ev)=>{let err=`io worker: ${ev.message}`;for(let res of state.pending.values())res({id:-1,ok:!1,err});state.pending.clear()},state.w=w2},call=(fn,args)=>{if(INLINE)return state.inline??=Promise.resolve().then(() => (init_fns(),exports_fns)).then((m2)=>m2.FNS),state.inline.then((f)=>f[fn](...args));return new Promise((resolve4,reject)=>{let id=++state.seq;state.pending.set(id,(r)=>r.ok?resolve4(r.v):reject(Error(r.err))),spawn2().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react45=__toESM(require_react_production(),1);var Ctx5=import_react45.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react45.useState([]),gate=import_react45.useRef(!1),gen=import_react45.useRef(0),prev=import_react45.useRef(null),refocus=import_react45.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react45.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react45.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react45.useCallback(()=>gate.current,[]),onError=import_react45.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key3)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key3))clear()});let value=import_react45.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react45.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react45.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,overflow:"hidden",flexDirection:"row",children:[$jsx("box",{flexShrink:0,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.titleRight?$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",justifyContent:"flex-end",children:props.titleRight}):null]}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react47=__toESM(require_react_production(),1);var HintBar=import_react47.memo((props)=>{let theme=useTheme().theme,text3=props.pairs?props.pairs.map((p)=>`[${p[0]}] ${p[1]}`).join(" ")+(props.suffix?` \xB7 ${props.suffix}`:""):props.raw??"";return $jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text3})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react48=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text3=p.children,box=import_react48.useRef(null),node=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react48.useState(!1);import_react48.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text3.length>w2),!animate){tn.scrollX=0;return}let id,period=text3.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text3.length<=cur){tn.scrollX=0;return}tn.scrollX=(tn.scrollX+1)%period},p.speed??180)},p.hold??600);return()=>{if(clearTimeout(hold),id)clearInterval(id);if(node.current)node.current.scrollX=0}},[animate,text3,p.speed,p.hold]);let body=wraps?text3+GAP+text3:text3;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,attributes:p.underline?TextAttributes.UNDERLINE:TextAttributes.NONE,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,attributes:p.underline?TextAttributes.UNDERLINE:TextAttributes.NONE,children:body})})})},GAP=" ";var import_react49=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react49.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var import_react50=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react50.memo((p)=>{let theme=useTheme().theme,color=p.color??theme.accent,text3=p.textColor??theme.text,bg2=p.state==="in"?color:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?color:theme.borderSubtle:p.selected?color:text3;return $jsx("box",{id:p.id,height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.onConfirm();if(keys.match("dialog.deny",key3))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="s")return props.onPick("save");if(key3.name==="d")return props.onPick("discard");if(key3.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react52=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react52.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost2=(c)=>c==null?"\u2014":`$${c.toFixed(2)}`,clock=(d2)=>d2.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:h12()}),stamp=(ts)=>{let d2=new Date(ts*1000);return d2.toDateString()===new Date().toDateString()?clock(d2):d2.toLocaleDateString(void 0,{month:"short",day:"numeric"})},rel=(ts)=>{let s=Math.floor(Date.now()/1000-ts);if(s<60)return"just now";if(s<3600)return`${Math.floor(s/60)}m ago`;if(s<86400)return`${Math.floor(s/3600)}h ago`;return`${Math.floor(s/86400)}d ago`},ago=(ts)=>abs()?stamp(ts):rel(ts),until=(ts)=>{if(abs())return ts<=Date.now()/1000?"due":stamp(ts);let s=Math.floor(ts-Date.now()/1000);if(s<=0)return"due";if(s<60)return`in ${s}s`;if(s<3600)return`in ${Math.floor(s/60)}m`;if(s<86400)return`in ${Math.floor(s/3600)}h`;return`in ${Math.floor(s/86400)}d`},when=(ts)=>{let d2=new Date(ts*1000);return`${d2.toLocaleDateString()} ${clock(d2)}`},span=(start,end)=>{let s=Math.round(end-start);if(s<0)return"\u2014";if(s>=3600)return`${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m`;if(s>=60)return`${Math.floor(s/60)}m`;return`${s}s`},dur2=(s)=>s>=3600?`${Math.floor(s/3600)}h${Math.floor(s%3600/60)}m`:s>=60?`${Math.floor(s/60)}m${Math.floor(s%60)}s`:`${Math.floor(s)}s`;var import_react53=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync13,statSync as statSync6}from"fs";import{dirname as dirname9,basename as basename9}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync,readSync,closeSync,readdirSync as readdirSync6,readFileSync as readFileSync8,existsSync as existsSync12}from"fs";import{homedir as homedir5}from"os";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,$YAMLError=errors.YAMLError,$YAMLParseError=errors.YAMLParseError,$YAMLWarning=errors.YAMLWarning,$Alias=Alias.Alias,$isAlias=identity.isAlias,$isCollection=identity.isCollection,$isDocument=identity.isDocument,$isMap=identity.isMap,$isNode=identity.isNode,$isPair=identity.isPair,$isScalar=identity.isScalar,$isSeq=identity.isSeq,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,$parse=publicApi.parse,$parseAllDocuments=publicApi.parseAllDocuments,$parseDocument=publicApi.parseDocument,$stringify=publicApi.stringify,$visit=visit.visit,$visitAsync=visit.visitAsync;init_sessions_db();var HOME3=process.env.HOME||homedir5(),home={path:process.env.HERMES_HOME||`${HOME3}/.hermes`},setHome2=(h2)=>{home.path=h2},hermesPath=(relative5)=>`${home.path}/${relative5}`,managedSystem=async()=>{let env2=(process.env.HERMES_MANAGED??"").trim();if(env2){let norm=env2.toLowerCase();if(norm==="1"||norm==="true"||norm==="yes"||norm==="on")return"NixOS";return{homebrew:"Homebrew",nix:"NixOS",nixos:"NixOS"}[norm]??env2}return await Bun.file(hermesPath(".managed")).exists()?"NixOS":null},makeSource=(relative5,label)=>({file:hermesPath(relative5),relative:relative5,label:label??relative5.split("/").pop()??relative5});function readSkillFrontmatter(source){try{let fd=openSync(source.file,"r"),buf=Buffer.alloc(2048),n=readSync(fd,buf,0,2048,0);closeSync(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
4109
4112
  ---`,3);if(end<0)return{description:"",tags:[]};let fm=$parse(head.slice(3,end)),tags=Array.isArray(fm.tags)?fm.tags.map(String):[];return{description:String(fm.description??""),tags}}catch{return{description:"",tags:[]}}}async function readSkillUsage(){try{let f=Bun.file(hermesPath("skills/.usage.json"));if(!await f.exists())return{};let raw=await f.json(),out={};for(let[k2,v2]of Object.entries(raw??{}))out[k2]={use_count:Number(v2.use_count??0),view_count:Number(v2.view_count??0),patch_count:Number(v2.patch_count??0),last_used_at:v2.last_used_at??null,last_viewed_at:v2.last_viewed_at??null,last_patched_at:v2.last_patched_at??null,created_at:v2.created_at??null,archived_at:v2.archived_at??null,state:v2.state??"active",pinned:Boolean(v2.pinned)};return out}catch{return{}}}async function readCuratorState(){try{let f=Bun.file(hermesPath("skills/.curator_state"));if(!await f.exists())return null;let raw=await f.json();return{last_run_at:raw.last_run_at??null,last_run_duration_seconds:raw.last_run_duration_seconds??null,last_run_summary:raw.last_run_summary??null,paused:Boolean(raw.paused),run_count:Number(raw.run_count??0)}}catch{return null}}async function readLatestCuratorReport(){try{let base2=hermesPath("logs/curator"),entries2=readdirSync6(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory());if(entries2.length===0)return null;entries2.sort((a,b2)=>b2.name.localeCompare(a.name));let runId=entries2[0].name,rel2=`logs/curator/${runId}/REPORT.md`,source=makeSource(rel2),body=await Bun.file(source.file).text();return{source,content:body.trim(),runId}}catch{return null}}function listCuratorRuns(){try{let base2=hermesPath("logs/curator");return readdirSync6(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory()).sort((a,b2)=>b2.name.localeCompare(a.name)).flatMap((e)=>{try{let fd=openSync(`${base2}/${e.name}/run.json`,"r"),buf=Buffer.alloc(8192),n=readSync(fd,buf);closeSync(fd);let j2=JSON.parse(buf.toString("utf8",0,n)),c=j2.counts??{};return[{id:e.name,at:Date.parse(j2.started_at??"")/1000||0,archived:c.archived_this_run??0,consolidated:c.consolidated_this_run??0,added:c.added_this_run??0,before:c.before??0,after:c.after??0}]}catch{return[]}})}catch{return[]}}async function readCuratorReport(id){try{return(await Bun.file(hermesPath(`logs/curator/${id}/REPORT.md`)).text()).trim()}catch{return""}}function indexCuratorLineage(){let out=new Map,push2=(name,ev)=>{let a=out.get(name)??[];a.push(ev),out.set(name,a)};try{let base2=hermesPath("logs/curator");for(let e of readdirSync6(base2,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let j2=JSON.parse(readFileSync8(`${base2}/${e.name}/run.json`,"utf8")),at=Date.parse(j2.started_at??"")/1000||0,run=e.name,into=new Map;for(let c of j2.consolidated??[])push2(c.name,{kind:"merged",run,at,into:c.into,reason:c.reason}),into.set(c.into,[...into.get(c.into)??[],c.name]);for(let[tgt,srcs]of into)push2(tgt,{kind:"absorbed",run,at,sources:srcs});for(let t2 of j2.state_transitions??[])push2(t2.name,{kind:"transition",run,at,from:t2.from,to:t2.to});for(let p of j2.pruned??[])push2(p.name,{kind:"pruned",run,at,reason:p.reason});for(let n of j2.added??[])push2(n,{kind:"added",run,at})}catch{}}}catch{}for(let a of out.values())a.sort((x2,y2)=>y2.at-x2.at);return out}function readChangelog(){try{let source=makeSource("herm/changelog.md"),fd=openSync(source.file,"r"),buf=Buffer.alloc(4096),n=readSync(fd,buf);closeSync(fd);let body=buf.toString("utf8",0,n).trim(),line=body.split(`
4110
4113
  `).find((l)=>/^[-*\u00B7]/.test(l.trim()));return{source,headline:line?.replace(/^[-*\u00B7]\s*/,"").trim()??"",body}}catch{return null}}async function readConfig(){try{let text3=await Bun.file(hermesPath("config.yaml")).text(),raw=$parse(text3);return{source:makeSource("config.yaml","config.yaml"),model:{default:raw?.model?.default??"unknown",provider:raw?.model?.provider??"auto",base_url:raw?.model?.base_url??"",context_length:raw?.model?.context_length},agent:{max_turns:raw?.agent?.max_turns??60,reasoning_effort:raw?.agent?.reasoning_effort??"medium"},compression:{enabled:raw?.compression?.enabled??!0,threshold:raw?.compression?.threshold??0.5,target_ratio:raw?.compression?.target_ratio??0.2,protect_last_n:raw?.compression?.protect_last_n??20,summary_model:raw?.compression?.summary_model??""},memory:{memory_enabled:raw?.memory?.memory_enabled??!0,user_profile_enabled:raw?.memory?.user_profile_enabled??!0,memory_char_limit:raw?.memory?.memory_char_limit??2200,user_char_limit:raw?.memory?.user_char_limit??1375,provider:raw?.memory?.provider??"",nudge_interval:raw?.memory?.nudge_interval??10,flush_min_turns:raw?.memory?.flush_min_turns??6},display:{personality:raw?.display?.personality??"default",skin:raw?.display?.skin??"default",show_cost:raw?.display?.show_cost??!1},curator:{enabled:raw?.curator?.enabled??!0,interval_hours:raw?.curator?.interval_hours??168,stale_after_days:raw?.curator?.stale_after_days??30,archive_after_days:raw?.curator?.archive_after_days??90},approvals:{destructive_slash_confirm:raw?.approvals?.destructive_slash_confirm??!0},gateway:{platforms:{api_server:raw?.gateway?.platforms?.api_server??void 0}}}}catch{return null}}async function readMemoryFile(filename,charLimit){try{let relative5=`memories/${filename}`,content=await Bun.file(hermesPath(relative5)).text(),entryCount=content.split("\xA7").filter((s)=>s.trim()).length;return{source:makeSource(relative5,filename),content,charCount:content.length,charLimit,usagePercent:charLimit>0?Math.round(content.length/charLimit*100):0,entryCount}}catch{return null}}async function readLiveSessions(){try{let file=Bun.file(hermesPath("sessions/sessions.json"));if(!await file.exists())return{};let text3=await file.text();return JSON.parse(text3)}catch{return{}}}var MEMORY_CFG_FILES={mem0:["mem0.json"],honcho:["honcho.json"],hindsight:["hindsight/config.json"],supermemory:["supermemory.json"],holographic:["holographic.db"]};function discoverMemoryProviders(){let names=new Set(["builtin"]);try{for(let e of readdirSync6(hermesPath("hermes-agent/plugins/memory"),{withFileTypes:!0}))if(e.isDirectory()&&!e.name.startsWith("_"))names.add(e.name)}catch{}return[...names]}async function readMemoryProviders(activeProvider){let out=[];for(let name of discoverMemoryProviders()){if(name==="builtin"){out.push({name,active:!0,config:{}});continue}let cfg={};for(let f of MEMORY_CFG_FILES[name]??[])try{let file=Bun.file(hermesPath(f));if(f.endsWith(".json")){let raw=await file.json();for(let[k2,v2]of Object.entries(raw))if(typeof v2==="string"||typeof v2==="number"||typeof v2==="boolean"){let lower=k2.toLowerCase();if(lower.includes("key")||lower.includes("token")||lower.includes("secret"))cfg[k2]=typeof v2==="string"?`${v2.slice(0,4)}...`:v2;else cfg[k2]=v2}}else{let st=await file.stat();if(st)cfg.db_size=`${Math.round(st.size/1024)}KB`}}catch{}out.push({name,active:name===activeProvider,config:cfg})}return out}async function readSoul(){try{let text3=await Bun.file(hermesPath("SOUL.md")).text();return{source:makeSource("SOUL.md"),charCount:text3.length,tokenEstimate:count2(text3),content:text3}}catch{return null}}async function readToolsFromLatestSession(){try{let dir=hermesPath("sessions");if(!existsSync12(dir))return null;let glob=new Bun.Glob("session_*.json"),latestPath="",latestTime=0;for await(let path7 of glob.scan({cwd:dir})){let stat2=await Bun.file(hermesPath(`sessions/${path7}`)).stat();if(stat2&&stat2.mtimeMs>latestTime)latestTime=stat2.mtimeMs,latestPath=path7}if(!latestPath)return null;let relative5=`sessions/${latestPath}`,tools=((await Bun.file(hermesPath(relative5)).json()).tools||[]).map((t2)=>({name:t2?.function?.name??"unknown",descriptionLength:(t2?.function?.description??"").length,paramsLength:JSON.stringify(t2?.function?.parameters??{}).length}));return{source:makeSource(relative5,latestPath),tools}}catch{return null}}async function readCronOutput(jobId,tailLines=40){let dir=hermesPath(`cron/output/${jobId}`),entries2;try{entries2=await readdir2(dir)}catch{return null}let md=entries2.filter((f)=>f.endsWith(".md")).sort().reverse();if(md.length===0)return null;let path7=`${dir}/${md[0]}`,full=await Bun.file(path7).text(),lines3=full.trimEnd().split(`
4111
4114
  `),text3=lines3.length>tailLines?`\u2026(${lines3.length-tailLines} earlier lines)
@@ -4115,11 +4118,11 @@ tell application "System Events" to get value of property list item "CFBundleNam
4115
4118
  `),found=!1,updated=lines3.map((line)=>{if(line.startsWith(`${key3}=`))return found=!0,`${key3}=${value}`;return line});if(!found)updated.push(`${key3}=${value}`);await Bun.write(ENV_PATH,updated.join(`
4116
4119
  `))}async function removeEnvVar(key3){let text3="";try{text3=await Bun.file(ENV_PATH).text()}catch{return}let lines3=text3.split(`
4117
4120
  `).filter((l)=>!l.startsWith(`${key3}=`));await Bun.write(ENV_PATH,lines3.join(`
4118
- `))}var ENV_CATALOG=[{category:"LLM Providers",keys:["ANTHROPIC_API_KEY","OPENAI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","MISTRAL_API_KEY","XAI_API_KEY","TOGETHER_API_KEY","FIREWORKS_API_KEY","NOUS_API_KEY"]},{category:"Tool API Keys",keys:["FIRECRAWL_API_KEY","BROWSERBASE_API_KEY","BROWSERBASE_PROJECT_ID","TAVILY_API_KEY","EXA_API_KEY","ELEVENLABS_API_KEY"]},{category:"Messaging",keys:["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN","SLACK_BOT_TOKEN","SLACK_APP_TOKEN"]},{category:"Agent",keys:["API_SERVER_KEY","MEM0_API_KEY"]}];var SLICES={config:{read:()=>readConfig(),watch:()=>[hermesPath("config.yaml")]},memory:{read:(d2)=>readMemoryFile("MEMORY.md",d2.config?.memory?.memory_char_limit??2200),deps:["config"],watch:()=>[hermesPath("memories/MEMORY.md")]},userProfile:{read:(d2)=>readMemoryFile("USER.md",d2.config?.memory?.user_char_limit??1375),deps:["config"],watch:()=>[hermesPath("memories/USER.md")]},memoryProviders:{read:(d2)=>readMemoryProviders(d2.config?.memory?.provider??""),deps:["config"]},memoryActivity:{read:()=>io.memoryActivity()},env:{read:()=>readEnvFile(),watch:()=>[hermesPath(".env")]},soul:{read:()=>readSoul(),watch:()=>[hermesPath("SOUL.md")]},liveSessions:{read:()=>readLiveSessions(),watch:()=>[hermesPath("sessions/sessions.json")]},recentSessions:{read:()=>io.roots(30)},systemPrompt:{read:()=>io.systemPrompt().then((r)=>r&&{source:makeSource("state.db"),sessionId:r.id,text:r.text,totalChars:r.text.length,tokenEstimate:count2(r.text)}).catch(()=>null)},toolsInfo:{read:()=>readToolsFromLatestSession(),watch:()=>[hermesPath("sessions")]},skillUsage:{read:()=>readSkillUsage(),watch:()=>[hermesPath("skills/.usage.json")]},curatorState:{read:()=>readCuratorState(),watch:()=>[hermesPath("skills/.curator_state")]}},DEPENDENTS=(()=>{let m2=new Map;for(let[k2,s]of Object.entries(SLICES))for(let d2 of s.deps??[]){let arr=m2.get(d2)??[];arr.push(k2),m2.set(d2,arr)}return m2})(),DEBOUNCE_MS=50;class HomeStore{data={};subs=new Map;inflight=new Map;watchers=new Map;debounce=new Map;get(k2){return this.data[k2]}subscribe(k2,cb){let set2=this.subs.get(k2);if(!set2)this.subs.set(k2,set2=new Set);return set2.add(cb),()=>set2.delete(cb)}ensure(k2){if(k2 in this.data)return Promise.resolve(this.data[k2]);let hit=this.inflight.get(k2);if(hit)return hit;let slice=SLICES[k2],p=(async()=>{let deps={};for(let d2 of slice.deps??[])deps[d2]=await this.ensure(d2);let v2=await slice.read(deps);return this.data[k2]=v2,this.startWatch(k2,slice.watch),this.notify(k2),v2})().finally(()=>this.inflight.delete(k2));return this.inflight.set(k2,p),p}invalidate(k2){if(!(k2 in this.data)&&!this.inflight.has(k2))return;if(delete this.data[k2],this.subs.get(k2)?.size)this.ensure(k2);for(let dep of DEPENDENTS.get(k2)??[])this.invalidate(dep)}close(){for(let ws of this.watchers.values())for(let w2 of ws)w2.close();for(let t2 of this.debounce.values())clearTimeout(t2);this.watchers.clear(),this.debounce.clear(),this.subs.clear(),this.inflight.clear(),this.data={}}reset(){for(let ws of this.watchers.values())for(let w2 of ws)w2.close();for(let t2 of this.debounce.values())clearTimeout(t2);this.watchers.clear(),this.debounce.clear(),this.inflight.clear(),this.data={};for(let k2 of this.subs.keys())if(this.subs.get(k2)?.size)this.ensure(k2)}notify(k2){let set2=this.subs.get(k2);if(set2)for(let cb of set2)cb()}startWatch(k2,watchFn){if(!watchFn||this.watchers.has(k2))return;let paths=watchFn(),ws=[],fire=()=>{let prev=this.debounce.get(k2);if(prev)clearTimeout(prev);this.debounce.set(k2,setTimeout(()=>this.invalidate(k2),DEBOUNCE_MS))};for(let p of paths){let dir=dirname9(p),name=basename9(p);try{if(existsSync13(p)&&statSync6(p).isDirectory())dir=p,name=null}catch{}if(!existsSync13(dir))continue;try{ws.push(watch2(dir,{persistent:!1},(_ev,f)=>{if(name===null||f===name)fire()}))}catch{}}this.watchers.set(k2,ws)}}var home2=new HomeStore;function useHome(k2){let v2=import_react53.useSyncExternalStore((cb)=>home2.subscribe(k2,cb),()=>home2.get(k2));return import_react53.useEffect(()=>{home2.ensure(k2)},[k2]),v2}var cmp=(s)=>{let k2=(r)=>s==="started"?r.started_at:r.detail?.last_active??r.started_at;return(a,b2)=>k2(b2)-k2(a)},WORD={api:"API",cli:"CLI",tui:"TUI",whatsapp:"WhatsApp"},badge=(s)=>s.split(/[_-]+/).filter(Boolean).map((w2)=>WORD[w2.toLowerCase()]??(w2[0]?.toUpperCase()??"")+w2.slice(1)).join(" ")||"\u2014",label=(r)=>r.title.trim()||(r.live?"-":"Untitled"),src=(r)=>r.detail?.sessionSource||r.source||"",HOME4="conversations",HBAR={visible:!1},ROW={flexDirection:"row"},sid=(s)=>`source:${s}`,chip=(id)=>`sessions-source-${id.replace(/[^a-z0-9_-]/gi,"_")}`,tick2=(r)=>r.detail?.last_active??r.started_at,FilterRow=import_react54.memo((p)=>{let theme=useTheme().theme,ref=import_react54.useRef(null);return import_react54.useEffect(()=>{let move=()=>{let node=ref.current,idx=p.views.findIndex((v2)=>v2.id===p.view);if(!node||idx<0)return;let left=p.views.slice(0,idx).reduce((n,v2,i)=>n+(i===0?0:1)+`${v2.label} ${v2.count}`.length+2,0),w2=`${p.views[idx].label} ${p.views[idx].count}`.length+2,port2=Math.max(1,node.viewport.width-4),pos=node.scrollLeft;node.scrollLeft=Math.max(0,left<pos?left:left+w2>pos+port2?left+w2-port2:pos)};move();let id=setTimeout(move,0);return()=>clearTimeout(id)},[p.view,p.views]),$jsx("scrollbox",{ref,scrollX:!0,height:1,paddingLeft:2,horizontalScrollbarOptions:HBAR,contentOptions:ROW,children:p.views.map((v2,i)=>$jsx(FilterChip,{id:chip(v2.id),label:`${v2.label} ${v2.count}`,state:p.view===v2.id?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.primary,onMouseDown:()=>p.setView(v2.id)},v2.id))})}),line=(s)=>(s??"").replace(/\s+/g," ").trim(),fold=(msgs)=>{let turns=[],tools=0;for(let m2 of msgs){if(m2.role==="tool"){tools++;continue}if(m2.role!=="user"&&m2.role!=="assistant")continue;let text3=line(m2.content);if(!text3)continue;turns.push({role:m2.role,text:text3})}return{turns,tools}},PeekRow=import_react54.memo((props)=>{let theme=useTheme().theme,[hot,setHot]=import_react54.useState(!1),left=props.row.role==="user",color=left?theme.primary:theme.accent,fg2=left?theme.text:theme.markdownText,bar=(side)=>$jsx("box",{width:2,flexShrink:0,height:1,border:[side],borderColor:color,customBorderChars:SIDE_PIPE});return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:hot?theme.backgroundElement:void 0,onMouseOver:()=>setHot(!0),onMouseOut:()=>setHot(!1),children:[left?bar("left"):null,$jsx(Ticker,{active:hot,speed:35,hold:150,fg:fg2,children:inline(props.row.text).map((s,i)=>s.c?$jsx("span",{fg:theme.warning,children:s.t},i):s.b?$jsx("span",{fg:fg2,children:$jsx("strong",{children:s.t})},i):s.i?$jsx("span",{fg:fg2,children:$jsx("u",{children:s.t})},i):$jsx("span",{fg:fg2,children:s.t},i))}),left?null:bar("right")]})}),Peek=import_react54.memo((props)=>{let theme=useTheme().theme,[data2,setData]=import_react54.useState(null),sb=import_react54.useRef(null);if(import_react54.useEffect(()=>{Promise.resolve(props.peek(props.sid,60)).then((m2)=>setData(fold(m2)))},[props.sid,props.peek]),import_react54.useEffect(()=>{if(data2&&sb.current)sb.current.scrollTop=sb.current.scrollHeight},[data2]),data2===null)return null;if(data2.turns.length===0&&data2.tools===0)return $jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local transcript)"})});let more=Math.max(0,props.total-60);return $jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:5,border:!0,borderStyle:"single",borderColor:theme.border,title:` Transcript${more>0?` \xB7 ${more} earlier`:""} `,titleAlignment:"left",children:[$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,minHeight:3,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.turns.map((r,i)=>$jsx(PeekRow,{row:r},i))})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${data2.turns.length} turn${data2.turns.length===1?"":"s"} \xB7 ${data2.tools} tool call${data2.tools===1?"":"s"}`})})]})}),Detail=import_react54.memo((props)=>{let theme=useTheme().theme,r=props.row,d2=r.detail,lastActive=d2?.last_active??d2?.ended_at??null,subs2=d2?.subagent_count??0,[info,setInfo]=import_react54.useState({});import_react54.useEffect(()=>{Promise.resolve(props.lineage(r.id)).then(setInfo)},[r.id,props.lineage]);let hasLineage=info.continuesFrom||info.compressedTo||subs2>0,go=(sid2)=>()=>props.onSwitch?.(sid2);return $jsx(TabShell,{title:"Session Detail",grow:2,children:$jsxs("box",{flexDirection:"column",width:"100%",flexGrow:1,overflow:"hidden",children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:label(r)})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["ID",r.id],["Source",badge(src(r))],["Model",d2?.model??"\u2014"],["Started",when(r.started_at)],["Last active",lastActive?`${when(lastActive)} (${ago(lastActive)})`:"\u2014"],["Duration",lastActive?span(r.started_at,lastActive):"\u2014"],["Ended",d2?.ended_at?`${when(d2.ended_at)} \xB7 ${d2.end_reason??"\u2014"}`:void 0]]}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Messages",String(r.message_count)],["Tool calls",d2?String(d2.tool_call_count):void 0],["Input",d2?`${fmt(d2.input_tokens)} tok`:void 0],["Output",d2?`${fmt(d2.output_tokens)} tok`:void 0],["Cache",d2?`${fmt(d2.cache_read_tokens)} r / ${fmt(d2.cache_write_tokens)} w`:void 0],["Reasoning",d2?`${fmt(d2.reasoning_tokens)} tok`:void 0],["Cost",d2?cost2(d2.estimated_cost_usd):void 0,theme.success]]}),hasLineage?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,children:"Lineage"})}),info.continuesFrom?$jsx("box",{height:1,onMouseDown:go(info.continuesFrom.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2190 continues from "}),$jsx("span",{fg:theme.accent,children:info.continuesFrom.title||info.continuesFrom.id})]})}):null,info.compressedTo?$jsx("box",{height:1,onMouseDown:go(info.compressedTo.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2192 compressed to "}),$jsx("span",{fg:theme.accent,children:info.compressedTo.title||info.compressedTo.id})]})}):null,subs2>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2387 spawned "}),$jsx("span",{fg:theme.text,children:String(subs2)}),$jsx("span",{fg:theme.textMuted,children:` subagent${subs2===1?"":"s"}`})]})}):null]}):null,!d2?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local detail \u2014 state.db mismatch)"})})]}):null,$jsx("box",{height:1})]}),$jsx(Peek,{sid:r.id,total:r.message_count,peek:props.peek})]})})}),SearchDetail=import_react54.memo((props)=>{let theme=useTheme().theme,r=props.result,parts2=[],rest=r.snippet;while(rest.length){let start=rest.indexOf(">>>");if(start<0){parts2.push({text:rest,hi:!1});break}if(start>0)parts2.push({text:rest.slice(0,start),hi:!1});let end=rest.indexOf("<<<",start+3);if(end<0){parts2.push({text:rest.slice(start+3),hi:!0});break}parts2.push({text:rest.slice(start+3,end),hi:!0}),rest=rest.slice(end+3)}return $jsx(TabShell,{title:"Search Match",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:r.title??"Untitled"})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Source",badge(r.source)],["Model",r.model??"\u2014"],["Time",when(r.started_at)]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Snippet"})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:parts2.map((p,i)=>p.hi?$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:p.text})},i):$jsx("span",{fg:theme.text,children:p.text},i))})})]})})})}),HeaderRow=import_react54.memo((props)=>{let theme=useTheme().theme,fg2=theme.textMuted,on=theme.accent,by=props.sort;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:8,fg:by==="started"?on:fg2,bold:!0,onClick:()=>props.onSort("started"),children:by==="started"?"Start \u25BE":"Start"}),$jsx(Col,{w:10,fg:by==="active"?on:fg2,bold:!0,right:!0,onClick:()=>props.onSort("active"),children:by==="active"?"Active \u25BE":"Active"}),$jsx(Col,{w:7,fg:fg2,bold:!0,right:!0,children:"Msgs"}),$jsx("box",{width:3})]})}),Item=import_react54.memo((props)=>{let theme=useTheme().theme,{row:r,idx:i}=props,[x2,setX]=import_react54.useState(!1),active=r.detail?.last_active??r.detail?.ended_at??null,locked=props.indent||Boolean(r.live),leader=props.indent?"\u2514\u2500":props.selected?"\u25B8 ":" ",muted=props.indent&&!props.selected?theme.textMuted:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:muted??theme.text,children:leader}),$jsx(Marquee,{grow:!0,active:props.selected,fg:props.selected?theme.accent:muted??theme.text,bold:props.selected,children:label(r)}),$jsx(Col,{w:9,fg:muted??theme.info,children:badge(src(r))}),$jsx(Col,{w:8,fg:theme.textMuted,children:stamp(r.started_at)}),$jsx(Col,{w:10,fg:theme.textMuted,right:!0,children:active?ago(active):"\u2014"}),$jsx(Col,{w:7,fg:theme.textMuted,right:!0,children:String(r.message_count)}),locked?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{children:$jsx("span",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})})]})}),SearchHeaderRow=import_react54.memo(()=>{let fg2=useTheme().theme.textMuted;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:10,fg:fg2,bold:!0,children:"When"}),$jsx(Col,{w:20,fg:fg2,bold:!0,children:"Model"})]})}),SearchItem=import_react54.memo((props)=>{let theme=useTheme().theme,{result:r,idx:i}=props;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,bold:props.selected,children:r.title??"Untitled"}),$jsx(Col,{w:9,fg:theme.info,children:badge(r.source)}),$jsx(Col,{w:10,fg:theme.textMuted,children:ago(r.started_at)}),$jsx(Col,{w:20,fg:theme.textMuted,children:r.model??"\u2014"})]})}),last={rows:[],kids:new Map},Sessions=import_react54.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),cached2=props.io==null,io2={list:props.io?.list??io.roots,search:props.io?.search??io.search,subagents:props.io?.subagents??io.children,lineage:props.io?.lineage??io.lineage,peek:props.io?.peek??io.peek,remove:props.io?.remove??exports_sessions_db.remove,rename:props.io?.rename??exports_sessions_db.rename},[rows2,setRows]=import_react54.useState(cached2?last.rows:[]),[liveRows,setLiveRows]=import_react54.useState([]),[warn,setWarn]=import_react54.useState(""),[pending3,setPending]=import_react54.useState(rows2.length===0),sort=exports_preferences.usePref("sessions")?.sort??"active",setSort=import_react54.useCallback((s)=>exports_preferences.set("sessions",{sort:s}),[]),[view,setView]=import_react54.useState(HOME4),active=import_react54.useMemo(()=>[...liveRows].sort((a,b2)=>Number(Boolean(b2.live?.current))-Number(Boolean(a.live?.current))||(b2.live?.last_active??b2.started_at)-(a.live?.last_active??a.started_at)),[liveRows]),ids=import_react54.useMemo(()=>new Set(active.flatMap((r)=>[r.id,r.live?.session_key].filter((x2)=>Boolean(x2)))),[active]),sorted=import_react54.useMemo(()=>rows2.filter((r)=>!ids.has(r.id)).sort(cmp(sort)),[rows2,ids,sort]),views=import_react54.useMemo(()=>{let stats=sorted.reduce((m2,r)=>{let s=src(r);if(!s)return m2;let prev=m2.get(s);return m2.set(s,{count:(prev?.count??0)+1,last:Math.max(prev?.last??0,tick2(r))}),m2},new Map),conv=sorted.filter((r)=>src(r)!=="cron").length;return[...conv>0?[{id:HOME4,label:"Conversations",count:conv,aggregate:"conversations"}]:[],...[...stats.entries()].sort((a,b2)=>b2[1].last-a[1].last||badge(a[0]).localeCompare(badge(b2[0]))).map(([source,stat2])=>({id:sid(source),label:badge(source),count:stat2.count,source}))]},[sorted]),cur=views.find((v2)=>v2.id===view)??views[0],chosen=cur?.id??view,hist=import_react54.useMemo(()=>{if(!cur)return[];if(cur.aggregate===HOME4)return sorted.filter((r)=>src(r)!=="cron");return sorted.filter((r)=>src(r)===cur.source)},[sorted,cur]),listed=import_react54.useMemo(()=>[...active,...hist],[active,hist]);import_react54.useEffect(()=>{if(views.length>0&&!views.some((v2)=>v2.id===view))setView(views[0].id)},[views,view]);let[anchor,setAnchor]=import_react54.useState(null),[searching,setSearching]=import_react54.useState(!1),[query,setQuery]=import_react54.useState(""),[results,setResults]=import_react54.useState([]),[searchSel,setSearchSel]=import_react54.useState(0),[kids,setKids]=import_react54.useState(cached2?last.kids:new Map),debounce=import_react54.useRef(null),vscroll=import_react54.useRef(null),seen=import_react54.useRef(!1),anchored=anchor&&listed.find((r)=>r.id===anchor.id),owner=anchor?.indent?listed.find((r)=>kids.get(r.id)?.some((c)=>c.id===anchor.id)):(anchored?.detail?.subagent_count??0)>0?anchored:void 0,visible2=listed.flatMap((r,i)=>r.id===owner?.id?[{row:r,indent:!1,parentIdx:i},...(kids.get(r.id)??[]).map((c)=>({row:c,indent:!0,parentIdx:i}))]:[{row:r,indent:!1,parentIdx:i}]),sel=anchor?Math.max(0,visible2.findIndex((v2)=>v2.row.id===anchor.id&&v2.indent===anchor.indent)):0,live=import_react54.useRef({rows:listed,visible:visible2,anchor,results,searching,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId});live.current={rows:listed,visible:visible2,anchor,results,searching,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId};let setSel=import_react54.useCallback((arg)=>{let cur2=live.current,prev=cur2.visible.findIndex((v3)=>v3.row.id===cur2.anchor?.id&&v3.indent===cur2.anchor.indent),n=typeof arg==="function"?arg(Math.max(0,prev)):arg,v2=cur2.visible[Math.max(0,Math.min(cur2.visible.length-1,n))];if(v2)setAnchor({id:v2.row.id,indent:v2.indent})},[]),LIMIT=2000,keep=(d2)=>d2.message_count>0||d2.lineage_root_id!=null,toRow2=(d2)=>({id:d2.id,title:d2.title??"",preview:d2.lastMessage??"",message_count:d2.message_count,started_at:d2.started_at,source:d2.sessionSource,detail:d2}),toLiveRow=(s,d2,r)=>({id:s.id,title:s.title?.trim()||d2?.title||"",preview:s.preview??"",message_count:s.message_count??d2?.message_count??r?.message_count??0,started_at:s.started_at??d2?.started_at??r?.started_at??s.last_active??0,source:d2?.sessionSource??r?.source??s.source??"",detail:d2,live:s}),pick=(m2,s)=>m2.get(s.id)??m2.get(s.session_key??""),load4=import_react54.useCallback(async()=>{setPending(!0);let rpc=gw.request("session.list",{limit:LIMIT}).then((r2)=>({ok:!0,v:r2})).catch((e)=>({ok:!1,e})),active2=gw.request("session.active_list",{current_session_id:props.currentId}).then((r2)=>({ok:!0,v:r2})).catch((e)=>({ok:!1,e})),disk=await Promise.resolve(io2.list(LIMIT)).catch(()=>[]),local=new Map(disk.map((r2)=>[r2.id,r2])),diskRows=disk.filter(keep).map(toRow2);if(setRows(diskRows),cached2)last.rows=diskRows;let fillKids=async(list2)=>{let ps=list2.filter((r2)=>(r2.detail?.subagent_count??0)>0),cs=await Promise.all(ps.map((r2)=>io2.subagents(r2.id))),m2=new Map(ps.map((r2,i)=>[r2.id,cs[i].map(toRow2)]));if(setKids(m2),cached2)last.kids=m2};fillKids(diskRows);let a=await active2,live2=a.ok?a.v.sessions??[]:[];if(a.ok)setLiveRows(live2.map((s)=>toLiveRow(s,pick(local,s))));let r=await rpc;if(r.ok&&r.v.sessions?.length){let seen2=new Set(diskRows.map((s)=>s.id)),merged=[...diskRows,...r.v.sessions.filter((s)=>(s.message_count??0)>0&&!seen2.has(s.id)).map((s)=>({...s,detail:local.get(s.id)}))];if(setRows(merged),cached2)last.rows=merged;let found=new Map(merged.map((s)=>[s.id,s]));if(live2.length)setLiveRows(live2.map((s)=>toLiveRow(s,pick(local,s),pick(found,s))));fillKids(merged)}setPending(!1),setWarn(!r.ok?local.size?`gateway session.list failed (${r.e.message}) \u2014 listing state.db directly; rows may not resume`:r.e.message:"")},[gw,props.currentId]);import_react54.useEffect(()=>{load4()},[load4]),import_react54.useEffect(()=>{let on=active.length>0,fresh=on&&!seen.current;if(!listed.length){seen.current=on;return}if(!anchor||!visible2.some((v2)=>v2.row.id===anchor.id&&v2.indent===anchor.indent)){setAnchor({id:listed[0].id,indent:!1}),seen.current=on;return}if(fresh&&active[0]&&hist[0]?.id===anchor.id&&!anchor.indent)setAnchor({id:active[0].id,indent:!1});seen.current=on},[listed,active,hist,anchor]),import_react54.useEffect(()=>{if(!searching||!query.trim()){setResults([]);return}return debounce.current=setTimeout(()=>{Promise.resolve(io2.search(query,30)).then((r)=>{setResults(r),setSearchSel(0)})},150),()=>{if(debounce.current)clearTimeout(debounce.current)}},[query,searching]);let rowHover=import_react54.useCallback((i)=>{live.current.searching?setSearchSel(i):setSel(i)},[setSel]),rowActivate=import_react54.useCallback((i)=>{let l=live.current;l.searching?setSearchSel(i):setSel(i);let hit=l.searching?l.results[i]:l.visible[i]?.row,id=l.searching?hit?.session_id:hit?.id;if(!id)return;if(!l.searching&&hit?.live){if(l.onActivateLive)return l.onActivateLive(id);return l.onSwitch?.(id)}if(!l.onSwitch)return;if(id===l.currentId)return l.onSwitch(id);let title=hit?.title||"Untitled",n=l.searching?void 0:hit.message_count;openConfirm(dialog,{title:"Load session?",body:`${trunc5(title,60)}${n!=null?` \xB7 ${n} msg${n===1?"":"s"}`:""}
4121
+ `))}var ENV_CATALOG=[{category:"LLM Providers",keys:["ANTHROPIC_API_KEY","OPENAI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","MISTRAL_API_KEY","XAI_API_KEY","TOGETHER_API_KEY","FIREWORKS_API_KEY","NOUS_API_KEY"]},{category:"Tool API Keys",keys:["FIRECRAWL_API_KEY","BROWSERBASE_API_KEY","BROWSERBASE_PROJECT_ID","TAVILY_API_KEY","EXA_API_KEY","ELEVENLABS_API_KEY"]},{category:"Messaging",keys:["TELEGRAM_BOT_TOKEN","DISCORD_BOT_TOKEN","SLACK_BOT_TOKEN","SLACK_APP_TOKEN"]},{category:"Agent",keys:["API_SERVER_KEY","MEM0_API_KEY"]}];var SLICES={config:{read:()=>readConfig(),watch:()=>[hermesPath("config.yaml")]},memory:{read:(d2)=>readMemoryFile("MEMORY.md",d2.config?.memory?.memory_char_limit??2200),deps:["config"],watch:()=>[hermesPath("memories/MEMORY.md")]},userProfile:{read:(d2)=>readMemoryFile("USER.md",d2.config?.memory?.user_char_limit??1375),deps:["config"],watch:()=>[hermesPath("memories/USER.md")]},memoryProviders:{read:(d2)=>readMemoryProviders(d2.config?.memory?.provider??""),deps:["config"]},memoryActivity:{read:()=>io.memoryActivity()},env:{read:()=>readEnvFile(),watch:()=>[hermesPath(".env")]},soul:{read:()=>readSoul(),watch:()=>[hermesPath("SOUL.md")]},liveSessions:{read:()=>readLiveSessions(),watch:()=>[hermesPath("sessions/sessions.json")]},recentSessions:{read:()=>io.roots(30)},systemPrompt:{read:()=>io.systemPrompt().then((r)=>r&&{source:makeSource("state.db"),sessionId:r.id,text:r.text,totalChars:r.text.length,tokenEstimate:count2(r.text)}).catch(()=>null)},toolsInfo:{read:()=>readToolsFromLatestSession(),watch:()=>[hermesPath("sessions")]},skillUsage:{read:()=>readSkillUsage(),watch:()=>[hermesPath("skills/.usage.json")]},curatorState:{read:()=>readCuratorState(),watch:()=>[hermesPath("skills/.curator_state")]}},DEPENDENTS=(()=>{let m2=new Map;for(let[k2,s]of Object.entries(SLICES))for(let d2 of s.deps??[]){let arr=m2.get(d2)??[];arr.push(k2),m2.set(d2,arr)}return m2})(),DEBOUNCE_MS=50;class HomeStore{data={};subs=new Map;inflight=new Map;watchers=new Map;debounce=new Map;get(k2){return this.data[k2]}subscribe(k2,cb){let set2=this.subs.get(k2);if(!set2)this.subs.set(k2,set2=new Set);return set2.add(cb),()=>set2.delete(cb)}ensure(k2){if(k2 in this.data)return Promise.resolve(this.data[k2]);let hit=this.inflight.get(k2);if(hit)return hit;let slice=SLICES[k2],p=(async()=>{let deps={};for(let d2 of slice.deps??[])deps[d2]=await this.ensure(d2);let v2=await slice.read(deps);return this.data[k2]=v2,this.startWatch(k2,slice.watch),this.notify(k2),v2})().finally(()=>this.inflight.delete(k2));return this.inflight.set(k2,p),p}invalidate(k2){if(!(k2 in this.data)&&!this.inflight.has(k2))return;if(delete this.data[k2],this.subs.get(k2)?.size)this.ensure(k2);for(let dep of DEPENDENTS.get(k2)??[])this.invalidate(dep)}close(){for(let ws of this.watchers.values())for(let w2 of ws)w2.close();for(let t2 of this.debounce.values())clearTimeout(t2);this.watchers.clear(),this.debounce.clear(),this.subs.clear(),this.inflight.clear(),this.data={}}reset(){for(let ws of this.watchers.values())for(let w2 of ws)w2.close();for(let t2 of this.debounce.values())clearTimeout(t2);this.watchers.clear(),this.debounce.clear(),this.inflight.clear(),this.data={};for(let k2 of this.subs.keys())if(this.subs.get(k2)?.size)this.ensure(k2)}notify(k2){let set2=this.subs.get(k2);if(set2)for(let cb of set2)cb()}startWatch(k2,watchFn){if(!watchFn||this.watchers.has(k2))return;let paths=watchFn(),ws=[],fire=()=>{let prev=this.debounce.get(k2);if(prev)clearTimeout(prev);this.debounce.set(k2,setTimeout(()=>this.invalidate(k2),DEBOUNCE_MS))};for(let p of paths){let dir=dirname9(p),name=basename9(p);try{if(existsSync13(p)&&statSync6(p).isDirectory())dir=p,name=null}catch{}if(!existsSync13(dir))continue;try{ws.push(watch2(dir,{persistent:!1},(_ev,f)=>{if(name===null||f===name)fire()}))}catch{}}this.watchers.set(k2,ws)}}var home2=new HomeStore;function useHome(k2){let v2=import_react53.useSyncExternalStore((cb)=>home2.subscribe(k2,cb),()=>home2.get(k2));return import_react53.useEffect(()=>{home2.ensure(k2)},[k2]),v2}var cmp=(s)=>{let k2=(r)=>s==="started"?r.started_at:r.detail?.last_active??r.started_at;return(a,b2)=>k2(b2)-k2(a)},WORD={api:"API",cli:"CLI",tui:"TUI",whatsapp:"WhatsApp"},badge=(s)=>s.split(/[_-]+/).filter(Boolean).map((w2)=>WORD[w2.toLowerCase()]??(w2[0]?.toUpperCase()??"")+w2.slice(1)).join(" ")||"\u2014",label=(r)=>r.title.trim()||(r.live?"-":"Untitled"),src=(r)=>r.detail?.sessionSource||r.source||"",HOME4="conversations",HBAR={visible:!1},ROW={flexDirection:"row"},sid=(s)=>`source:${s}`,chip=(id)=>`sessions-source-${id.replace(/[^a-z0-9_-]/gi,"_")}`,tick2=(r)=>r.detail?.last_active??r.started_at,FilterRow=import_react54.memo((p)=>{let theme=useTheme().theme,ref=import_react54.useRef(null);return import_react54.useEffect(()=>{let move=()=>{let node=ref.current,idx=p.views.findIndex((v2)=>v2.id===p.view);if(!node||idx<0)return;let left=p.views.slice(0,idx).reduce((n,v2,i)=>n+(i===0?0:1)+`${v2.label} ${v2.count}`.length+2,0),w2=`${p.views[idx].label} ${p.views[idx].count}`.length+2,port2=Math.max(1,node.viewport.width-4),pos=node.scrollLeft;node.scrollLeft=Math.max(0,left<pos?left:left+w2>pos+port2?left+w2-port2:pos)};move();let id=setTimeout(move,0);return()=>clearTimeout(id)},[p.view,p.views]),$jsx("scrollbox",{ref,scrollX:!0,height:1,paddingLeft:2,horizontalScrollbarOptions:HBAR,contentOptions:ROW,children:p.views.map((v2,i)=>$jsx(FilterChip,{id:chip(v2.id),label:`${v2.label} ${v2.count}`,state:p.view===v2.id?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.primary,onMouseDown:()=>p.setView(v2.id)},v2.id))})}),line=(s)=>(s??"").replace(/\s+/g," ").trim(),fold=(msgs)=>{let turns=[],tools=0;for(let m2 of msgs){if(m2.role==="tool"){tools++;continue}if(m2.role!=="user"&&m2.role!=="assistant")continue;let text3=line(m2.content);if(!text3)continue;turns.push({role:m2.role,text:text3})}return{turns,tools}},PeekRow=import_react54.memo((props)=>{let theme=useTheme().theme,[hot,setHot]=import_react54.useState(!1),left=props.row.role==="user",color=left?theme.primary:theme.accent,fg2=left?theme.text:theme.markdownText,bar=(side)=>$jsx("box",{width:2,flexShrink:0,height:1,border:[side],borderColor:color,customBorderChars:SIDE_PIPE});return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:hot?theme.backgroundElement:void 0,onMouseOver:()=>setHot(!0),onMouseOut:()=>setHot(!1),children:[left?bar("left"):null,$jsx(Ticker,{active:hot,speed:35,hold:150,fg:fg2,children:inline(props.row.text).map((s,i)=>s.c?$jsx("span",{fg:theme.warning,children:s.t},i):s.b?$jsx("span",{fg:fg2,children:$jsx("strong",{children:s.t})},i):s.i?$jsx("span",{fg:fg2,children:$jsx("u",{children:s.t})},i):$jsx("span",{fg:fg2,children:s.t},i))}),left?null:bar("right")]})}),Peek=import_react54.memo((props)=>{let theme=useTheme().theme,[data2,setData]=import_react54.useState(null),sb=import_react54.useRef(null);if(import_react54.useEffect(()=>{Promise.resolve(props.peek(props.sid)).then((m2)=>setData(fold(m2)))},[props.sid,props.peek]),import_react54.useEffect(()=>{if(data2&&sb.current)sb.current.scrollTop=sb.current.scrollHeight},[data2]),data2===null)return null;if(data2.turns.length===0&&data2.tools===0)return $jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local transcript)"})});let gap=props.total>4;return $jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:5,border:!0,borderStyle:"single",borderColor:theme.border,title:` Transcript${gap?" \xB7 first 2 / last 2":""} `,titleAlignment:"left",children:[$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,minHeight:3,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.turns.map((r,i)=>$jsxs(import_react54.Fragment,{children:[$jsx(PeekRow,{row:r}),gap&&i===1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" \u2026"})}):null]},i))})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${data2.turns.length} turn${data2.turns.length===1?"":"s"} \xB7 ${data2.tools} tool call${data2.tools===1?"":"s"}`})})]})}),Detail=import_react54.memo((props)=>{let theme=useTheme().theme,r=props.row,d2=r.detail,lastActive=d2?.last_active??d2?.ended_at??null,subs2=d2?.subagent_count??0,[info,setInfo]=import_react54.useState({});import_react54.useEffect(()=>{Promise.resolve(props.lineage(r.id)).then(setInfo)},[r.id,props.lineage]);let hasLineage=info.continuesFrom||info.compressedTo||subs2>0,go=(sid2)=>()=>props.onSwitch?.(sid2);return $jsx(TabShell,{title:"Session Detail",grow:2,children:$jsxs("box",{flexDirection:"column",width:"100%",flexGrow:1,overflow:"hidden",children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:label(r)})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["ID",r.id],["Source",badge(src(r))],["Model",d2?.model??"\u2014"],["Started",when(r.started_at)],["Last active",lastActive?`${when(lastActive)} (${ago(lastActive)})`:"\u2014"],["Duration",lastActive?span(r.started_at,lastActive):"\u2014"],["Ended",d2?.ended_at?`${when(d2.ended_at)} \xB7 ${d2.end_reason??"\u2014"}`:void 0]]}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Messages",String(r.message_count)],["Tool calls",d2?String(d2.tool_call_count):void 0],["Input",d2?`${fmt(d2.input_tokens)} tok`:void 0],["Output",d2?`${fmt(d2.output_tokens)} tok`:void 0],["Cache",d2?`${fmt(d2.cache_read_tokens)} r / ${fmt(d2.cache_write_tokens)} w`:void 0],["Reasoning",d2?`${fmt(d2.reasoning_tokens)} tok`:void 0],["Cost",d2?cost2(d2.estimated_cost_usd):void 0,theme.success]]}),hasLineage?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,children:"Lineage"})}),info.continuesFrom?$jsx("box",{height:1,onMouseDown:go(info.continuesFrom.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2190 continues from "}),$jsx("span",{fg:theme.accent,children:info.continuesFrom.title||info.continuesFrom.id})]})}):null,info.compressedTo?$jsx("box",{height:1,onMouseDown:go(info.compressedTo.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2192 compressed to "}),$jsx("span",{fg:theme.accent,children:info.compressedTo.title||info.compressedTo.id})]})}):null,subs2>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2387 spawned "}),$jsx("span",{fg:theme.text,children:String(subs2)}),$jsx("span",{fg:theme.textMuted,children:` subagent${subs2===1?"":"s"}`})]})}):null]}):null,!d2?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local detail \u2014 state.db mismatch)"})})]}):null,$jsx("box",{height:1})]}),$jsx(Peek,{sid:r.id,total:r.message_count,peek:props.peek})]})})}),SearchDetail=import_react54.memo((props)=>{let theme=useTheme().theme,r=props.result,parts2=[],rest=r.snippet;while(rest.length){let start=rest.indexOf(">>>");if(start<0){parts2.push({text:rest,hi:!1});break}if(start>0)parts2.push({text:rest.slice(0,start),hi:!1});let end=rest.indexOf("<<<",start+3);if(end<0){parts2.push({text:rest.slice(start+3),hi:!0});break}parts2.push({text:rest.slice(start+3,end),hi:!0}),rest=rest.slice(end+3)}return $jsx(TabShell,{title:"Search Match",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:r.title??"Untitled"})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Source",badge(r.source)],["Model",r.model??"\u2014"],["Time",when(r.started_at)]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Snippet"})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:parts2.map((p,i)=>p.hi?$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:p.text})},i):$jsx("span",{fg:theme.text,children:p.text},i))})})]})})})}),HeaderRow=import_react54.memo((props)=>{let theme=useTheme().theme,fg2=theme.textMuted,on=theme.accent,by=props.sort;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:8,fg:by==="started"?on:fg2,bold:!0,onClick:()=>props.onSort("started"),children:by==="started"?"Start \u25BE":"Start"}),$jsx(Col,{w:10,fg:by==="active"?on:fg2,bold:!0,right:!0,onClick:()=>props.onSort("active"),children:by==="active"?"Active \u25BE":"Active"}),$jsx(Col,{w:7,fg:fg2,bold:!0,right:!0,children:"Msgs"}),$jsx("box",{width:3})]})}),Item=import_react54.memo((props)=>{let theme=useTheme().theme,{row:r,idx:i}=props,[x2,setX]=import_react54.useState(!1),active=r.detail?.last_active??r.detail?.ended_at??null,locked=props.indent||Boolean(r.live),subs2=!props.indent&&(r.detail?.subagent_count??0)>0,leader=props.indent?"\u2514\u2500":props.selected?"\u25B8 ":" ",muted=props.indent&&!props.selected?theme.textMuted:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:muted??theme.text,children:leader}),$jsx(Marquee,{grow:!0,active:props.selected,fg:props.selected?theme.accent:muted??theme.text,bold:props.selected,underline:props.selected&&subs2,children:label(r)}),$jsx(Col,{w:9,fg:muted??theme.info,children:badge(src(r))}),$jsx(Col,{w:8,fg:theme.textMuted,children:stamp(r.started_at)}),$jsx(Col,{w:10,fg:theme.textMuted,right:!0,children:active?ago(active):"\u2014"}),$jsx(Col,{w:7,fg:theme.textMuted,right:!0,children:subs2?`${r.detail?.subagent_count} subs`:String(r.message_count)}),locked?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{children:$jsx("span",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})})]})}),SearchHeaderRow=import_react54.memo(()=>{let fg2=useTheme().theme.textMuted;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:10,fg:fg2,bold:!0,children:"When"}),$jsx(Col,{w:20,fg:fg2,bold:!0,children:"Model"})]})}),SearchItem=import_react54.memo((props)=>{let theme=useTheme().theme,{result:r,idx:i}=props;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,bold:props.selected,children:r.title??"Untitled"}),$jsx(Col,{w:9,fg:theme.info,children:badge(r.source)}),$jsx(Col,{w:10,fg:theme.textMuted,children:ago(r.started_at)}),$jsx(Col,{w:20,fg:theme.textMuted,children:r.model??"\u2014"})]})}),last={rows:[],kids:new Map},Sessions=import_react54.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),cached2=props.io==null,io2={list:props.io?.list??io.roots,search:props.io?.search??io.search,subagents:props.io?.subagents??io.children,lineage:props.io?.lineage??io.lineage,peek:props.io?.peek??io.peek,remove:props.io?.remove??exports_sessions_db.remove,rename:props.io?.rename??exports_sessions_db.rename},[rows2,setRows]=import_react54.useState(cached2?last.rows:[]),[liveRows,setLiveRows]=import_react54.useState([]),[warn,setWarn]=import_react54.useState(""),[pending3,setPending]=import_react54.useState(rows2.length===0),sort=exports_preferences.usePref("sessions")?.sort??"active",setSort=import_react54.useCallback((s)=>exports_preferences.set("sessions",{sort:s}),[]),[view,setView]=import_react54.useState(HOME4),active=import_react54.useMemo(()=>[...liveRows].sort((a,b2)=>Number(Boolean(b2.live?.current))-Number(Boolean(a.live?.current))||(b2.live?.last_active??b2.started_at)-(a.live?.last_active??a.started_at)),[liveRows]),ids=import_react54.useMemo(()=>new Set(active.flatMap((r)=>[r.id,r.live?.session_key].filter((x2)=>Boolean(x2)))),[active]),sorted=import_react54.useMemo(()=>rows2.filter((r)=>!ids.has(r.id)).sort(cmp(sort)),[rows2,ids,sort]),views=import_react54.useMemo(()=>{let stats=sorted.reduce((m2,r)=>{let s=src(r);if(!s)return m2;let prev=m2.get(s);return m2.set(s,{count:(prev?.count??0)+1,last:Math.max(prev?.last??0,tick2(r))}),m2},new Map),conv=sorted.filter((r)=>src(r)!=="cron").length;return[...conv>0?[{id:HOME4,label:"Conversations",count:conv,aggregate:"conversations"}]:[],...[...stats.entries()].sort((a,b2)=>b2[1].last-a[1].last||badge(a[0]).localeCompare(badge(b2[0]))).map(([source,stat2])=>({id:sid(source),label:badge(source),count:stat2.count,source}))]},[sorted]),cur=views.find((v2)=>v2.id===view)??views[0],chosen=cur?.id??view,hist=import_react54.useMemo(()=>{if(!cur)return[];if(cur.aggregate===HOME4)return sorted.filter((r)=>src(r)!=="cron");return sorted.filter((r)=>src(r)===cur.source)},[sorted,cur]),listed=import_react54.useMemo(()=>[...active,...hist],[active,hist]);import_react54.useEffect(()=>{if(views.length>0&&!views.some((v2)=>v2.id===view))setView(views[0].id)},[views,view]);let[anchor,setAnchor]=import_react54.useState(null),[open2,setOpen]=import_react54.useState(null),[searching,setSearching]=import_react54.useState(!1),[query,setQuery]=import_react54.useState(""),[results,setResults]=import_react54.useState([]),[searchSel,setSearchSel]=import_react54.useState(0),[kids,setKids]=import_react54.useState(cached2?last.kids:new Map),debounce=import_react54.useRef(null),vscroll=import_react54.useRef(null),seen=import_react54.useRef(!1),anchored=anchor&&listed.find((r)=>r.id===anchor.id),branch2=open2?listed.find((r)=>r.id===open2):void 0,owner=branch2&&(anchor?.indent?kids.get(branch2.id)?.some((c)=>c.id===anchor.id):anchored?.id===branch2.id)?branch2:void 0,showDetailPanel=dims.width>=120,visible2=listed.flatMap((r,i)=>r.id===owner?.id?[{row:r,indent:!1,parentIdx:i},...(kids.get(r.id)??[]).map((c)=>({row:c,indent:!0,parentIdx:i}))]:[{row:r,indent:!1,parentIdx:i}]),sel=anchor?Math.max(0,visible2.findIndex((v2)=>v2.row.id===anchor.id&&v2.indent===anchor.indent)):0,live=import_react54.useRef({rows:listed,visible:visible2,anchor,results,searching,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId});live.current={rows:listed,visible:visible2,anchor,results,searching,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId};let setSel=import_react54.useCallback((arg)=>{let cur2=live.current,prev=cur2.visible.findIndex((v3)=>v3.row.id===cur2.anchor?.id&&v3.indent===cur2.anchor.indent),n=typeof arg==="function"?arg(Math.max(0,prev)):arg,v2=cur2.visible[Math.max(0,Math.min(cur2.visible.length-1,n))];if(v2)setAnchor({id:v2.row.id,indent:v2.indent})},[]),LIMIT=2000,keep=(d2)=>d2.message_count>0||d2.lineage_root_id!=null,toRow2=(d2)=>({id:d2.id,title:d2.title??"",preview:d2.lastMessage??"",message_count:d2.message_count,started_at:d2.started_at,source:d2.sessionSource,detail:d2}),toLiveRow=(s,d2,r)=>({id:s.id,title:s.title?.trim()||d2?.title||"",preview:s.preview??"",message_count:s.message_count??d2?.message_count??r?.message_count??0,started_at:s.started_at??d2?.started_at??r?.started_at??s.last_active??0,source:d2?.sessionSource??r?.source??s.source??"",detail:d2,live:s}),pick=(m2,s)=>m2.get(s.id)??m2.get(s.session_key??""),load4=import_react54.useCallback(async()=>{setPending(!0);let rpc=gw.request("session.list",{limit:LIMIT}).then((r2)=>({ok:!0,v:r2})).catch((e)=>({ok:!1,e})),active2=gw.request("session.active_list",{current_session_id:props.currentId}).then((r2)=>({ok:!0,v:r2})).catch((e)=>({ok:!1,e})),disk=await Promise.resolve(io2.list(LIMIT)).catch(()=>[]),local=new Map(disk.map((r2)=>[r2.id,r2])),diskRows=disk.filter(keep).map(toRow2);if(setRows(diskRows),cached2)last.rows=diskRows;let fillKids=async(list2)=>{let ps=list2.filter((r2)=>(r2.detail?.subagent_count??0)>0),cs=await Promise.all(ps.map((r2)=>io2.subagents(r2.id))),m2=new Map(ps.map((r2,i)=>[r2.id,cs[i].map(toRow2)]));if(setKids(m2),cached2)last.kids=m2};fillKids(diskRows);let a=await active2,live2=a.ok?a.v.sessions??[]:[];if(a.ok)setLiveRows(live2.map((s)=>toLiveRow(s,pick(local,s))));let r=await rpc;if(r.ok&&r.v.sessions?.length){let seen2=new Set(diskRows.map((s)=>s.id)),merged=[...diskRows,...r.v.sessions.filter((s)=>(s.message_count??0)>0&&!seen2.has(s.id)).map((s)=>({...s,detail:local.get(s.id)}))];if(setRows(merged),cached2)last.rows=merged;let found=new Map(merged.map((s)=>[s.id,s]));if(live2.length)setLiveRows(live2.map((s)=>toLiveRow(s,pick(local,s),pick(found,s))));fillKids(merged)}setPending(!1),setWarn(!r.ok?local.size?`gateway session.list failed (${r.e.message}) \u2014 listing state.db directly; rows may not resume`:r.e.message:"")},[gw,props.currentId]);import_react54.useEffect(()=>{load4()},[load4]),import_react54.useEffect(()=>{let on=active.length>0,fresh=on&&!seen.current;if(!listed.length){seen.current=on;return}if(!anchor||!visible2.some((v2)=>v2.row.id===anchor.id&&v2.indent===anchor.indent)){setAnchor({id:listed[0].id,indent:!1}),seen.current=on;return}if(fresh&&active[0]&&hist[0]?.id===anchor.id&&!anchor.indent)setAnchor({id:active[0].id,indent:!1});seen.current=on},[listed,active,hist,anchor]),import_react54.useEffect(()=>{if(!searching||!query.trim()){setResults([]);return}return debounce.current=setTimeout(()=>{Promise.resolve(io2.search(query,30)).then((r)=>{setResults(r),setSearchSel(0)})},150),()=>{if(debounce.current)clearTimeout(debounce.current)}},[query,searching]);let rowHover=import_react54.useCallback((i)=>{live.current.searching?setSearchSel(i):setSel(i)},[setSel]),rowActivate=import_react54.useCallback((i)=>{let l=live.current;l.searching?setSearchSel(i):setSel(i);let hit=l.searching?l.results[i]:l.visible[i]?.row,id=l.searching?hit?.session_id:hit?.id;if(!id)return;if(!l.searching&&hit?.live){if(l.onActivateLive)return l.onActivateLive(id);return l.onSwitch?.(id)}if(!l.onSwitch)return;if(id===l.currentId)return l.onSwitch(id);let title=hit?.title||"Untitled",n=l.searching?void 0:hit.message_count;openConfirm(dialog,{title:"Load session?",body:`${trunc5(title,60)}${n!=null?` \xB7 ${n} msg${n===1?"":"s"}`:""}
4119
4122
 
4120
4123
  Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(id)})},[dialog]),rowDelete=import_react54.useCallback((i)=>{let v2=live.current.visible[i];if(v2&&!v2.indent&&!v2.row.live)confirmDeleteRef.current(v2.row)},[]),lineageSwitch=import_react54.useCallback((sid2)=>{let l=live.current;if(!l.onSwitch)return;if(sid2===l.currentId)return l.onSwitch(sid2);openConfirm(dialog,{title:"Load session?",body:`Switch to ${trunc5(sid2,24)}?
4121
4124
 
4122
- Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid2)})},[dialog]),confirmDeleteRef=import_react54.useRef(()=>{}),confirmDelete=import_react54.useCallback((r)=>{openConfirm(dialog,{title:"Delete Session?",body:trunc5(label(r),46),yes:"Delete",danger:!0}).then(async(ok)=>{if(!ok)return;if(!await gw.request("session.delete",{session_id:r.id}).then(()=>!0).catch((e)=>{if(/active session/i.test(e.message))return toast.show({variant:"error",message:"Can't delete the active session"}),!1;return io2.remove(r.id)}))return;home2.invalidate("recentSessions"),toast.show({variant:"success",message:"Session deleted"}),load4()})},[gw,dialog,toast,load4]);confirmDeleteRef.current=confirmDelete;let rename2=import_react54.useCallback(async()=>{let v2=live.current.visible[sel];if(!v2||v2.indent)return;let r=v2.row,name=await openTextPrompt(dialog,{title:`Rename: ${trunc5(label(r),42)}`,label:"Title",initial:r.title||""});if(name===null)return;Promise.resolve().then(async()=>{let title=r.live?(await gw.request("session.title",{session_id:r.id,title:name})).title??name:name;if(!r.live&&!io2.rename(r.id,title))throw Error("not found");let ids2=[r.id,r.live?.session_key].filter((id)=>Boolean(id));home2.invalidate("recentSessions"),setRows((prev)=>prev.map((row3)=>ids2.includes(row3.id)?{...row3,title}:row3)),setLiveRows((prev)=>prev.map((row3)=>row3.id===r.id?{...row3,title,live:row3.live?{...row3.live,title}:row3.live}:row3)),toast.show({variant:"success",message:"Renamed"})}).catch((e)=>toast.show({variant:"error",message:`Rename failed: ${e.message}`}))},[gw,dialog,toast,sel]),count3=searching?results.length:visible2.length,rowId=(i)=>{if(searching)return`sess-s-${results[i]?.session_id??i}`;let v2=visible2[i];return v2?`sess-${v2.indent?"c":"p"}-${v2.row.id}`:`sess-empty-${i}`},keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setResults([]),setSearchSel(0);return}if(key3.name==="backspace")return setQuery((p)=>p.slice(0,-1));if(key3.name==="return")return rowActivate(searchSel);if(key3.name==="up")return setSearchSel((p)=>Math.max(0,p-1));if(key3.name==="down")return setSearchSel((p)=>Math.min(count3-1,p+1));if(key3.raw&&key3.raw.length===1&&key3.raw>=" ")return setQuery((p)=>p+key3.raw);return}if(handleListKey(keys,key3,{count:count3,setSel,page:Math.max(1,(vscroll.current?.viewport.height??10)-1),scrollTo:(n)=>vscroll.current?.scrollChildIntoView(rowId(n)),onActivate:()=>rowActivate(sel),onToggle:()=>setSort(sort==="active"?"started":"active"),onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onDelete:()=>{let v2=visible2[sel];if(v2&&!v2.indent&&!v2.row.live)confirmDelete(v2.row)},onSearch:()=>{setSearching(!0),setQuery(""),setResults([]),setSearchSel(0)}}))return;if(keys.match("sessions.rename",key3))return void rename2();let prev=keys.match("sessions.prev",key3),next=keys.match("sessions.next",key3);if(prev||next){if(views.length<2)return;let dir=prev?-1:1;setView((v2)=>{let list2=views.map((x2)=>x2.id),i=list2.indexOf(v2);return list2[((i<0?0:i)+dir+list2.length)%list2.length]});return}});let empty=searching?results.length===0&&query.length>0:active.length===0&&sorted.length===0,action=visible2[sel]?.row.live?"activate live":"switch",top=(i)=>Boolean(visible2[i]?.row.live&&(i===0||!visible2[i-1]?.row.live)),tabs=(i)=>Boolean(views.length>0&&hist[0]&&!visible2[i]?.indent&&visible2[i]?.row.id===hist[0].id),gap=(i)=>active.length>0&&tabs(i),blank=cur?.aggregate===HOME4?"No conversations found":cur?`No ${cur.label} sessions found`:"No sessions found",showDetailPanel=dims.width>=120,nav=views.length>1?[["\u2190\u2192","filter"]]:[];return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Search Results (${results.length})`:`Sessions (${listed.length}${pending3?"\u2026":""})`,error:warn||null,grow:3,children:[searching?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,empty?$jsx("box",{flexGrow:1,padding:2,children:pending3&&!searching?$jsx(Spinner,{color:theme.textMuted,label:"loading sessions\u2026"}):$jsx("text",{fg:theme.textMuted,children:searching?"No matching sessions found":"No sessions found"})},"empty"):$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[searching?$jsx(SearchHeaderRow,{}):$jsx(HeaderRow,{sort,onSort:setSort}),$jsx("box",{height:1}),$jsxs("scrollbox",{ref:vscroll,scrollY:!0,viewportCulling:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:[searching?results.map((r,i)=>$jsx(SearchItem,{id:rowId(i),idx:i,result:r,selected:i===searchSel,onActivate:rowActivate,onHover:rowHover},r.session_id)):visible2.map((v2,i)=>$jsxs("box",{flexDirection:"column",height:1+(top(i)?1:0)+(tabs(i)?2:0)+(gap(i)?1:0),children:[top(i)?$jsx("box",{height:1,paddingLeft:2,children:$jsx("text",{fg:theme.primary,children:active.length===1?"Active Session":"Active Sessions"})}):null,gap(i)?$jsx("box",{height:1}):null,tabs(i)?$jsxs($Fragment,{children:[$jsx(FilterRow,{views,view:chosen,setView}),$jsx("box",{height:1})]}):null,$jsx(Item,{id:rowId(i),idx:i,row:v2.row,selected:i===sel,indent:v2.indent,onActivate:rowActivate,onHover:rowHover,onDelete:rowDelete})]},`${v2.row.id}-${v2.indent?"c":"p"}`)),!searching&&views.length>0&&hist.length===0?$jsxs("box",{flexDirection:"column",height:3+(active.length>0?1:0),children:[active.length>0?$jsx("box",{height:1}):null,$jsx(FilterRow,{views,view:chosen,setView}),$jsx("box",{height:1}),$jsx("box",{height:1,paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:blank})})]},"sessions-empty-filter"):null]})]},"table")]}),showDetailPanel&&searching&&results[searchSel]?$jsx(SearchDetail,{result:results[searchSel]}):showDetailPanel&&!searching&&visible2[sel]?.row?$jsx(Detail,{row:visible2[sel].row,lineage:io2.lineage,peek:io2.peek,onSwitch:lineageSwitch}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter/click","switch"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],...nav,[`${keys.print("list.activate")}/click`,action],[keys.print("list.search"),"search"],[keys.print("list.toggle"),`sort: ${sort}`],[keys.print("sessions.rename"),"rename"],[keys.print("list.delete"),"delete"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react57=__toESM(require_react_production(),1);var GRID=256,CPT=4,MEMORY_IDS=new Set(["soul","memory","user","mem0"]),SYSTEM_PROMPT_IDS=new Set(["project","meta","other"]);function parse4(text3){if(!text3)return[];let sections=[],used=Array(text3.length).fill(!1),mark2=(start2,end,id,label2,source)=>{let slice=text3.slice(start2,end);if(slice.trim().length===0)return;for(let i=start2;i<end;i++)used[i]=!0;sections.push({id,label:label2,chars:slice.length,tokens:count2(slice),text:slice,source})},bar1=text3.indexOf("\u2550\u2550\u2550\u2550\u2550\u2550");if(bar1>0)mark2(0,bar1,"soul","SOUL.md",makeSource("SOUL.md"));let memH=text3.indexOf("MEMORY (your personal notes)");if(memH>=0){let s=text3.lastIndexOf("\u2550\u2550\u2550\u2550\u2550\u2550",memH),after=text3.indexOf(`
4125
+ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid2)})},[dialog]),confirmDeleteRef=import_react54.useRef(()=>{}),confirmDelete=import_react54.useCallback((r)=>{openConfirm(dialog,{title:"Delete Session?",body:trunc5(label(r),46),yes:"Delete",danger:!0}).then(async(ok)=>{if(!ok)return;if(!await gw.request("session.delete",{session_id:r.id}).then(()=>!0).catch((e)=>{if(/active session/i.test(e.message))return toast.show({variant:"error",message:"Can't delete the active session"}),!1;return io2.remove(r.id)}))return;home2.invalidate("recentSessions"),toast.show({variant:"success",message:"Session deleted"}),load4()})},[gw,dialog,toast,load4]);confirmDeleteRef.current=confirmDelete;let rename2=import_react54.useCallback(async()=>{let v2=live.current.visible[sel];if(!v2||v2.indent)return;let r=v2.row,name=await openTextPrompt(dialog,{title:`Rename: ${trunc5(label(r),42)}`,label:"Title",initial:r.title||""});if(name===null)return;Promise.resolve().then(async()=>{let title=r.live?(await gw.request("session.title",{session_id:r.id,title:name})).title??name:name;if(!r.live&&!io2.rename(r.id,title))throw Error("not found");let ids2=[r.id,r.live?.session_key].filter((id)=>Boolean(id));home2.invalidate("recentSessions"),setRows((prev)=>prev.map((row3)=>ids2.includes(row3.id)?{...row3,title}:row3)),setLiveRows((prev)=>prev.map((row3)=>row3.id===r.id?{...row3,title,live:row3.live?{...row3.live,title}:row3.live}:row3)),toast.show({variant:"success",message:"Renamed"})}).catch((e)=>toast.show({variant:"error",message:`Rename failed: ${e.message}`}))},[gw,dialog,toast,sel]),toggle=import_react54.useCallback(()=>{let v2=visible2[sel];if(!v2)return;if(v2.indent){let p=listed.find((r)=>kids.get(r.id)?.some((c)=>c.id===v2.row.id));if(!p)return;setAnchor({id:p.id,indent:!1}),setOpen(null);return}if((v2.row.detail?.subagent_count??0)<=0)return;setOpen((id)=>id===v2.row.id?null:v2.row.id)},[visible2,sel,listed,kids]),count3=searching?results.length:visible2.length,rowId=(i)=>{if(searching)return`sess-s-${results[i]?.session_id??i}`;let v2=visible2[i];return v2?`sess-${v2.indent?"c":"p"}-${v2.row.id}`:`sess-empty-${i}`},keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setResults([]),setSearchSel(0);return}if(key3.name==="backspace")return setQuery((p)=>p.slice(0,-1));if(key3.name==="return")return rowActivate(searchSel);if(key3.name==="up")return setSearchSel((p)=>Math.max(0,p-1));if(key3.name==="down")return setSearchSel((p)=>Math.min(count3-1,p+1));if(key3.raw&&key3.raw.length===1&&key3.raw>=" ")return setQuery((p)=>p+key3.raw);return}if(handleListKey(keys,key3,{count:count3,setSel,page:Math.max(1,(vscroll.current?.viewport.height??10)-1),scrollTo:(n)=>vscroll.current?.scrollChildIntoView(rowId(n)),onActivate:()=>rowActivate(sel),onToggle:toggle,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onDelete:()=>{let v2=visible2[sel];if(v2&&!v2.indent&&!v2.row.live)confirmDelete(v2.row)},onSearch:()=>{setSearching(!0),setQuery(""),setResults([]),setSearchSel(0)}}))return;if(keys.match("sessions.sort",key3))return setSort(sort==="active"?"started":"active");if(keys.match("sessions.rename",key3))return void rename2();let prev=keys.match("sessions.prev",key3),next=keys.match("sessions.next",key3);if(prev||next){if(views.length<2)return;let dir=prev?-1:1;setView((v2)=>{let list2=views.map((x2)=>x2.id),i=list2.indexOf(v2);return list2[((i<0?0:i)+dir+list2.length)%list2.length]});return}});let empty=searching?results.length===0&&query.length>0:active.length===0&&sorted.length===0,action=visible2[sel]?.row.live?"activate live":"switch",top=(i)=>Boolean(visible2[i]?.row.live&&(i===0||!visible2[i-1]?.row.live)),tabs=(i)=>Boolean(views.length>0&&hist[0]&&!visible2[i]?.indent&&visible2[i]?.row.id===hist[0].id),gap=(i)=>active.length>0&&tabs(i),blank=cur?.aggregate===HOME4?"No conversations found":cur?`No ${cur.label} sessions found`:"No sessions found",nav=views.length>1?[["\u2190\u2192","filter"]]:[],sub2=visible2[sel]?.indent||(visible2[sel]?.row.detail?.subagent_count??0)>0?[[keys.print("list.toggle"),visible2[sel]?.indent||open2===visible2[sel]?.row.id?"hide subs":"show subs"]]:[];return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Search Results (${results.length})`:`Sessions (${listed.length}${pending3?"\u2026":""})`,error:warn||null,grow:3,children:[searching?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,empty?$jsx("box",{flexGrow:1,padding:2,children:pending3&&!searching?$jsx(Spinner,{color:theme.textMuted,label:"loading sessions\u2026"}):$jsx("text",{fg:theme.textMuted,children:searching?"No matching sessions found":"No sessions found"})},"empty"):$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[searching?$jsx(SearchHeaderRow,{}):$jsx(HeaderRow,{sort,onSort:setSort}),$jsx("box",{height:1}),$jsxs("scrollbox",{ref:vscroll,scrollY:!0,viewportCulling:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:[searching?results.map((r,i)=>$jsx(SearchItem,{id:rowId(i),idx:i,result:r,selected:i===searchSel,onActivate:rowActivate,onHover:rowHover},r.session_id)):visible2.map((v2,i)=>$jsxs("box",{flexDirection:"column",height:1+(top(i)?1:0)+(tabs(i)?2:0)+(gap(i)?1:0),children:[top(i)?$jsx("box",{height:1,paddingLeft:2,children:$jsx("text",{fg:theme.primary,children:active.length===1?"Active Session":"Active Sessions"})}):null,gap(i)?$jsx("box",{height:1}):null,tabs(i)?$jsxs($Fragment,{children:[$jsx(FilterRow,{views,view:chosen,setView}),$jsx("box",{height:1})]}):null,$jsx(Item,{id:rowId(i),idx:i,row:v2.row,selected:i===sel,indent:v2.indent,onActivate:rowActivate,onHover:rowHover,onDelete:rowDelete})]},`${v2.row.id}-${v2.indent?"c":"p"}`)),!searching&&views.length>0&&hist.length===0?$jsxs("box",{flexDirection:"column",height:3+(active.length>0?1:0),children:[active.length>0?$jsx("box",{height:1}):null,$jsx(FilterRow,{views,view:chosen,setView}),$jsx("box",{height:1}),$jsx("box",{height:1,paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:blank})})]},"sessions-empty-filter"):null]})]},"table")]}),showDetailPanel&&searching&&results[searchSel]?$jsx(SearchDetail,{result:results[searchSel]}):showDetailPanel&&!searching&&visible2[sel]?.row?$jsx(Detail,{row:visible2[sel].row,lineage:io2.lineage,peek:io2.peek,onSwitch:lineageSwitch}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter/click","switch"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],...nav,...sub2,[`${keys.print("list.activate")}/click`,action],[keys.print("list.search"),"search"],[keys.print("sessions.sort"),`sort: ${sort}`],[keys.print("sessions.rename"),"rename"],[keys.print("list.delete"),"delete"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react57=__toESM(require_react_production(),1);var GRID=256,CPT=4,MEMORY_IDS=new Set(["soul","memory","user","mem0"]),SYSTEM_PROMPT_IDS=new Set(["project","meta","other"]);function parse4(text3){if(!text3)return[];let sections=[],used=Array(text3.length).fill(!1),mark2=(start2,end,id,label2,source)=>{let slice=text3.slice(start2,end);if(slice.trim().length===0)return;for(let i=start2;i<end;i++)used[i]=!0;sections.push({id,label:label2,chars:slice.length,tokens:count2(slice),text:slice,source})},bar1=text3.indexOf("\u2550\u2550\u2550\u2550\u2550\u2550");if(bar1>0)mark2(0,bar1,"soul","SOUL.md",makeSource("SOUL.md"));let memH=text3.indexOf("MEMORY (your personal notes)");if(memH>=0){let s=text3.lastIndexOf("\u2550\u2550\u2550\u2550\u2550\u2550",memH),after=text3.indexOf(`
4123
4126
  `,text3.indexOf("\u2550\u2550\u2550\u2550\u2550\u2550",memH+1)),next=text3.indexOf("\u2550\u2550\u2550\u2550\u2550\u2550",after>0?after:memH+40),e=next>0?text3.lastIndexOf(`
4124
4127
  `,next)+1:text3.length;if(s>=0)mark2(s,e,"memory","Memory Notes",makeSource("memories/MEMORY.md","MEMORY.md"))}let userH=text3.indexOf("USER PROFILE (who the user is)");if(userH>=0){let s=text3.lastIndexOf("\u2550\u2550\u2550\u2550\u2550\u2550",userH),after=text3.indexOf(`
4125
4128
  `,text3.indexOf("\u2550\u2550\u2550\u2550\u2550\u2550",userH+1)),next=text3.slice(after>0?after:userH+40).search(/\n#\s/),e=next>=0?(after>0?after:userH+40)+next+1:text3.length;if(s>=0)mark2(s,e,"user","User Profile",makeSource("memories/USER.md","USER.md"))}let m0=text3.indexOf("# Mem0 Memory");if(m0>=0){let next=text3.slice(m0+1).search(/\n##?\s/);mark2(m0,next>=0?m0+1+next+1:text3.length,"mem0","Mem0 Memory")}let skH=text3.indexOf("## Skills (mandatory)"),skE=text3.indexOf("</available_skills>");if(skH>=0&&skE>=0){let end=text3.indexOf(`
@@ -4140,7 +4143,7 @@ The child returns whatever partial result it has so far.`,yes:"interrupt",danger
4140
4143
  WHERE task_id = ? AND summary IS NOT NULL AND summary != ''
4141
4144
  ORDER BY id DESC LIMIT 1`).get(id)?.summary??null}catch{return null}};function tailLogOf(s,id,bytes=16384){let path7=`${logsDir(s)}/${id}.log`;if(!existsSync15(path7))return null;try{let size=statSync7(path7).size,want=Math.min(size,bytes),fd=openSync2(path7,"r"),buf=Buffer.alloc(want);readSync2(fd,buf,0,want,size-want),closeSync2(fd);let out=buf.toString("utf-8");if(size>bytes){let nl=out.indexOf(`
4142
4145
  `);if(nl>=0&&nl<out.length-1)out=out.slice(nl+1)}return out}catch{return null}}function assignees(s=slug){let seen=new Set,dir=kp("profiles");if(existsSync15(dir)){for(let e of readdirSync7(dir,{withFileTypes:!0}))if(e.isDirectory())seen.add(e.name)}let conn2=dbOf(s);if(conn2)try{for(let r of conn2.query("SELECT DISTINCT assignee FROM tasks WHERE assignee IS NOT NULL AND status != 'archived'").all())seen.add(r.assignee)}catch{}return[...seen].sort()}function checkFileLength(conn2){try{let row3=conn2.query("PRAGMA database_list").get(),path7=String(row3?.file??row3?.[2]??"");if(!path7)return;let pageRow=conn2.query("PRAGMA page_size").get(),pageSize=Number(Object.values(pageRow??{})[0]);if(!pageSize)return;let fd=openSync2(path7,"r");try{let buf=Buffer.alloc(4);if(readSync2(fd,buf,0,4,28)<4)return;let headerPages=buf.readUInt32BE(0);if(!headerPages)return;let actualPages=Math.floor(fstatSync(fd).size/pageSize);if(actualPages<headerPages)throw Error(`torn-extend detected: page count mismatch on ${path7}: header claims ${headerPages} pages, file has ${actualPages} pages`)}finally{closeSync2(fd)}}catch(err){if(err instanceof Error&&err.message.startsWith("torn-extend detected"))throw err}}function writeTxn(conn2,fn){conn2.exec("BEGIN IMMEDIATE");try{let out=fn();return conn2.exec("COMMIT"),checkFileLength(conn2),out}catch(err){try{conn2.exec("ROLLBACK")}catch{}throw err}}var now=()=>Math.floor(Date.now()/1000);function patchTask(s,id,patch){let conn2=rwOf(s);if(!conn2)return!1;if(!conn2.query("SELECT 1 FROM tasks WHERE id = ?").get(id))return!1;if(patch.priority!==void 0){let p=Math.max(0,Math.min(9,Math.floor(patch.priority)));writeTxn(conn2,()=>{conn2.query("UPDATE tasks SET priority = ? WHERE id = ?").run(p,id),conn2.query("INSERT INTO task_events (task_id, run_id, kind, payload, created_at) VALUES (?, NULL, 'reprioritized', ?, ?)").run(id,JSON.stringify({priority:p}),now())})}if(patch.title!==void 0||patch.body!==void 0){let sets=[],vals=[];if(patch.title!==void 0){let t2=patch.title.trim();if(!t2)throw Error("title cannot be empty");sets.push("title = ?"),vals.push(t2)}if(patch.body!==void 0)sets.push("body = ?"),vals.push(patch.body);vals.push(id),writeTxn(conn2,()=>{conn2.query(`UPDATE tasks SET ${sets.join(", ")} WHERE id = ?`).run(...vals),conn2.query("INSERT INTO task_events (task_id, run_id, kind, payload, created_at) VALUES (?, NULL, 'edited', NULL, ?)").run(id,now())})}return!0}var q3=(s)=>/^[A-Za-z0-9._\/:+=-]+$/.test(s)?s:`'${s.replace(/'/g,"'\\''")}'`;var import_react78=__toESM(require_react_production(),1);function openCreateTask(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form2,{pool:opts.assignees,parent:opts.parent,done}),void 0,{ownCancel:!0})})}var CORE=["title","body","assignee","priority","triage","more"],MORE=["tenant","workspace","maxRuntime","skills"],SELECTY=new Set(["assignee","priority","workspace"]),MAX_RUNTIME_RE=/^\d+[smhd]?$/,SKILL_MATCHES_MAX=6,wsLabel=(w2)=>w2.kind==="scratch"?"scratch":w2.kind==="worktree"?"worktree":`dir @ ${w2.path}`,Form2=(p)=>{let theme=useTheme().theme,gw=useGateway(),body=import_react78.useRef(null),[bodyText,setBodyText]=import_react78.useState(""),[field,setField]=import_react78.useState("title"),[more,setMore]=import_react78.useState(!1),[picker,setPicker]=import_react78.useState(null),[title,setTitle]=import_react78.useState(""),[assignee,setAssignee]=import_react78.useState(null),[priority,setPriority]=import_react78.useState(0),[triage,setTriage]=import_react78.useState(!1),[tenant,setTenant]=import_react78.useState(""),[workspace,setWorkspace]=import_react78.useState({kind:"scratch"}),[maxRuntime,setMaxRuntime]=import_react78.useState(""),[catalog3,setCatalog]=import_react78.useState([]),[skills,setSkills]=import_react78.useState([]),[filter,setFilter]=import_react78.useState(""),[matchIdx,setMatchIdx]=import_react78.useState(0);import_react78.useEffect(()=>{let live=!0;return gw.request("skills.manage",{action:"list"}).then((r)=>{if(!live)return;let raw=r.skills??{},out=[];for(let cat of Object.keys(raw))for(let name of raw[cat]??[])out.push({cat,name});out.sort((a,b2)=>a.name.localeCompare(b2.name)),setCatalog(out)}).catch(()=>{}),()=>{live=!1}},[gw]);let matches=import_react78.useMemo(()=>{if(!filter.trim())return[];let q4=filter.trim().toLowerCase(),picked=new Set(skills),hits=[];for(let s of catalog3){if(picked.has(s.name))continue;if(s.name.toLowerCase().includes(q4)||s.cat.toLowerCase().includes(q4))hits.push(s);if(hits.length>=SKILL_MATCHES_MAX)break}return hits},[catalog3,filter,skills]);import_react78.useEffect(()=>{if(matchIdx>0&&matchIdx>=matches.length)setMatchIdx(Math.max(0,matches.length-1))},[matches.length,matchIdx]);let order=()=>more?[...CORE,...MORE]:CORE,titleOk=title.trim().length>0,runtimeOk=maxRuntime.trim()===""||MAX_RUNTIME_RE.test(maxRuntime.trim()),valid=titleOk&&runtimeOk,submit2=()=>{if(!valid)return;p.done({title:title.trim(),body:(body.current?.plainText??bodyText).trim(),assignee,priority,parent:p.parent?.id??null,triage,tenant:tenant.trim()||null,workspace,maxRuntime:maxRuntime.trim()||null,skills})},moveField=(dir)=>{let o=order(),i=o.indexOf(field),next2=o[(i+dir+o.length)%o.length];setField(next2)},openPicker=()=>{if(field==="assignee")return setPicker({kind:"assignee"});if(field==="priority")return setPicker({kind:"priority"});if(field==="workspace")return setPicker({kind:"workspace"})},commitMatch=()=>{let hit=matches[matchIdx];if(!hit)return!1;return setSkills((s)=>s.includes(hit.name)?s:[...s,hit.name]),setFilter(""),setMatchIdx(0),!0},popSkill=()=>setSkills((s)=>s.slice(0,-1));if(useKeyboard((key3)=>{if(picker){if(key3.name==="escape")setPicker(picker.kind==="dirPath"?{kind:"workspace"}:null);return}if(key3.name==="escape")return p.done(null);if(key3.name==="return"){if(key3.ctrl)return submit2();if(field!=="body")return submit2();return}if(field==="skills"){if(key3.name==="tab"){if(!key3.shift&&commitMatch())return;return moveField(key3.shift?-1:1)}if(key3.name==="backspace"){if(filter.length>0)return setFilter((f)=>f.slice(0,-1));return popSkill()}if(key3.name==="up"){if(matches.length>0)return setMatchIdx((i)=>Math.max(0,i-1));return moveField(-1)}if(key3.name==="down"){if(matches.length>0)return setMatchIdx((i)=>Math.min(matches.length-1,i+1));return moveField(1)}if(key3.raw&&key3.raw.length===1&&/[A-Za-z0-9_\-/ ]/.test(key3.raw))setFilter((f)=>f+key3.raw),setMatchIdx(0);return}if(key3.name==="tab")return moveField(key3.shift?-1:1);if(key3.name==="up"){if(field==="body"){if((body.current?.logicalCursor.row??0)>0)return}return moveField(-1)}if(key3.name==="down"){if(field==="body"){let row3=body.current?.logicalCursor.row??0,last3=(body.current?.lineCount??1)-1;if(row3<last3)return}return moveField(1)}if(field==="more"){if(key3.name==="return"||key3.name==="space")return setMore((m2)=>!m2);return}if(field==="triage"&&key3.name==="space")return setTriage((t2)=>!t2);if(SELECTY.has(field)&&key3.name==="space")return openPicker()}),picker?.kind==="assignee"){let opts=[{title:"(unassigned)",value:""},...p.pool.map((n)=>({title:n,value:n}))];return $jsx(DialogSelect,{title:"Assignee",options:opts,placeholder:"Search profiles\u2026",current:assignee??"",onSelect:(o)=>{setAssignee(o.value||null),setPicker(null)}})}if(picker?.kind==="priority"){let opts=Array.from({length:10},(_2,n)=>({title:n===0?"P0 (none)":`P${n}`,value:String(n),description:n===0?"default":n<=2?"normal":n<=5?"elevated":"high"}));return $jsx(DialogSelect,{title:"Priority",options:opts,filterable:!1,current:String(priority),onSelect:(o)=>{setPriority(Number(o.value)),setPicker(null)}})}if(picker?.kind==="workspace")return $jsx(DialogSelect,{title:"Workspace",options:[{title:"scratch",value:"scratch",description:"isolated temp dir under the board root (default)"},{title:"worktree",value:"worktree",description:"git worktree at .worktrees/<task-id> \u2014 worker runs `git worktree add`"},{title:"dir:\u2026",value:"dir",description:"an exact absolute path (prompts next)"}],filterable:!1,current:workspace.kind,onSelect:(o)=>{if(o.value==="scratch")return setWorkspace({kind:"scratch"}),setPicker(null);if(o.value==="worktree")return setWorkspace({kind:"worktree"}),setPicker(null);return setPicker({kind:"dirPath",value:workspace.kind==="dir"?workspace.path:""})}});if(picker?.kind==="dirPath"){let val=picker.value,ok=val.trim().length>0&&val.trim().startsWith("/");return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Directory path"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"absolute path (required)"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value:val,onInput:(v2)=>setPicker({kind:"dirPath",value:v2}),onSubmit:()=>{if(!ok)return;setWorkspace({kind:"dir",path:val.trim()}),setPicker(null)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement},"dirpath")})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:ok?"Enter confirm \xB7 Esc back":"absolute path required \xB7 Esc back"})})]})}let lbl=(f,text3)=>$jsx("box",{width:13,flexShrink:0,children:$jsxs("text",{fg:field===f?theme.accent:theme.textMuted,children:[field===f?"\u25B8 ":" ",text3]})}),textRow=(f,label2,value,set2,placeholder)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label2),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:set2,onSubmit:submit2,focused:field===f,placeholder,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field===f?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement},`field-${f}`)})]}),valRow=(f,label2,value,hint)=>$jsxs("box",{height:1,flexDirection:"row",children:[lbl(f,label2),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.text,children:value})}),field===f?$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]}),skillsRows=()=>{let focused=field==="skills",empty=skills.length===0&&!focused;return $jsxs($Fragment,{children:[$jsxs("box",{height:1,flexDirection:"row",children:[lbl("skills","Skills"),$jsxs("box",{flexGrow:1,minWidth:0,height:1,flexDirection:"row",overflow:"hidden",children:[skills.map((n)=>$jsx(FilterChip,{label:n,state:"in",gap:0},n)),empty?$jsx("text",{fg:theme.textMuted,children:"(none \u2014 focus field to pick)"}):$jsxs("box",{flexDirection:"row",marginLeft:skills.length>0?1:0,children:[$jsx("text",{fg:theme.text,children:filter}),focused?$jsx("text",{fg:theme.accent,children:"\u2588"}):null]})]})]}),focused&&matches.length>0?$jsx("box",{flexDirection:"column",children:matches.map((s,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:i===matchIdx?theme.accent:theme.textMuted,children:i===matchIdx?" \u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:i===matchIdx?theme.accent:theme.text,children:s.name}),$jsx("span",{fg:theme.textMuted,children:` ${s.cat}`})]})})]},`${s.cat}/${s.name}`))}):null]})},footer=!valid?!titleOk?"type a title":"fix runtime (e.g. 30m, 2h, 1800)":field==="body"?"Ctrl+Enter create \xB7 Tab leave \xB7 \u2191\u2193 cursor \xB7 Esc cancel":field==="more"?`Space ${more?"collapse":"expand"} \xB7 Ctrl+Enter create \xB7 \u2191\u2193/Tab \xB7 Esc`:field==="skills"?(()=>{if(matches.length>0)return"Tab add \xB7 \u2191\u2193 pick \xB7 Bksp remove \xB7 Enter create \xB7 Esc";if(skills.length>0)return"type to filter \xB7 Bksp remove last \xB7 Enter create \xB7 \u2191\u2193/Tab \xB7 Esc";return"type to filter \xB7 Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc cancel"})():SELECTY.has(field)?"Space pick \xB7 Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc cancel":field==="triage"?"Space toggle \xB7 Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc":"Enter create \xB7 \u2191\u2193/Tab field \xB7 Esc cancel";return $jsxs("box",{flexDirection:"column",width:66,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:p.parent?`New Task \xB7 child of ${p.parent.id}`:"New Task"})})}),p.parent?$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[" ",p.parent.title]})}):null,$jsx("box",{height:1}),textRow("title","Title",title,setTitle,"one-line summary"),$jsxs("box",{flexDirection:"row",children:[lbl("body","Body"),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("textarea",{ref:body,initialValue:bodyText,onContentChange:()=>{if(body.current)setBodyText(body.current.plainText)},focused:field==="body",placeholder:"longer spec \u2014 markdown ok (Enter for newline)",textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field==="body"?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement,minHeight:5,maxHeight:5},"field-body")})]}),valRow("assignee","Assignee",assignee??"(unassigned)","Space pick \u25BE"),valRow("priority","Priority",priority?`P${priority}`:"P0 (none)","Space pick \u25BE"),valRow("triage","Triage",triage?"yes \u2014 park for a specifier":"no","Space toggle"),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsxs("text",{fg:field==="more"?theme.accent:theme.textMuted,children:[field==="more"?"\u25B8 ":" ",more?"More \u25BE":"More \u25B8"]})}),!more?$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:"tenant \xB7 workspace \xB7 runtime \xB7 skills"})}):null]}),more?textRow("tenant","Tenant",tenant,setTenant,"namespace (optional)"):null,more?valRow("workspace","Workspace",wsLabel(workspace),"Space pick \u25BE"):null,more?textRow("maxRuntime","Runtime",maxRuntime,setMaxRuntime,"e.g. 30m, 2h, 1800 (optional)"):null,more?skillsRows():null,$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:footer})})]})};var arr=(v2)=>Array.isArray(v2)?v2:[],str2=(v2)=>typeof v2==="string"?v2:"",num3=(v2)=>typeof v2==="number"&&Number.isFinite(v2)?v2:0,ids=(v2)=>arr(v2).map(str2).filter(Boolean),spawned=(v2)=>arr(v2).flatMap((x2)=>{if(!x2||typeof x2!=="object")return[];let r=x2,task_id=str2(r.task_id);if(!task_id)return[];return[{task_id,assignee:str2(r.assignee),workspace:str2(r.workspace)}]}),capped=(v2)=>arr(v2).flatMap((x2)=>{if(!x2||typeof x2!=="object")return[];let r=x2,task_id=str2(r.task_id);if(!task_id)return[];return[{task_id,assignee:str2(r.assignee),current:num3(r.current)}]}),guarded=(v2)=>arr(v2).flatMap((x2)=>{if(Array.isArray(x2)){let task_id2=str2(x2[0]);if(!task_id2)return[];return[{task_id:task_id2,reason:str2(x2[1])}]}if(!x2||typeof x2!=="object")return[];let r=x2,task_id=str2(r.task_id);if(!task_id)return[];return[{task_id,reason:str2(r.reason)}]}),parseDispatchResult=(out)=>{let raw=JSON.parse(out);return{reclaimed:num3(raw.reclaimed),promoted:num3(raw.promoted),spawned:spawned(raw.spawned),skipped_unassigned:ids(raw.skipped_unassigned),skipped_nonspawnable:ids(raw.skipped_nonspawnable),skipped_per_profile_capped:capped(raw.skipped_per_profile_capped),auto_assigned_default:ids(raw.auto_assigned_default),crashed:ids(raw.crashed),auto_blocked:ids(raw.auto_blocked),timed_out:ids(raw.timed_out),stale:ids(raw.stale),respawn_guarded:guarded(raw.respawn_guarded)}},dispatchFailures=(r)=>[...r.crashed,...r.auto_blocked,...r.timed_out,...r.stale],dispatchGuarded=(r)=>r.respawn_guarded.map((x2)=>x2.task_id),dispatchVariant=(r)=>{let failed=dispatchFailures(r).length,guarded2=dispatchGuarded(r).length,unassigned=r.skipped_unassigned.length,benign=r.skipped_per_profile_capped.length+r.skipped_nonspawnable.length;if(r.spawned.length===0&&(failed>0||unassigned>0))return"error";if(failed>0||guarded2>0||unassigned>0)return"warning";if(benign>0)return"info";return"success"},line2=(label2,xs)=>xs.length?[`${label2}: ${xs.join(", ")}`]:[],caps=(r)=>{let map=r.skipped_per_profile_capped.reduce((m2,x2)=>{let key3=x2.assignee||"unassigned";return m2.set(key3,[...m2.get(key3)??[],x2]),m2},new Map);if(map.size===0)return[];return["Deferred at per-profile cap:",...[...map.entries()].map(([k2,xs])=>` ${k2} (${Math.max(...xs.map((x2)=>x2.current))} running): ${xs.map((x2)=>x2.task_id).join(", ")}`)]},dispatchDetails=(r)=>[...line2("Defaulted to kanban.default_assignee",r.auto_assigned_default),...caps(r),...line2("Unassigned",r.skipped_unassigned),...line2("Non-spawnable lanes",r.skipped_nonspawnable),...line2("Failed/reclaimed \xB7 crashed",r.crashed),...line2("Failed/reclaimed \xB7 auto-blocked",r.auto_blocked),...line2("Failed/reclaimed \xB7 timed out",r.timed_out),...line2("Failed/reclaimed \xB7 stale",r.stale),...line2("Respawn guarded",r.respawn_guarded.map((x2)=>`${x2.task_id}${x2.reason?` (${x2.reason})`:""}`))].join(`
4143
- `);var NOBAR={visible:!1},RULE=["bottom"],HEAD={triage:"triage",todo:"todo",scheduled:"scheduled",ready:"ready",running:"running",blocked:"blocked",done:"done"},EMPTY2={who:new Map,pri:new Map,status:new Map},EMPTY_DIAG=new Map,EMPTY_DIAGS=[],chipId=(c)=>c.kind==="who"?`who:${c.v}`:c.kind==="pri"?`pri:${c.v}`:`st:${c.v}`,chipLabel=(c)=>c.kind==="who"?c.v:c.kind==="pri"?`P${c.v}`:HEAD[c.v],triOf=(c,m2)=>c.kind==="who"?m2.who.get(c.v)??"off":c.kind==="pri"?m2.pri.get(c.v)??"off":m2.status.get(c.v)??"off",recOf=(v2)=>v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:null,assignedByDefault=(d2)=>d2.events.some((e)=>e.kind==="assigned"&&recOf(e.payload)?.source==="kanban.default_assignee");function admits(g,v2){let t2=g.get(v2);if(t2==="ex")return!1;if(t2==="in")return!0;for(let s of g.values())if(s==="in")return!1;return!0}var pass=(t2,m2)=>admits(m2.who,t2.assignee??null)&&admits(m2.pri,t2.priority),indexDiags=(rows3)=>{let out=new Map;for(let r of rows3)if(r.diagnostics.length>0)out.set(r.task_id,sortDiags(r.diagnostics));return out},maskFromPrefs=(raw)=>{let out=new Map;if(!raw)return out;for(let slug2 of Object.keys(raw)){let g=raw[slug2];out.set(slug2,{who:new Map(g.who??[]),pri:new Map(g.pri??[]),status:new Map(g.status??[])})}return out},maskToPrefs=(masks)=>{let out={};for(let[slug2,m2]of masks){let filt=(xs)=>xs.filter(([,t2])=>t2==="in"||t2==="ex"),who=filt([...m2.who]),pri=filt([...m2.pri]),status=filt([...m2.status]);if(who.length||pri.length||status.length)out[slug2]={who,pri,status}}return out},persist=(masks,open2)=>{let cur=load2().kanban??{};set("kanban",{...cur,open:[...open2],masks:maskToPrefs(masks)})},SEV_GLYPH={warning:"\u26A0",error:"!!",critical:"\u203C"},sevColor=(sev,theme)=>sev==="warning"?theme.warning:theme.error,Card=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{id:p.id,height:2,flexDirection:"row",paddingLeft:1,border:RULE,borderStyle:"single",borderColor:theme.borderSubtle,backgroundColor:p.on?theme.backgroundElement:void 0,onMouseDown:p.onPick,onMouseMove:p.onHover,children:$jsxs(Ticker,{active:p.on||p.hov,fg:p.on?theme.accent:theme.text,children:[p.sev?$jsxs($Fragment,{children:[$jsx("span",{fg:sevColor(p.sev,theme),children:SEV_GLYPH[p.sev]})," "]}):null,p.t.title]})})}),Column=import_react80.memo((p)=>{let theme=useTheme().theme,box=import_react80.useRef(null),[hov,setHov]=import_react80.useState(-1),id=(i)=>`kb-${p.slug}-${p.status}-${i}`;import_react80.useEffect(()=>{if(p.on&&p.tasks.length>0)box.current?.scrollChildIntoView(id(p.sel))},[p.on,p.sel,p.tasks.length]);let tint=p.status==="blocked"?theme.warning:p.status==="running"?theme.success:p.status==="scheduled"?theme.textMuted:p.status==="done"?theme.textMuted:theme.primary;return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:18,border:!0,borderColor:p.on?theme.primary:theme.border,onMouseOut:()=>setHov(-1),children:[$jsx("box",{height:1,paddingLeft:1,children:$jsxs("text",{children:[$jsx("span",{fg:tint,children:$jsx("strong",{children:HEAD[p.status]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.tasks.length}`})]})}),$jsx("scrollbox",{id:`kb-col-${p.slug}-${p.status}`,ref:box,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,onMouseScroll:(e)=>e.stopPropagation(),children:$jsx("box",{flexDirection:"column",width:"100%",children:p.tasks.map((t2,i)=>$jsx(Card,{id:id(i),t:t2,on:p.on&&i===p.sel,hov:i===hov,sev:maxSeverity(p.diags.get(t2.id)??[]),onHover:()=>{if(hov!==i)setHov(i)},onPick:()=>p.onPick(i)},t2.id))})})]})}),ErrorBanner=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",marginLeft:2,marginBottom:1,paddingLeft:1,border:!0,borderColor:theme.error,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:$jsxs("strong",{children:["Kanban DB ",p.error.kind]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.error.path}`})]})}),$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.error.message}),p.backups.length>0?$jsx("text",{wrapMode:"word",fg:theme.warning,children:`quarantine backup${p.backups.length===1?"":"s"}: ${p.backups.join(", ")}`}):null]})}),FilterBar=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,flexDirection:"row",flexWrap:"no-wrap",overflow:"hidden",marginBottom:1,children:p.chips.flatMap((c,i)=>{let chip2=$jsx(FilterChip,{label:chipLabel(c),state:triOf(c,p.mask),selected:p.on&&i===p.sel,onMouseDown:()=>p.onPick(i)},chipId(c));if(i===0||p.chips[i-1].kind===c.kind)return[chip2];return[$jsx("box",{height:1,flexShrink:0,marginLeft:1,children:$jsx("text",{fg:theme.borderSubtle,children:"|"})},`sep:${chipId(c)}`),chip2]})})}),FIELDS=["title","body","assignee","priority","status","parents","result","comment"],fieldsFor=(t2)=>FIELDS.filter((f)=>{if(f==="result")return t2.status==="done";return!0}),SidePane=import_react80.memo((p)=>{let{theme,syntaxStyle}=useTheme();if(p.pane.kind==="log"||p.pane.kind==="dispatch")return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:p.pane.kind==="log"?p.pane.id:"Dispatch"})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${p.pane.kind==="log"?"worker log (tail)":"details"}`})]})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.pane.text||"(empty)"})})]});let d2=p.pane.d,fields=fieldsFor(d2),cur=p.on?fields[Math.min(p.sel,fields.length-1)]:null,srow=(f,label2,value,hint)=>{let active=cur===f;return $jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:active?theme.text:theme.textMuted,children:value})}),hint?$jsx("box",{flexShrink:0,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]},f)},mrow=(f,label2,content,hint)=>{let active=cur===f;return $jsxs("box",{flexDirection:"column",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),hint?$jsx("box",{flexGrow:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]}),$jsx("box",{paddingLeft:10,flexShrink:0,children:content})]},f)},resultText=d2.result||d2.latest_summary||"",sizeText=(n)=>n===null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:d2.id})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${d2.status} \xB7 ${ago(d2.updated_at)}`})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[srow("title","Title",d2.title,p.on&&cur==="title"?"Enter edit":void 0),mrow("body","Body",d2.body?cur==="body"?$jsx("text",{wrapMode:"word",fg:theme.text,children:d2.body}):$jsx("markdown",{content:d2.body,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="body"?"Enter edit (raw)":void 0),srow("assignee","Assignee",d2.assignee?assignedByDefault(d2)?`${d2.assignee} (default)`:d2.assignee:"\u2014",p.on&&cur==="assignee"?"Enter pick":void 0),srow("priority","Priority",d2.priority?`P${d2.priority}`:"\u2014",p.on&&cur==="priority"?"Enter select":void 0),srow("status","Status",d2.status,p.on&&cur==="status"?"Enter change":void 0),srow("parents","Parents",d2.parents.length?d2.parents.join(", "):"\u2014",p.on&&cur==="parents"?"Enter add/remove":void 0),d2.children.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Children"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.children.join(", ")})})]}):null,d2.workspace_kind?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Workspace"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,children:[d2.workspace_kind,d2.workspace_path?` @ ${d2.workspace_path}`:""]})})]}):null,d2.branch_name?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Branch"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.branch_name})})]}):null,d2.skills.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Skills"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.skills.join(", ")})})]}):null,d2.model_override?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Model"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.model_override})})]}):null,d2.max_retries!==null?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Retries"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.max_retries)})})]}):null,d2.pid?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"PID"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.pid)})})]}):null,d2.last_heartbeat_at&&d2.status==="running"?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Heartbeat"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:ago(d2.last_heartbeat_at)})})]}):null,d2.session_id?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Session"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.session_id})})]}):null,d2.attachments.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Attachments (${d2.attachments.length})`})}),d2.attachments.map((a)=>{let source=a.path?{file:a.path,relative:a.relative_path??a.path,label:a.name}:null;return $jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${a.id} `}),$jsx("span",{fg:theme.text,children:a.name}),$jsx("span",{fg:theme.textMuted,children:` ${sizeText(a.size)} ${ago(a.created_at)}`})]})}),source?$jsx("box",{height:1,overflow:"hidden",children:$jsx(FileLink,{source,children:source.relative})}):$jsx("text",{wrapMode:"word",fg:theme.error,children:`unsafe path omitted: ${a.stored_path}`})]},a.id)})]}):null,d2.error?$jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:"Error"})}),$jsx("box",{paddingLeft:2,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:d2.error})})]}):null,d2.status==="done"?mrow("result","Result",resultText?cur==="result"?$jsx("text",{wrapMode:"word",fg:theme.text,children:resultText}):$jsx("markdown",{content:resultText,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="result"?"Enter edit":void 0):null,p.diags.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"Diagnostics "}),$jsx("span",{fg:sevColor(p.diags[0].severity,theme),children:`(${p.diags.length})`})]})}),p.diags.map((dx,i)=>$jsxs("box",{flexDirection:"column",marginTop:i===0?0:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:sevColor(dx.severity,theme),children:SEV_GLYPH[dx.severity]}),$jsx("span",{fg:theme.text,children:` [${dx.severity}] ${dx.kind}`}),dx.count>1?$jsx("span",{fg:theme.textMuted,children:` \xD7${dx.count}`}):null]})}),$jsxs("box",{paddingLeft:2,flexDirection:"column",children:[$jsx("text",{wrapMode:"word",fg:theme.text,children:dx.title}),dx.detail?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:dx.detail}):null,dx.actions.map((a,j2)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:a.suggested?theme.accent:theme.textMuted,children:a.suggested?"\u2192 ":"\xB7 "}),$jsx("span",{fg:a.suggested?theme.text:theme.textMuted,children:a.label})]})},j2))]})]},`${dx.kind}-${i}`))]}):null,d2.runs.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Runs (${d2.runs.length})`})}),d2.runs.map((r)=>{let outcome=r.outcome||r.status||(r.ended_at?"ended":"active"),elapsed=r.ended_at?`${Math.max(0,r.ended_at-r.started_at)}s`:"active";return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${r.id} `}),$jsx("span",{fg:theme.text,children:outcome}),$jsx("span",{fg:theme.textMuted,children:` @${r.profile??"-"} ${elapsed} ${ago(r.started_at)}`})]})}),r.summary?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:` \u2192 ${r.summary.split(`
4146
+ `);var NOBAR={visible:!1},RULE=["bottom"],HEAD={triage:"triage",todo:"todo",scheduled:"scheduled",ready:"ready",running:"running",blocked:"blocked",done:"done"},EMPTY2={who:new Map,pri:new Map,status:new Map},EMPTY_DIAG=new Map,EMPTY_DIAGS=[],chipId=(c)=>c.kind==="who"?`who:${c.v}`:c.kind==="pri"?`pri:${c.v}`:`st:${c.v}`,chipLabel=(c)=>c.kind==="who"?c.v:c.kind==="pri"?`P${c.v}`:HEAD[c.v],triOf=(c,m2)=>c.kind==="who"?m2.who.get(c.v)??"off":c.kind==="pri"?m2.pri.get(c.v)??"off":m2.status.get(c.v)??"off",recOf=(v2)=>v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:null,assignedByDefault=(d2)=>d2.events.some((e)=>e.kind==="assigned"&&recOf(e.payload)?.source==="kanban.default_assignee");function admits(g,v2){let t2=g.get(v2);if(t2==="ex")return!1;if(t2==="in")return!0;for(let s of g.values())if(s==="in")return!1;return!0}var pass=(t2,m2)=>admits(m2.who,t2.assignee??null)&&admits(m2.pri,t2.priority),indexDiags=(rows3)=>{let out=new Map;for(let r of rows3)if(r.diagnostics.length>0)out.set(r.task_id,sortDiags(r.diagnostics));return out},maskFromPrefs=(raw)=>{let out=new Map;if(!raw)return out;for(let slug2 of Object.keys(raw)){let g=raw[slug2];out.set(slug2,{who:new Map(g.who??[]),pri:new Map(g.pri??[]),status:new Map(g.status??[])})}return out},maskToPrefs=(masks)=>{let out={};for(let[slug2,m2]of masks){let filt=(xs)=>xs.filter(([,t2])=>t2==="in"||t2==="ex"),who=filt([...m2.who]),pri=filt([...m2.pri]),status=filt([...m2.status]);if(who.length||pri.length||status.length)out[slug2]={who,pri,status}}return out},persist=(masks,open2)=>{let cur=load2().kanban??{};set("kanban",{...cur,open:[...open2],masks:maskToPrefs(masks)})},SEV_GLYPH={warning:"\u26A0",error:"!!",critical:"\u203C"},sevColor=(sev,theme)=>sev==="warning"?theme.warning:theme.error,Card=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{id:p.id,height:2,flexDirection:"row",paddingLeft:1,border:RULE,borderStyle:"single",borderColor:theme.borderSubtle,backgroundColor:p.on?theme.backgroundElement:void 0,onMouseDown:p.onPick,onMouseMove:p.onHover,children:$jsxs(Ticker,{active:p.on||p.hov,fg:p.on?theme.accent:theme.text,children:[p.sev?$jsxs($Fragment,{children:[$jsx("span",{fg:sevColor(p.sev,theme),children:SEV_GLYPH[p.sev]})," "]}):null,p.t.title]})})}),Column=import_react80.memo((p)=>{let theme=useTheme().theme,box=import_react80.useRef(null),[hov,setHov]=import_react80.useState(-1),id=(i)=>`kb-${p.slug}-${p.status}-${i}`;import_react80.useEffect(()=>{if(p.on&&p.tasks.length>0)box.current?.scrollChildIntoView(id(p.sel))},[p.on,p.sel,p.tasks.length]);let tint=p.status==="blocked"?theme.warning:p.status==="running"?theme.success:p.status==="scheduled"?theme.textMuted:p.status==="done"?theme.textMuted:theme.primary;return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:18,border:!0,borderColor:p.on?theme.primary:theme.border,onMouseOut:()=>setHov(-1),children:[$jsx("box",{height:1,paddingLeft:1,children:$jsxs("text",{children:[$jsx("span",{fg:tint,children:$jsx("strong",{children:HEAD[p.status]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.tasks.length}`})]})}),$jsx("scrollbox",{id:`kb-col-${p.slug}-${p.status}`,ref:box,scrollY:!0,flexGrow:1,verticalScrollbarOptions:NOBAR,onMouseScroll:(e)=>e.stopPropagation(),children:$jsx("box",{flexDirection:"column",width:"100%",children:p.tasks.map((t2,i)=>$jsx(Card,{id:id(i),t:t2,on:p.on&&i===p.sel,hov:i===hov,sev:maxSeverity(p.diags.get(t2.id)??[]),onHover:()=>{if(hov!==i)setHov(i)},onPick:()=>p.onPick(i)},t2.id))})})]})}),ErrorBanner=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",marginLeft:2,marginBottom:1,paddingLeft:1,border:!0,borderColor:theme.error,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:$jsxs("strong",{children:["Kanban DB ",p.error.kind]})}),$jsx("span",{fg:theme.textMuted,children:` ${p.error.path}`})]})}),$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.error.message}),p.backups.length>0?$jsx("text",{wrapMode:"word",fg:theme.warning,children:`quarantine backup${p.backups.length===1?"":"s"}: ${p.backups.join(", ")}`}):null]})}),FilterBar=import_react80.memo((p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,flexDirection:"row",flexWrap:"no-wrap",overflow:"hidden",marginBottom:1,children:p.chips.flatMap((c,i)=>{let chip2=$jsx(FilterChip,{label:chipLabel(c),state:triOf(c,p.mask),selected:p.on&&i===p.sel,onMouseDown:()=>p.onPick(i)},chipId(c));if(i===0||p.chips[i-1].kind===c.kind)return[chip2];return[$jsx("box",{height:1,flexShrink:0,marginLeft:1,children:$jsx("text",{fg:theme.borderSubtle,children:"|"})},`sep:${chipId(c)}`),chip2]})})}),FIELDS=["title","body","assignee","priority","status","parents","result","comment"],fieldsFor=(t2)=>FIELDS.filter((f)=>{if(f==="result")return t2.status==="done";return!0}),SidePane=import_react80.memo((p)=>{let{theme,syntaxStyle}=useTheme();if(p.pane.kind==="log"||p.pane.kind==="dispatch")return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:p.pane.kind==="log"?p.pane.id:"Dispatch"})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${p.pane.kind==="log"?"worker log (tail)":"details"}`})]})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:p.pane.text||"(empty)"})})]});let d2=p.pane.d,fields=fieldsFor(d2),cur=p.on?fields[Math.min(p.sel,fields.length-1)]:null,srow=(f,label2,value,hint)=>{let active=cur===f;return $jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:active?theme.text:theme.textMuted,children:value})}),hint?$jsx("box",{flexShrink:0,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]},f)},mrow=(f,label2,content,hint)=>{let active=cur===f;return $jsxs("box",{flexDirection:"column",paddingLeft:1,backgroundColor:active?theme.backgroundElement:void 0,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:active?theme.accent:theme.textMuted,children:label2})}),hint?$jsx("box",{flexGrow:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:hint})}):null]}),$jsx("box",{paddingLeft:10,flexShrink:0,children:content})]},f)},resultText=d2.result||d2.latest_summary||"",sizeText=(n)=>n===null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:d2.id})}),$jsx("span",{fg:theme.textMuted,children:` \xB7 ${p.pane.slug} \xB7 ${d2.status} \xB7 ${ago(d2.updated_at)}`})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[srow("title","Title",d2.title,p.on&&cur==="title"?"Enter edit":void 0),mrow("body","Body",d2.body?cur==="body"?$jsx("text",{wrapMode:"word",fg:theme.text,children:d2.body}):$jsx("markdown",{content:d2.body,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="body"?"Enter edit (raw)":void 0),srow("assignee","Assignee",d2.assignee?assignedByDefault(d2)?`${d2.assignee} (default)`:d2.assignee:"\u2014",p.on&&cur==="assignee"?"Enter pick":void 0),srow("priority","Priority",d2.priority?`P${d2.priority}`:"\u2014",p.on&&cur==="priority"?"Enter select":void 0),srow("status","Status",d2.status,p.on&&cur==="status"?"Enter change":void 0),srow("parents","Parents",d2.parents.length?d2.parents.join(", "):"\u2014",p.on&&cur==="parents"?"Enter add/remove":void 0),d2.children.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Children"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.children.join(", ")})})]}):null,d2.workspace_kind?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Workspace"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,children:[d2.workspace_kind,d2.workspace_path?` @ ${d2.workspace_path}`:""]})})]}):null,d2.branch_name?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Branch"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.branch_name})})]}):null,d2.skills.length?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Skills"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.skills.join(", ")})})]}):null,d2.model_override?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Model"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.model_override})})]}):null,d2.max_retries!==null?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Retries"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.max_retries)})})]}):null,d2.pid?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"PID"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:String(d2.pid)})})]}):null,d2.last_heartbeat_at&&d2.status==="running"?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Heartbeat"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:ago(d2.last_heartbeat_at)})})]}):null,d2.session_id?$jsxs("box",{height:1,flexDirection:"row",paddingLeft:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:"Session"})}),$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:d2.session_id})})]}):null,d2.attachments.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Attachments (${d2.attachments.length})`})}),d2.attachments.map((a)=>{let source=a.path?{file:a.path,relative:a.relative_path??a.path,label:a.name}:null;return $jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${a.id} `}),$jsx("span",{fg:theme.text,children:a.name}),$jsx("span",{fg:theme.textMuted,children:` ${sizeText(a.size)} ${ago(a.created_at)}`})]})}),source?$jsx("box",{height:1,overflow:"hidden",children:$jsx(FileLink,{source,children:source.relative})}):$jsx("text",{wrapMode:"word",fg:theme.error,children:`unsafe path omitted: ${a.stored_path}`})]},a.id)})]}):null,d2.error?$jsxs("box",{flexDirection:"column",paddingLeft:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:"Error"})}),$jsx("box",{paddingLeft:2,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:d2.error})})]}):null,d2.status==="done"?mrow("result","Result",resultText?cur==="result"?$jsx("text",{wrapMode:"word",fg:theme.text,children:resultText}):$jsx("markdown",{content:resultText,fg:theme.markdownText,syntaxStyle}):$jsx("text",{fg:theme.textMuted,children:"\u2014"}),p.on&&cur==="result"?"Enter edit":void 0):null,p.diags.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"Diagnostics "}),$jsx("span",{fg:sevColor(p.diags[0].severity,theme),children:`(${p.diags.length})`})]})}),p.diags.map((dx,i)=>$jsxs("box",{flexDirection:"column",marginTop:i===0?0:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:sevColor(dx.severity,theme),children:SEV_GLYPH[dx.severity]}),$jsx("span",{fg:theme.text,children:` [${dx.severity}] ${dx.kind}`}),dx.count>1?$jsx("span",{fg:theme.textMuted,children:` \xD7${dx.count}`}):null]})}),$jsxs("box",{paddingLeft:2,flexDirection:"column",children:[$jsx("text",{wrapMode:"word",fg:theme.text,children:dx.title}),dx.detail?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:dx.detail}):null,dx.actions.map((a,j2)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:a.suggested?theme.accent:theme.textMuted,children:a.suggested?"\u2192 ":"\xB7 "}),$jsx("span",{fg:a.suggested?theme.text:theme.textMuted,children:a.label})]})},j2))]})]},`${dx.kind}-${i}`))]}):null,d2.runs.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Runs (${d2.runs.length})`})}),d2.runs.map((r)=>{let outcome2=r.outcome||r.status||(r.ended_at?"ended":"active"),elapsed=r.ended_at?`${Math.max(0,r.ended_at-r.started_at)}s`:"active";return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:`#${r.id} `}),$jsx("span",{fg:theme.text,children:outcome2}),$jsx("span",{fg:theme.textMuted,children:` @${r.profile??"-"} ${elapsed} ${ago(r.started_at)}`})]})}),r.summary?$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:` \u2192 ${r.summary.split(`
4144
4147
  `)[0].slice(0,200)}`}):null,r.error?$jsx("text",{wrapMode:"word",fg:theme.error,children:` \u2716 ${r.error.split(`
4145
4148
  `)[0].slice(0,200)}`}):null]},r.id)})]}):null,d2.events.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Events (${d2.events.length})`})}),d2.events.map((e)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:`${ago(e.created_at).padEnd(10)} `}),$jsx("span",{fg:theme.text,children:e.kind}),e.payload?$jsx("span",{fg:theme.textMuted,children:` ${JSON.stringify(e.payload)}`}):null]})},e.id))]}):null,d2.comments.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:`Comments (${d2.comments.length})`})}),d2.comments.map((c,i)=>$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${c.author} \xB7 ${ago(c.at)}`})}),$jsx("text",{wrapMode:"word",children:c.body})]},i))]}):null,p.on&&cur==="comment"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.accent,children:"Enter add comment"})}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.on?"Tab/\u2191\u2193 field Enter edit Esc grid a assign c comment l log":"Tab into pane a assign c comment u unblock d archive l log N child"})})]})}),Kanban=import_react80.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),keys=useKeys(),[boards,setBoards]=import_react80.useState(listBoards),[data2,setData]=import_react80.useState(()=>new Map(boards.map((b2)=>[b2.slug,boardStateOf(b2.slug)]))),[diags,setDiags]=import_react80.useState(()=>new Map),[masks,setMasks]=import_react80.useState(()=>maskFromPrefs(load2().kanban?.masks)),[open2,setOpen]=import_react80.useState(()=>{let saved=load2().kanban?.open;if(saved)return new Set(saved);let init=currentBoard();return new Set(listBoards().filter((b2)=>{let state2=boardStateOf(b2.slug);return b2.slug===init||[...state2.columns.values()].some((v2)=>v2.length>0)||!!state2.error}).map((b2)=>b2.slug))}),[at,setAt]=import_react80.useState(currentBoard),[tier,setTier]=import_react80.useState("grid"),[col,setCol]=import_react80.useState(0),[row3,setRow]=import_react80.useState(0),[chip2,setChip]=import_react80.useState(0),[paneSel,setPaneSel]=import_react80.useState(0),[pane,setPane]=import_react80.useState(null),outer=import_react80.useRef(null),load4=import_react80.useCallback(()=>{let bs=listBoards();setBoards(bs),setData(new Map(bs.map((b2)=>[b2.slug,boardStateOf(b2.slug)]))),setPane((p)=>p?.kind==="detail"?((d2)=>d2?{...p,d:d2}:null)(detailOf(p.slug,p.d.id)):p),Promise.all(bs.map((b2)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(b2.slug)} diagnostics --json`}).then((r)=>r.code===0?parseDiagnostics(r.stdout):[]).catch(()=>[]).then((rows3)=>[b2.slug,indexDiags(rows3)]))).then((pairs)=>setDiags(new Map(pairs)))},[gw]);import_react80.useEffect(load4,[load4]),import_react80.useEffect(()=>{persist(masks,open2)},[masks,open2]);let maskOf=(s)=>masks.get(s)??EMPTY2,wide=dims.width>=160,maxH=Math.max(8,dims.height-16),sections=import_react80.useMemo(()=>{let built=boards.map((b2)=>{let state2=data2.get(b2.slug)??boardStateOf(b2.slug),d2=state2.columns,flat=STATUSES.flatMap((s)=>d2.get(s)??[]),total=flat.length,who=[...new Set(flat.map((t2)=>t2.assignee).filter((v2)=>!!v2))].sort(),pri=[...new Set(flat.map((t2)=>t2.priority).filter((n)=>n>0))].sort((a,z2)=>z2-a),chips=[...who.map((v2)=>({kind:"who",v:v2})),...pri.map((v2)=>({kind:"pri",v:v2})),...STATUSES.map((v2)=>({kind:"status",v:v2}))],m2=maskOf(b2.slug),cols3=STATUSES.filter((s)=>admits(m2.status,s)).map((s)=>({status:s,tasks:(d2.get(s)??[]).filter((t2)=>pass(t2,m2))})).filter((c)=>wide||c.tasks.length>0),shown=cols3.reduce((a,c)=>a+c.tasks.length,0),tall=cols3.reduce((a,c)=>Math.max(a,c.tasks.length),0);return{board:b2,cols:cols3,chips,total,shown,running:d2.get("running")?.length??0,cap:Math.min(maxH,Math.max(5,3+2*tall)),error:state2.error,corruptBackups:state2.corruptBackups}});return[...built.filter((s)=>s.total>0),...built.filter((s)=>s.total===0)]},[boards,data2,masks,wide,maxH]),idx=sections.findIndex((s)=>s.board.slug===at),sec3=sections[idx]??sections[0],cols2=sec3?.cols??[],clampCol=Math.min(col,Math.max(0,cols2.length-1)),cur=cols2[clampCol],task=tier==="grid"||tier==="pane"?cur?.tasks[Math.min(row3,Math.max(0,(cur?.tasks.length??1)-1))]:void 0,grand=sections.reduce((a,s)=>a+s.total,0),running2=sections.reduce((a,s)=>a+s.running,0);import_react80.useEffect(()=>{if(pane?.kind!=="detail")return;if(tier!=="grid"&&tier!=="pane"){setPane(null);return}if(!task){setPane(null);return}if(pane.slug===at&&pane.d.id===task.id)return;let d2=detailOf(at,task.id);setPane(d2?{kind:"detail",slug:at,d:d2}:null),setPaneSel(0)},[task?.id,at,tier]),import_react80.useEffect(()=>{if(!props.focused||running2===0)return;let t2=setInterval(load4,3000);return()=>clearInterval(t2)},[props.focused,running2,load4]),import_react80.useEffect(()=>{outer.current?.scrollChildIntoView(`kb-sec-${at}`)},[at,open2]);let sh=import_react80.useCallback((argv,ok)=>gw.request("shell.exec",{command:`hermes kanban --board ${q3(at)} ${argv}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());if(ok)toast.show({variant:"success",message:ok});return resetKanban(),load4(),r.stdout}).catch((e)=>void toast.show({variant:"error",message:trunc5(e.message,120)})),[gw,toast,load4,at]),patchDirect=import_react80.useCallback((id,p,ok)=>{try{if(!patchTask(at,id,p))return void toast.show({variant:"error",message:`no such task: ${id}`});toast.show({variant:"success",message:ok}),load4()}catch(e){toast.show({variant:"error",message:trunc5(e.message,120)})}},[at,toast,load4]),enterTop=(s)=>{setAt(s.board.slug),setTier("head"),setChip(0),setRow(0)},enterBottom=(s)=>{if(setAt(s.board.slug),setChip(Math.max(0,s.chips.length-1)),open2.has(s.board.slug)&&s.shown>0){let nc=Math.min(col,Math.max(0,s.cols.length-1));setTier("grid"),setCol(nc),setRow(Math.max(0,(s.cols[nc]?.tasks.length??1)-1));return}if(open2.has(s.board.slug)){setTier("filter");return}setTier("head")},stepBoard=(d2)=>{let n=idx+d2;return n<0||n>=sections.length?null:sections[n]},goBoard=import_react80.useCallback((d2)=>{let n=(idx+d2+sections.length)%sections.length,s=sections[n];setAt(s.board.slug),setTier("head"),setCol(0),setRow(0),setChip(0),setOpen((o)=>o.has(s.board.slug)?o:new Set(o).add(s.board.slug))},[idx,sections]),flip=import_react80.useCallback((c)=>setMasks((m2)=>{let cur2=m2.get(at)??EMPTY2,who=new Map(cur2.who),pri=new Map(cur2.pri),status=new Map(cur2.status),g=c.kind==="who"?who:c.kind==="pri"?pri:status,next2=cycle(g.get(c.v)??"off");next2==="off"?g.delete(c.v):g.set(c.v,next2);let out=new Map(m2);return out.set(at,{who,pri,status}),setRow(0),out}),[at]),toggle=import_react80.useCallback((s)=>setOpen((o)=>{let n=new Set(o);return n.has(s)?n.delete(s):n.add(s),n}),[]),newBoard=import_react80.useCallback(()=>openTextPrompt(dialog,{title:"New board",label:"Slug (a-z, 0-9, -_)"}).then((v2)=>{if(!v2)return;return gw.request("shell.exec",{command:`hermes kanban boards create ${q3(v2)}`}).then((r)=>r.code===0?(toast.show({variant:"success",message:`Board '${v2}' created`}),resetKanban(),load4(),setAt(v2),setTier("head")):Promise.reject(Error((r.stderr||r.stdout).trim()))).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)}))}),[dialog,gw,toast,load4]),live=import_react80.useRef({task,at,sec:sec3});live.current={task,at,sec:sec3};let create=import_react80.useCallback((parent2)=>openCreateTask(dialog,{assignees:assignees(live.current.at),parent:parent2?{id:parent2.id,title:parent2.title}:void 0}).then((d2)=>{if(!d2)return;let ws=d2.workspace.kind==="scratch"?"":d2.workspace.kind==="worktree"?"--workspace worktree":`--workspace ${q3(`dir:${d2.workspace.path}`)}`,flags=[d2.assignee?`--assignee ${q3(d2.assignee)}`:"",d2.body?`--body ${q3(d2.body)}`:"",d2.priority?`--priority ${d2.priority}`:"",d2.parent?`--parent ${q3(d2.parent)}`:"",d2.triage?"--triage":"",d2.tenant?`--tenant ${q3(d2.tenant)}`:"",ws,d2.maxRuntime?`--max-runtime ${q3(d2.maxRuntime)}`:"",...d2.skills.map((s)=>`--skill ${q3(s)}`)].filter(Boolean).join(" ");return sh(`create ${q3(d2.title)} ${flags}`.trim(),`Created${d2.triage?" (triage)":""}${d2.assignee?` \u2192 ${d2.assignee}`:""}`)}),[dialog,sh]),assign=import_react80.useCallback((t2)=>{let opts=[{title:"(unassigned)",value:"none"},...assignees(live.current.at).map((n)=>({title:n,value:n}))];dialog.replace($jsx(DialogSelect,{title:`Assign ${t2.id}`,options:opts,current:t2.assignee??"none",placeholder:"Search profiles\u2026",onSelect:(o)=>{dialog.clear(),sh(`assign ${q3(t2.id)} ${q3(o.value)}`,o.value==="none"?`Unassigned ${t2.id}`:`${t2.id} \u2192 ${o.value}`)}}))},[dialog,sh]),comment=import_react80.useCallback((t2)=>openTextPrompt(dialog,{title:`Comment on ${t2.id}`,label:t2.title}).then((v2)=>v2&&sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`,"Comment added")),[dialog,sh]),unblock=import_react80.useCallback((t2)=>{if(t2.status!=="blocked"&&t2.status!=="scheduled")return void toast.show({variant:"info",message:`${t2.id} is ${t2.status}, not blocked/scheduled`});if(t2.status==="scheduled")return void sh(`unblock ${q3(t2.id)}`,`Released ${t2.id}`);return openTextPrompt(dialog,{title:`Unblock ${t2.id}`,label:"Answer (posted as comment, then task \u2192 ready)"}).then((v2)=>{if(v2)return sh(`comment ${q3(t2.id)} ${q3(v2)} --author user`)}).then(()=>sh(`unblock ${q3(t2.id)}`,`Unblocked ${t2.id}`))},[dialog,sh,toast]),archive=import_react80.useCallback((t2)=>openConfirm(dialog,{title:"Archive task?",danger:!0,yes:"archive",body:`${t2.id} \xB7 ${trunc5(t2.title,60)}
4146
4149
 
@@ -4193,8 +4196,8 @@ ${r.skipped.slice(0,8).join(", ")}${r.skipped.length>8?", \u2026":""}`:""}`,yes:
4193
4196
  `;writeSync(1,banner)}process.exit(0)}var exports_stash={};__export(exports_stash,{push:()=>push2,pop:()=>pop2,drop:()=>drop,all:()=>all,Stash:()=>exports_stash});import{join as join25}from"path";import{existsSync as existsSync26,readFileSync as readFileSync20,writeFileSync as writeFileSync9,mkdirSync as mkdirSync7}from"fs";var MAX=50,file2=()=>join25(configDir(),"stash.jsonl");function load5(){if(!existsSync26(file2()))return[];return readFileSync20(file2(),"utf-8").split(`
4194
4197
  `).filter(Boolean).map((l)=>JSON.parse(l)).slice(-MAX)}function save3(list3){mkdirSync7(configDir(),{recursive:!0}),writeFileSync9(file2(),list3.map((e)=>JSON.stringify(e)).join(`
4195
4198
  `)+`
4196
- `,"utf-8")}function push2(text4){let list3=load5(),at=Math.max(Date.now(),(list3[list3.length-1]?.at??0)+1);if(list3.push({text:text4,at}),list3.length>MAX)list3.shift();return save3(list3),list3.length}function pop2(){let list3=load5(),e=list3.pop();if(!e)return null;return save3(list3),e}function all(){return load5().reverse()}function drop(at){save3(load5().filter((e)=>e.at!==at))}var import_react127=__toESM(require_react_production(),1);var ctx=import_react127.createContext(null),BackgroundProvider=({children:children2})=>{let[set2,setSet]=import_react127.useState(()=>new Set),register2=import_react127.useCallback((id)=>{if(!id)return;setSet((prev)=>prev.has(id)?prev:new Set(prev).add(id))},[]),unregister=import_react127.useCallback((id)=>{setSet((prev)=>{if(!prev.has(id))return prev;let next2=new Set(prev);return next2.delete(id),next2})},[]),ids3=import_react127.useMemo(()=>Array.from(set2),[set2]),value=import_react127.useMemo(()=>({count:ids3.length,ids:ids3,register:register2,unregister}),[ids3,register2,unregister]);return $jsx(ctx.Provider,{value,children:children2})},useBackground=makeUse(ctx,"useBackground");var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"load.live":return{...initialTurn,messages:a.messages,streaming:a.streaming,hasContent:a.streaming&&Boolean(joinText(a.messages.at(-1)?.parts??[]))};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(sanitize(a.text))]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":{let chunk=sanitize(a.chunk);if(!chunk)return state2;return{...state2,hasContent:!0,toolActive:!1,messages:appendText(state2.messages,chunk)}}case"message.complete":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:finalize(state2.messages,a.text!=null?sanitize(a.text):void 0,a.usage)};case"tool.start":{let preview2=sanitize(a.preview),args=sanitize(a.args),raw2=args||preview2,json2=raw2&&/^\s*\{/.test(raw2),part={type:"tool",id:a.id,name:a.name,args:json2?raw2:"",status:"running",startedAt:Date.now(),preview:preview2||void 0,verboseArgs:args||void 0};return{...state2,toolActive:!0,hasContent:!1,messages:appendPart(state2.messages,part,!0)}}case"tool.progress":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:sanitize(a.preview)||p.preview}))};case"tool.generating":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:p.preview??"generating\u2026"}))};case"tool.complete":{let summary2=sanitize(a.summary),error=sanitize(a.error),diff=sanitize(a.inline_diff),result=sanitize(a.result);return{...state2,toolActive:!1,messages:updateToolById(state2.messages,a.id,(p)=>({...p,status:a.error?"error":"done",duration:a.duration??(p.startedAt?Date.now()-p.startedAt:void 0),preview:summary2||diff||p.preview,result:error||summary2||void 0,verboseResult:result||void 0,diff:diff||void 0}))}}case"thinking":return{...state2,messages:upsertThinking(state2.messages,sanitize(a.text),a.final,a.verbose)};case"subagent":return{...state2,messages:renderSubagent(state2.messages,a.event,a.payload)};case"prompt":{let part={type:"prompt",id:a.id,variant:a.req.variant,req:a.req};return{...state2,messages:appendPart(state2.messages,part,!0)}}case"prompt.answered":return{...state2,messages:updatePrompt(state2.messages,a.id,(p)=>({...p,answered:{label:a.label,ok:a.ok,at:Date.now()}}))};case"error":{let msg=systemMessage(`Error: ${sanitize(a.text)}`);if(a.fatal===!1)return{...state2,messages:[...state2.messages,msg]};return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:[...state2.messages,msg]}}case"interrupt.notice":{let clean5=sanitize(a.text),last3=state2.messages[state2.messages.length-1];if(last3?.role==="system"&&last3.parts[0]?.type==="text"&&last3.parts[0].content.includes(clean5))return state2;return{...state2,messages:[...state2.messages,systemMessage(clean5)]}}}}function userMessage(text4){return{id:mid(),role:"user",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function systemMessage(text4){return{id:mid(),role:"system",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function flatten3(text4){if(typeof text4==="string")return text4;if(!Array.isArray(text4))return"";let out=[];for(let p of text4)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")out.push(p.text);return out.join(`
4197
- `)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:sanitize(flatten3(r.text))})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,chunk){return withLastAssistant(messages,(m2)=>{let last3=m2.parts[m2.parts.length-1];if(last3?.type==="text"&&last3.streaming){let part={...last3,content:last3.content+chunk};return{...m2,parts:[...m2.parts.slice(0,-1),part]}}return{...m2,parts:[...m2.parts,{type:"text",key:pid(),content:chunk,streaming:!0}]}},()=>assistant([{type:"text",key:pid(),content:chunk,streaming:!0}]))}function appendPart(messages,part,close){return withLastAssistant(messages,(m2)=>({...m2,parts:[...close?seal(m2.parts):m2.parts,part]}),()=>assistant([part]))}function finalize(messages,final,usage){let last3=messages[messages.length-1];if(last3?.role==="assistant"){let tail=last3.parts[last3.parts.length-1],dup=final&&last3.parts.some((p)=>p.type==="text"&&sameText(p.content,final)),text4=tail?.type==="text"&&final&&sameText(tail.content,final)?tail.content:final,parts2=tail?.type==="text"&&tail.streaming?[...last3.parts.slice(0,-1),{...tail,content:text4||tail.content,streaming:!1}]:final&&!dup&&!sameText(joinText(last3.parts),final)?[...last3.parts,{type:"text",content:final,streaming:!1}]:seal(last3.parts);return[...messages.slice(0,-1),{...last3,parts:parts2,usage}]}if(!final)return messages;return[...messages,{...assistant([{type:"text",content:final,streaming:!1}]),usage}]}function joinText(parts2){return parts2.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function sameText(a,b2){return a.trim()===b2.trim()}function updateRunningTool(messages,name,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;for(let i=last3.parts.length-1;i>=0;i--){let p=last3.parts[i];if(p.type!=="tool"||p.status!=="running")continue;if(name&&p.name!==name)continue;let parts2=[...last3.parts];return parts2[i]=fn(p),[...messages.slice(0,-1),{...last3,parts:parts2}]}return messages}function updateToolById(messages,id,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;let parts2=last3.parts.map((p)=>p.type==="tool"&&p.id===id?fn(p):p);return[...messages.slice(0,-1),{...last3,parts:parts2}]}function updatePrompt(messages,id,fn){return messages.map((m2)=>{if(m2.role!=="assistant")return m2;if(!m2.parts.some((p)=>p.type==="prompt"&&p.id===id))return m2;return{...m2,parts:m2.parts.map((p)=>p.type==="prompt"&&p.id===id?fn(p):p)}})}function upsertThinking(messages,text4,final,verbose2){return withLastAssistant(messages,(m2)=>{let idx=m2.parts.findIndex((p)=>p.type==="thinking");if(idx>=0){let prev=m2.parts[idx],content=final?prev.content.trim()||text4:prev.content+text4,parts2=[...m2.parts];return parts2[idx]={...prev,content,streaming:!final,verbose:prev.verbose||verbose2||void 0},{...m2,parts:parts2}}return{...m2,parts:[{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2},...m2.parts]}},()=>assistant([{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2}]))}function renderSubagent(messages,event,p){let id=p.subagent_id?`sub-${p.subagent_id}`:`sub-${p.task_index}`;if(event==="start"){let goal=sanitize(p.goal),part={type:"tool",id,name:"delegate_task",args:"",status:"running",startedAt:Date.now(),preview:goal||void 0,goal:goal||void 0,depth:p.depth??0,trail:[]};return appendPart(messages,part,!0)}if(event==="tool"&&p.tool_name){let tname=sanitize(p.tool_name),tprev=sanitize(p.tool_preview);return updateToolById(messages,id,(t2)=>({...t2,trail:[...t2.trail??[],{name:tname,preview:tprev||void 0}],preview:tprev?`${tname}: ${tprev}`:tname}))}if(event==="complete"){let tokens3=(p.input_tokens??0)+(p.output_tokens??0),extra=tokens3?` \xB7 ${(tokens3/1000).toFixed(1)}k tok`:"",summary2=sanitize(p.summary);return updateToolById(messages,id,(t2)=>({...t2,status:p.status==="failed"||p.status==="error"||p.status==="timeout"||p.status==="interrupted"?"error":"done",duration:p.duration_seconds?p.duration_seconds*1000:t2.startedAt?Date.now()-t2.startedAt:void 0,result:summary2?summary2+extra:void 0,preview:t2.goal??t2.preview}))}return updateToolById(messages,id,(t2)=>({...t2,preview:sanitize(p.text)||t2.preview}))}function useSlash(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),themeCtx=useTheme(),cmd=useCommand(),renderer=useRenderer(),cfg=useHome("config"),bg2=useBackground(),ctx2=import_react128.useRef(c);ctx2.current=c;let gate=import_react128.useRef(cfg);gate.current=cfg;let destructive=import_react128.useCallback((arg,opts,action)=>{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",bypass=!(gate.current?.approvals?.destructive_slash_confirm??!0)||process.env.HERMES_TUI_NO_CONFIRM==="1",persist2=a==="always",fire=()=>{if(persist2)Promise.resolve().then(() => (init_lane(),exports_lane)).then(({writeConfig:writeConfig2})=>writeConfig2(gw,[{key:"approvals.destructive_slash_confirm",to:!1}]).then((r)=>{if(r.failed.length){toast.show({variant:"warning",message:`couldn't persist: ${r.failed[0].err}`});return}home2.invalidate("config"),toast.show({variant:"success",message:`${opts.yes} \xB7 future runs silent`})}).catch((e)=>toast.show({variant:"error",message:e.message})));action()};if(skip||bypass)return fire();openConfirm(dialog,{title:opts.title,body:opts.body,yes:opts.yes,danger:!0}).then((ok)=>{if(ok)fire()})},[gw,dialog,toast]),pickEikon=import_react128.useCallback(()=>openEikonPicker(dialog,(n)=>set("eikon",n)),[dialog]),applyTitle=import_react128.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{ctx2.current.setTitle(r.title),ctx2.current.dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),runCompress=import_react128.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await ctx2.current.session.compress();if(!r)return;if(r.info)ctx2.current.setInfo(r.info);if(ctx2.current.setUsage((u3)=>{let base2=r.usage??u3,max=r.usage?.context_max??u3?.context_max;if(typeof r.after_tokens!=="number"||typeof max!=="number")return base2;return{...base2??{input:0,output:0,total:0},context_used:r.after_tokens,context_max:max}}),!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines3=[s.headline,s.token_line,s.note].filter(Boolean).join(`
4199
+ `,"utf-8")}function push2(text4){let list3=load5(),at=Math.max(Date.now(),(list3[list3.length-1]?.at??0)+1);if(list3.push({text:text4,at}),list3.length>MAX)list3.shift();return save3(list3),list3.length}function pop2(){let list3=load5(),e=list3.pop();if(!e)return null;return save3(list3),e}function all(){return load5().reverse()}function drop(at){save3(load5().filter((e)=>e.at!==at))}var import_react127=__toESM(require_react_production(),1);var ctx=import_react127.createContext(null),BackgroundProvider=({children:children2})=>{let[set2,setSet]=import_react127.useState(()=>new Set),register2=import_react127.useCallback((id)=>{if(!id)return;setSet((prev)=>prev.has(id)?prev:new Set(prev).add(id))},[]),unregister=import_react127.useCallback((id)=>{setSet((prev)=>{if(!prev.has(id))return prev;let next2=new Set(prev);return next2.delete(id),next2})},[]),ids3=import_react127.useMemo(()=>Array.from(set2),[set2]),value=import_react127.useMemo(()=>({count:ids3.length,ids:ids3,register:register2,unregister}),[ids3,register2,unregister]);return $jsx(ctx.Provider,{value,children:children2})},useBackground=makeUse(ctx,"useBackground");var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"load.live":return{...initialTurn,messages:a.messages,streaming:a.streaming,hasContent:a.streaming&&Boolean(joinText(a.messages.at(-1)?.parts??[]))};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(sanitize(a.text))]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":{let chunk=sanitize(a.chunk);if(!chunk)return state2;return{...state2,hasContent:!0,toolActive:!1,messages:appendText(state2.messages,chunk)}}case"message.complete":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:finalize(state2.messages,a.text!=null?sanitize(a.text):void 0,a.usage)};case"tool.start":{let preview2=sanitize(a.preview),args=sanitize(a.args),raw2=args||preview2,json2=raw2&&/^\s*\{/.test(raw2),part={type:"tool",id:a.id,name:a.name,args:json2?raw2:"",status:"running",startedAt:Date.now(),preview:preview2||void 0,verboseArgs:args||void 0};return{...state2,toolActive:!0,hasContent:!1,messages:appendPart(state2.messages,part,!0)}}case"tool.progress":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:sanitize(a.preview)||p.preview}))};case"tool.generating":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:p.preview??"generating\u2026"}))};case"tool.complete":{let summary2=sanitize(a.summary),error=sanitize(a.error),diff=sanitize(a.inline_diff),result=sanitize(a.result);return{...state2,toolActive:!1,messages:updateToolById(state2.messages,a.id,(p)=>({...p,status:a.error?"error":"done",duration:a.duration??(p.startedAt?Date.now()-p.startedAt:void 0),preview:summary2||diff||p.preview,result:error||summary2||void 0,verboseResult:result||void 0,diff:diff||void 0}))}}case"thinking":return{...state2,messages:upsertThinking(state2.messages,sanitize(a.text),a.final,a.verbose)};case"subagent":return{...state2,messages:renderSubagent(state2.messages,a.event,a.payload)};case"prompt":{let part={type:"prompt",id:a.id,variant:a.req.variant,req:a.req};return{...state2,messages:appendPart(state2.messages,part,!0)}}case"prompt.answered":return{...state2,messages:updatePrompt(state2.messages,a.id,(p)=>({...p,answered:{label:a.label,ok:a.ok,at:Date.now(),question:promptQuestion(p.req)}}))};case"error":{let msg=systemMessage(`Error: ${sanitize(a.text)}`);if(a.fatal===!1)return{...state2,messages:[...state2.messages,msg]};return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:[...state2.messages,msg]}}case"interrupt.notice":{let clean5=sanitize(a.text),last3=state2.messages[state2.messages.length-1];if(last3?.role==="system"&&last3.parts[0]?.type==="text"&&last3.parts[0].content.includes(clean5))return state2;return{...state2,messages:[...state2.messages,systemMessage(clean5)]}}}}function userMessage(text4){return{id:mid(),role:"user",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function systemMessage(text4){return{id:mid(),role:"system",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function flatten3(text4){if(typeof text4==="string")return text4;if(!Array.isArray(text4))return"";let out=[];for(let p of text4)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")out.push(p.text);return out.join(`
4200
+ `)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:sanitize(flatten3(r.text))})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,chunk){return withLastAssistant(messages,(m2)=>{let last3=m2.parts[m2.parts.length-1];if(last3?.type==="text"&&last3.streaming){let part={...last3,content:last3.content+chunk};return{...m2,parts:[...m2.parts.slice(0,-1),part]}}return{...m2,parts:[...m2.parts,{type:"text",key:pid(),content:chunk,streaming:!0}]}},()=>assistant([{type:"text",key:pid(),content:chunk,streaming:!0}]))}function appendPart(messages,part,close){return withLastAssistant(messages,(m2)=>({...m2,parts:[...close?seal(m2.parts):m2.parts,part]}),()=>assistant([part]))}function finalize(messages,final,usage){let last3=messages[messages.length-1];if(last3?.role==="assistant"){let tail=last3.parts[last3.parts.length-1],dup=final&&last3.parts.some((p)=>p.type==="text"&&sameText(p.content,final)),text4=tail?.type==="text"&&final&&sameText(tail.content,final)?tail.content:final,parts2=tail?.type==="text"&&tail.streaming?[...last3.parts.slice(0,-1),{...tail,content:text4||tail.content,streaming:!1}]:final&&!dup&&!sameText(joinText(last3.parts),final)?[...last3.parts,{type:"text",content:final,streaming:!1}]:seal(last3.parts);return[...messages.slice(0,-1),{...last3,parts:parts2,usage}]}if(!final)return messages;return[...messages,{...assistant([{type:"text",content:final,streaming:!1}]),usage}]}function joinText(parts2){return parts2.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function sameText(a,b2){return a.trim()===b2.trim()}function updateRunningTool(messages,name,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;for(let i=last3.parts.length-1;i>=0;i--){let p=last3.parts[i];if(p.type!=="tool"||p.status!=="running")continue;if(name&&p.name!==name)continue;let parts2=[...last3.parts];return parts2[i]=fn(p),[...messages.slice(0,-1),{...last3,parts:parts2}]}return messages}function updateToolById(messages,id,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;let parts2=last3.parts.map((p)=>p.type==="tool"&&p.id===id?fn(p):p);return[...messages.slice(0,-1),{...last3,parts:parts2}]}function updatePrompt(messages,id,fn){return messages.map((m2)=>{if(m2.role!=="assistant")return m2;if(!m2.parts.some((p)=>p.type==="prompt"&&p.id===id))return m2;return{...m2,parts:m2.parts.map((p)=>p.type==="prompt"&&p.id===id?fn(p):p)}})}function promptQuestion(req){if(req.variant==="clarify")return req.question;if(req.variant==="approval")return req.description||"Shell command";if(req.variant==="sudo")return"Sudo required";return req.env_var?`Secret: ${req.env_var}`:"Secret required"}function upsertThinking(messages,text4,final,verbose2){return withLastAssistant(messages,(m2)=>{let idx=m2.parts.findIndex((p)=>p.type==="thinking");if(idx>=0){let prev=m2.parts[idx],content=final?prev.content.trim()||text4:prev.content+text4,parts2=[...m2.parts];return parts2[idx]={...prev,content,streaming:!final,verbose:prev.verbose||verbose2||void 0},{...m2,parts:parts2}}return{...m2,parts:[{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2},...m2.parts]}},()=>assistant([{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2}]))}function renderSubagent(messages,event,p){let id=p.subagent_id?`sub-${p.subagent_id}`:`sub-${p.task_index}`;if(event==="start"){let goal=sanitize(p.goal),part={type:"tool",id,name:"delegate_task",args:"",status:"running",startedAt:Date.now(),preview:goal||void 0,goal:goal||void 0,depth:p.depth??0,trail:[]};return appendPart(messages,part,!0)}if(event==="tool"&&p.tool_name){let tname=sanitize(p.tool_name),tprev=sanitize(p.tool_preview);return updateToolById(messages,id,(t2)=>({...t2,trail:[...t2.trail??[],{name:tname,preview:tprev||void 0}],preview:tprev?`${tname}: ${tprev}`:tname}))}if(event==="complete"){let tokens3=(p.input_tokens??0)+(p.output_tokens??0),extra=tokens3?` \xB7 ${(tokens3/1000).toFixed(1)}k tok`:"",summary2=sanitize(p.summary);return updateToolById(messages,id,(t2)=>({...t2,status:p.status==="failed"||p.status==="error"||p.status==="timeout"||p.status==="interrupted"?"error":"done",duration:p.duration_seconds?p.duration_seconds*1000:t2.startedAt?Date.now()-t2.startedAt:void 0,result:summary2?summary2+extra:void 0,preview:t2.goal??t2.preview}))}return updateToolById(messages,id,(t2)=>({...t2,preview:sanitize(p.text)||t2.preview}))}function useSlash(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),themeCtx=useTheme(),cmd=useCommand(),renderer=useRenderer(),cfg=useHome("config"),bg2=useBackground(),ctx2=import_react128.useRef(c);ctx2.current=c;let gate=import_react128.useRef(cfg);gate.current=cfg;let destructive=import_react128.useCallback((arg,opts,action)=>{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",bypass=!(gate.current?.approvals?.destructive_slash_confirm??!0)||process.env.HERMES_TUI_NO_CONFIRM==="1",persist2=a==="always",fire=()=>{if(persist2)Promise.resolve().then(() => (init_lane(),exports_lane)).then(({writeConfig:writeConfig2})=>writeConfig2(gw,[{key:"approvals.destructive_slash_confirm",to:!1}]).then((r)=>{if(r.failed.length){toast.show({variant:"warning",message:`couldn't persist: ${r.failed[0].err}`});return}home2.invalidate("config"),toast.show({variant:"success",message:`${opts.yes} \xB7 future runs silent`})}).catch((e)=>toast.show({variant:"error",message:e.message})));action()};if(skip||bypass)return fire();openConfirm(dialog,{title:opts.title,body:opts.body,yes:opts.yes,danger:!0}).then((ok)=>{if(ok)fire()})},[gw,dialog,toast]),pickEikon=import_react128.useCallback(()=>openEikonPicker(dialog,(n)=>set("eikon",n)),[dialog]),applyTitle=import_react128.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{ctx2.current.setTitle(r.title),ctx2.current.dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),runCompress=import_react128.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await ctx2.current.session.compress();if(!r)return;if(r.info)ctx2.current.setInfo(r.info);if(ctx2.current.setUsage((u3)=>{let base2=r.usage??u3,max=r.usage?.context_max??u3?.context_max;if(typeof r.after_tokens!=="number"||typeof max!=="number")return base2;return{...base2??{input:0,output:0,total:0},context_used:r.after_tokens,context_max:max}}),!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines3=[s.headline,s.token_line,s.note].filter(Boolean).join(`
4198
4201
  `);if(lines3)ctx2.current.dispatch({kind:"system",text:lines3});toast.show({variant:"success",message:s.headline??`Compressed ${r.before_messages??0}\u2192${r.after_messages??0} messages`})},[toast]),branch2=import_react128.useCallback((name)=>{let x2=ctx2.current;x2.session.branch(name?.trim()||void 0).then((id)=>id?void x2.activateSession(id):toast.show({variant:"error",message:"branch failed"}))},[toast]),run=import_react128.useCallback((c2,arg="")=>{let x2=ctx2.current;if(c2.target==="local")switch(c2.name){case"clear":destructive(arg,{title:"Clear session?",body:"Discards the in-memory transcript. Your session on disk is unchanged; reload to restore.",yes:"clear"},()=>x2.dispatch({kind:"reset"}));return;case"new":destructive(arg,{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{x2.newSession()});return;case"theme":{let mode=arg.trim().toLowerCase();if(!mode){openThemePicker(dialog,themeCtx);return}if(mode==="light"||mode==="dark"){themeCtx.setMode(mode),x2.dispatch({kind:"system",text:`theme mode \u2192 ${mode}`});return}toast.show({variant:"error",message:"usage: /theme [light|dark]"});return}case"help":dialog.replace($jsx(HelpDialog,{}));return;case"keys":openKeys(dialog);return;case"logs":openLogs(dialog);return;case"title":if(arg){applyTitle(arg);return}openTextPrompt(dialog,{title:"Session Title",initial:x2.title}).then((v2)=>{if(v2)applyTitle(v2)});return;case"rollback":openRollback(dialog,gw,toast);return;case"history":openHistory(dialog,gw);return;case"status":openStatus(dialog,x2.info,x2.sid);return;case"usage":openUsage(dialog,gw);return;case"profile":openProfile(dialog);return;case"chafa":if(!arg.trim()){toast.show({variant:"info",message:"usage: /chafa <path>"});return}openChafa(dialog,arg.trim());return;case"splash":x2.summoned.current=!0,x2.setSplash(!0);return;case"skin":{let name=arg.trim();if(!name){x2.dispatch({kind:"system",text:`skin: ${x2.skin.skin?.name??"\u2014"}
4199
4202
  ${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikon",void 0),x2.dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){x2.switchSession(arg);return}x2.goTo(TAB_SLASH.sessions.tab,TAB_SLASH.sessions.sub);return;case"branch":branch2(arg);return;case"compress":runCompress();return;case"undo":destructive(arg,{title:"Undo last turn?",body:"Pops the last user + assistant pair from the transcript. /redo in this session to restore.",yes:"undo"},()=>{let msgs=x2.turnRef.current.messages,at=msgs.map((m2)=>m2.role).lastIndexOf("user");if(at>=0)x2.undone.current.push(msgs.slice(at));x2.session.undo().then(()=>gw.request("session.history").then((r)=>x2.dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}))});return;case"redo":{let head=x2.undone.current.pop()?.find((m2)=>m2.role==="user");if(!head){toast.show({variant:"info",message:"nothing to redo"});return}x2.sendRef.current(text(head));return}case"retry":{let last3=[...x2.turnRef.current.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}x2.rewind(last3).then(()=>x2.sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});x2.dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"yolo":gw.request("config.set",{key:"yolo"}).then((r)=>{if(r.info)x2.setInfo(r.info),x2.setUsage(r.info.usage);else x2.setInfo({...x2.info??{},yolo:!x2.info?.yolo});if(toast.show({variant:"success",message:`yolo ${r.value??"toggled"}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,x2.sid,x2.title,gw);return;case"queue":if(!arg){x2.dispatch({kind:"system",text:`${x2.queueRef.current.length} queued`});return}x2.setQueue((q5)=>[...q5,arg]);return;case"stash":{let comp=x2.composer.current;if(arg==="pop"){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});comp?.set(e.text),x2.setFocusRegion("input");return}if(arg==="list"){let list3=exports_stash.all();if(list3.length===0)return toast.show({variant:"info",message:"stash empty"});dialog.replace($jsx(DialogSelect,{title:"Stashed prompts",filterable:list3.length>6,options:list3.map((e)=>({title:trunc5(e.text.replace(/\n/g," \u23CE "),50),value:String(e.at),hint:ago(e.at)})),onSelect:(o)=>{let e=list3.find((s)=>String(s.at)===o.value);if(e)exports_stash.drop(e.at),comp?.set(e.text),x2.setFocusRegion("input");dialog.clear()}}));return}let text4=arg||comp?.value().trim()||"";if(!text4)return toast.show({variant:"info",message:"nothing to stash \u2014 /stash list"});let n=exports_stash.push(text4);if(!arg)comp?.set("");toast.show({variant:"info",message:`stashed (${n}) \u2014 /stash pop to restore`});return}case"copy":{let all2=x2.turnRef.current.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all2.length):all2.length,m2=all2[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy2(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":x2.attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?x2.setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>{if(r.task_id)bg2.register(r.task_id);toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":x2.voiceToggle((arg||"status").toLowerCase(),x2.sid).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"browser":{let parts2=arg.trim().split(/\s+/),sub2=parts2[0]?.toLowerCase()||"connect",url2=parts2[1];if(!["connect","disconnect","status"].includes(sub2)){toast.show({variant:"error",message:"usage: /browser [connect|disconnect|status] [url]"});return}let payload={action:sub2};if(sub2==="connect"&&url2)payload.url=url2;gw.request("browser.manage",payload).then((r)=>{for(let m2 of r.messages??[])x2.dispatch({kind:"system",text:m2});if(r.connected)x2.dispatch({kind:"system",text:`Browser connected${r.url?` \u2192 ${r.url}`:""}`});else if(sub2==="disconnect")x2.dispatch({kind:"system",text:"Browser disconnected"});else if(sub2==="status")x2.dispatch({kind:"system",text:r.url??"No browser connected"})}).catch((e)=>toast.show({variant:"error",message:`browser: ${e.message}`}));return}case"compact":case"setup":x2.dispatch({kind:"system",text:`/${c2.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text4)=>gw.request("session.steer",{text:text4}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text4)=>{if(text4)fire(text4)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{x2.dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c2.target!=="gateway"||!x2.capabilities.canDispatchGatewayCommand)return;let jump=TAB_SLASH[c2.name];if(jump!==void 0&&!arg){x2.goTo(jump.tab,jump.sub);return}let full=`/${c2.name}${arg?" "+arg:""}`;if(x2.turnRef.current.streaming){x2.setQueue((q5)=>[...q5,full]);return}x2.dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)x2.dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)x2.dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c2.name,arg}).then((d2)=>{if(d2.notice)x2.dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return x2.dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void x2.sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")x2.dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c2.name}`});return void x2.sendRef.current(d2.message)}x2.dispatch({kind:"system",text:`/${c2.name}: unknown`})}).catch((e)=>x2.dispatch({kind:"system",text:`error: ${e.message}`}))})},[gw,dialog,toast,themeCtx,renderer,destructive,applyTitle,runCompress,branch2]);return import_react128.useEffect(()=>cmd.register([{title:"Help",value:"help",action:"help.open",category:"General",onSelect:()=>dialog.replace($jsx(HelpDialog,{}))},{title:"Keybindings",value:"keys",description:"View & rebind shortcuts",category:"General",onSelect:()=>openKeys(dialog)},{title:"Gateway Logs",value:"logs",description:"Show gateway stderr",category:"General",onSelect:()=>openLogs(dialog)},{title:"Switch Theme",value:"theme",action:"theme.pick",category:"General",onSelect:()=>openThemePicker(dialog,themeCtx)},{title:"Switch Model",value:"model",action:"model.pick",category:"General",onSelect:()=>openModelPicker(dialog,gw)},{title:"Pick Avatar",value:"eikon",description:"Choose sidebar .eikon avatar",category:"General",onSelect:()=>pickEikon()},{title:"Rollback",value:"rollback",description:"Browse & restore checkpoints",category:"Session",onSelect:()=>openRollback(dialog,gw,toast)},{title:"History",value:"history",action:"session.timeline",category:"Session",onSelect:()=>openHistory(dialog,gw)},{title:"Status",value:"status",action:"status.open",category:"Info",onSelect:()=>openStatus(dialog,ctx2.current.info,ctx2.current.sid)},{title:"Usage",value:"usage",description:"Tokens \xB7 context \xB7 cost",category:"Info",onSelect:()=>openUsage(dialog,gw)},{title:"Profile",value:"profile",description:"Active profile details",category:"Info",onSelect:()=>openProfile(dialog)},{title:"New Session",value:"new-session",action:"session.new",category:"Session",onSelect:()=>destructive("",{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{ctx2.current.newSession()})},{title:"Compress Session",value:"compress",action:"session.compress",category:"Session",onSelect:()=>runCompress()},{title:"Undo Last Turn",value:"undo",description:"Pop last user+assistant pair",category:"Session",onSelect:()=>run({name:"undo",target:"local"})},{title:"Redo",value:"redo",action:"session.redo",category:"Session",onSelect:()=>run({name:"redo",target:"local"})},{title:"Branch Session",value:"branch",description:"Fork the current conversation",category:"Session",onSelect:()=>branch2()}]),[cmd,dialog,themeCtx,gw,toast,destructive,pickEikon,runCompress,branch2,run]),run}var import_react132=__toESM(require_react_production(),1);var import_react130=__toESM(require_react_production(),1);function openAlert(dialog,title,body2){dialog.replace($jsx(Alert,{title,body:body2,onClose:()=>dialog.clear()}))}var Alert=(props)=>{let theme=useTheme().theme,keys=useKeys(),[copied,setCopied]=import_react130.useState(!1),doCopy=()=>{copy2(props.body),setCopied(!0),setTimeout(()=>setCopied(!1),900)};return useKeyboard((key5)=>{if(keys.match("dialog.cancel",key5)||keys.match("dialog.accept",key5))props.onClose();if(keys.match("dialog.copy",key5))doCopy()}),$jsxs("box",{flexDirection:"column",width:84,maxHeight:28,border:["left"],borderColor:theme.info,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingRight:2,paddingY:1,gap:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.info,children:"\u25C8 "}),$jsx("span",{fg:theme.text,children:props.title})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.body})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:`${keys.print("dialog.cancel")} close \xB7 ${keys.print("dialog.copy")} `})}),$jsx("box",{flexShrink:0,onMouseDown:(e)=>{e.stopPropagation(),doCopy()},children:$jsx("text",{fg:copied?theme.success:theme.textMuted,children:$jsx("u",{children:copied?"copied":"copy"})})})]})]})};init_perf();function variant(level2){switch(level2){case"error":return"error";case"warning":case"warn":return"warning";case"success":return"success";default:return"info"}}function duration2(p){if(p.kind==="sticky")return null;if(typeof p.ttl_ms==="number")return p.ttl_ms;if(typeof p.duration_ms==="number")return p.duration_ms;return}function showNotification(toast,p){let text4=String(p?.text??"").trim();if(!text4)return;toast.show({key:p?.key,variant:variant(p?.level),message:text4,duration:duration2(p??{text:text4})})}function clearNotification(toast,p){let key5=String(p?.key??"").trim();if(!key5)return;toast.clear(key5)}function count3(o){return o?Object.values(o).reduce((n,v2)=>n+v2.length,0):0}function formatProcessNotification(text4){let body2=text4.replace(/^\[IMPORTANT: /,"").replace(/\]$/,""),done2=body2.match(/^Background process (\S+) completed \(exit code (\S+)\)\.\nCommand: (.+?)(?:\n|$)/);if(done2)return`${done2[1]} exited ${done2[2]} \xB7 ${done2[3]}`;let hit2=body2.match(/^Background process (\S+) matched watch pattern "([^"]+)"\.\nCommand: (.+?)(?:\n|$)/);if(hit2)return`${hit2[1]} matched "${hit2[2]}" \xB7 ${hit2[3]}`;return body2.slice(0,100)}function mapEvent(ev,side){switch(ev.type){case"gateway.ready":if(side.onReady?.(),ev.payload?.skin)side.onSkin?.(ev.payload.skin);return null;case"session.info":{let si=ev.payload;side.onSessionInfo?.(si);let label2=si.model?`Connected \u2014 ${si.model} \xB7 ${count3(si.tools)} tools \xB7 ${count3(si.skills)} skills`:"Connected to Hermes";if(si.credential_warning)side.onStatus?.(si.credential_warning);return{kind:"system",text:label2}}case"message.start":return count("stream:start"),mem("stream-start"),{kind:"message.start"};case"message.delta":{let chunk=ev.payload?.text??"";if(!chunk)return null;return count("stream:chunk"),{kind:"message.delta",chunk}}case"message.complete":{count("stream:done"),mem("stream-done");let p=ev.payload;if(p?.usage)side.onUsage?.(p.usage);if(side.onTurnComplete?.(),p?.status==="error")return{kind:"error",text:p.text||"request failed \u2014 see messages above"};if(p?.status==="interrupted")return{kind:"message.complete",text:(p.text||"")+`
4200
4203
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herm-tui",
3
- "version": "1.9.0-dev.32",
3
+ "version": "1.9.0-dev.34",
4
4
  "description": "A modern TUI for Hermes Agent",
5
5
  "license": "MIT",
6
6
  "repository": {