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

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 +18 -15
  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"]}
@@ -4105,7 +4108,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
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
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(`
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(`
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(`
@@ -4184,7 +4187,7 @@ Usage:
4184
4187
 
4185
4188
  ${n} mapped \xB7 ${r.skipped.length} skipped (no herm equivalent)${r.skipped.length?`:
4186
4189
  ${r.skipped.slice(0,8).join(", ")}${r.skipped.length>8?", \u2026":""}`:""}`,yes:"import"}).then((ok)=>{if(openKeys(props.dialog),!ok)return;exports_preferences.set("keys",{...exports_preferences.get("keys")??{},...r.overrides}),toast.show({variant:"success",message:`Imported ${n} \xB7 skipped ${r.skipped.length}`})})};return useKeyboard((key4)=>{if(key4.name==="up")return setSel((s)=>Math.max(0,s-1));if(key4.name==="down")return setSel((s)=>Math.min(actionRows.length-1,s+1));if(key4.name==="return"&&cur)return rebind(cur.id);if(key4.name==="r"&&!key4.ctrl&&cur?.override){write(cur.id,void 0);return}if(key4.name==="o"&&!key4.ctrl)return importOc()}),$jsxs("box",{flexDirection:"column",width:78,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:$jsx("strong",{children:"Keybindings"})})}),$jsx("text",{fg:theme.textMuted,children:`leader = ${keys.print("leader")}`})]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:22,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((r,i)=>{if(r.type==="header")return $jsx("box",{height:1,marginTop:i>0?1:0,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:r.title})})},`h-${r.title}`);let ai=actionRows.findIndex((x2)=>x2.i===i),on=ai===sel,conf=conflictsWith(keys.table,r.id);return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseOver:()=>setSel(ai),onMouseDown:()=>{setSel(ai),rebind(r.id)},children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:on?theme.primary:theme.text,children:on?"\u25B8 ":" "})}),$jsx("box",{width:16,flexShrink:0,height:1,overflow:"hidden",children:$jsx("text",{fg:on?theme.accent:theme.text,children:print(r.chord,keys.print("leader"))||"\u2014"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:r.desc})}),$jsx("box",{width:5,flexShrink:0,flexDirection:"row",justifyContent:"flex-end",children:$jsxs("text",{children:[r.override?$jsx("span",{fg:theme.info,children:"\xB7 "}):null,conf.length>0?$jsx("span",{fg:theme.warning,children:"\u26A0"}):null]})})]},r.id)})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:curConflicts.length>0?$jsx("text",{fg:theme.warning,children:`\u26A0 shares ${keys.print(cur.id)} with: ${curConflicts.join(", ")}`}):$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select Enter rebind${cur?.override?" \xB7 r reset":""} \xB7 o import opencode \xB7 esc close \xB7 \xB7 = overridden`})})]})};function openKeys(dialog){dialog.replace($jsx(KeysDialog,{dialog}))}var ERRLIKE=/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i,LogsDialog=()=>{let theme=useTheme().theme,lines3=useGateway().tail(200).split(`
4187
- `).filter(Boolean);return $jsxs("box",{flexDirection:"column",width:110,height:Math.min(34,Math.max(8,lines3.length+5)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Gateway Logs"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[lines3.length," lines \xB7 stderr + protocol \xB7 Esc to close"]})}),$jsx("box",{height:1}),lines3.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No log output captured."})}):$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",children:lines3.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:ERRLIKE.test(l)?theme.error:theme.textMuted,children:l.length>106?l.slice(0,105)+"\u2026":l})},i))})})]})},openLogs=(dialog)=>dialog.replace($jsx(LogsDialog,{}));var import_react118=__toESM(require_react_production(),1);var ThemePickerDialog=({onConfirm})=>{let ctx=useTheme(),dialog=useDialog(),options=ctx.names.map((n)=>({title:n,value:n})),onMove=import_react118.useCallback((opt)=>{ctx.set(opt.value)},[ctx]),onSelect=import_react118.useCallback((opt)=>{ctx.set(opt.value),onConfirm(),dialog.clear()},[ctx,dialog,onConfirm]),flip=import_react118.useCallback(()=>{ctx.setMode(ctx.mode==="dark"?"light":"dark")},[ctx]),onKey=import_react118.useCallback((key4)=>{if(key4.name!=="tab")return!1;return flip(),!0},[flip]),footer=$jsx("box",{height:1,onMouseDown:flip,children:$jsxs("text",{fg:ctx.theme.textMuted,children:[$jsx("span",{children:"Mode: "}),$jsx("span",{fg:ctx.mode==="light"?ctx.theme.warning:ctx.theme.accent,children:ctx.mode}),$jsx("span",{children:" \xB7 Tab/click: toggle"})]})});return $jsx(DialogSelect,{title:"Switch Theme",options,current:ctx.name,onSelect,onMove,onKey,placeholder:"Search themes...",footer})},openThemePicker=(dialog,ctx)=>{let{name:saved,mode}=ctx,confirmed=!1;dialog.replace($jsx(ThemePickerDialog,{onConfirm:()=>{confirmed=!0}}),()=>{if(confirmed)return;ctx.set(saved),ctx.setMode(mode)})};var import_react119=__toESM(require_react_production(),1);import{homedir as homedir8}from"os";import{join as join23}from"path";var trunc6=(s,n)=>s.length<=n?s:s.slice(0,n-1)+"\u2026",defaultDirs=()=>{let hermesHome2=process.env.HERMES_HOME||join23(homedir8(),".hermes");return[BUNDLED_EIKON_DIR,join23(hermesHome2,"eikons")]},EikonPickerDialog=(props)=>{let theme=useTheme().theme,dialog=useDialog(),dirs2=props.dirs??defaultDirs(),found2=import_react119.useMemo(()=>listEikons(dirs2),[dirs2]),[cursor,setCursor]=import_react119.useState(0),cur=found2[cursor],parsed=import_react119.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]);useListKeys({active:!0,count:found2.length,setSel:setCursor,onActivate:()=>{if(cur)props.onSelect(cur.meta.name.toLowerCase()),dialog.clear()}});let w2=(parsed?.meta.width??48)+2,h2=Math.max(parsed?.meta.height??24,12);return $jsxs("box",{flexDirection:"column",width:40+w2,height:h2+4,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Pick Avatar"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${found2.length} found \xB7 \u2191\u2193 nav \xB7 Enter select \xB7 Esc close`})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx("box",{width:38,marginRight:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:found2.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No .eikon files found."})},"empty"):found2.map((e,i)=>{let on=i===cursor;return $jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>setCursor(i),children:[$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:$jsx("strong",{children:trunc6(e.meta.name,34)})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${e.meta.author??"\u2014"} \xB7 ${e.meta.states.length} states`})})]},e.path)})})})}),$jsx("box",{flexGrow:1,flexDirection:"column",overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur?.path??"none"):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No preview."})},"blank")})]})]})},openEikonPicker=(dialog,onSelect)=>dialog.replace($jsx(EikonPickerDialog,{onSelect}));var import_react120=__toESM(require_react_production(),1);var RollbackDialog=(props)=>{let theme=useTheme().theme,[data2,setData]=import_react120.useState(props.initial??null),[sel,setSel]=import_react120.useState(props.sel??0),[diff,setDiff]=import_react120.useState(null),[confirm,setConfirm]=import_react120.useState(!1);import_react120.useEffect(()=>{if(props.initial)return;props.gw.request("rollback.list").then(setData).catch((e)=>setData({enabled:!1,checkpoints:[],...{err:e.message}}))},[props.gw,props.initial]);let points=data2?.checkpoints??[],cur=points[sel],open2=(cp)=>{props.gw.request("rollback.diff",{hash:cp.hash}).then(setDiff).catch((e)=>props.toast.error(e))},back=()=>{setDiff(null),setConfirm(!1),props.dialog.replace($jsx(RollbackDialog,{gw:props.gw,toast:props.toast,dialog:props.dialog,initial:data2??void 0,sel}))},restore=(cp)=>{props.gw.request("rollback.restore",{hash:cp.hash}).then((r)=>{if(!r.success)throw Error("restore rejected");let n=r.history_removed;props.toast.show({variant:"success",message:`Restored ${cp.hash.slice(0,7)}${n?` \xB7 ${n} turns removed`:""}`}),props.dialog.clear()}).catch((e)=>{props.toast.show({variant:"error",message:`Restore failed: ${e.message}`}),props.dialog.clear()})},keys=useKeys();if(useKeyboard((key4)=>{if(diff){if(confirm){if(keys.match("dialog.confirm",key4))return restore(cur);if(keys.match("dialog.deny",key4)||keys.match("dialog.cancel",key4))return setConfirm(!1),back();return}if(keys.match("dialog.cancel",key4))return back();if(key4.name==="r")return setConfirm(!0);return}if(!data2?.enabled)return;handleListKey(keys,key4,{count:points.length,setSel,onActivate:()=>{if(cur)open2(cur)}})}),!data2)return $jsx("box",{width:60,height:3,children:$jsx("text",{fg:theme.textMuted,children:"Loading checkpoints\u2026"})});if(!data2.enabled)return $jsxs("box",{flexDirection:"column",width:60,height:5,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Checkpoints disabled"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enable checkpoints in config to use /rollback."})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to close"})})]});if(diff){let body=diff.rendered||diff.diff||diff.stat||"(empty diff)";return $jsxs("box",{flexDirection:"column",width:110,height:30,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Rollback \xB7 "})}),$jsx("span",{fg:theme.accent,children:cur.hash.slice(0,7)}),$jsx("span",{fg:theme.textMuted,children:` ${trunc5(cur.message,70)}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:diff.stat||" "})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx(DiffBlock,{text:body})})}),$jsx("box",{height:1}),confirm?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.warning,children:$jsx("strong",{children:"Restore this checkpoint? "})}),$jsx("span",{fg:theme.textMuted,children:"[y] restore [n] cancel"})]})}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[r] restore \xB7 Esc back"})})]})}return $jsxs("box",{flexDirection:"column",width:90,height:Math.min(28,Math.max(8,points.length+6)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Rollback"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${points.length} checkpoints \xB7 \u2191\u2193 navigate Enter diff Esc close`})}),$jsx("box",{height:1}),points.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No checkpoints yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:points.map((cp,i)=>{let on=i===sel;return $jsx("box",{height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),open2(cp)},onMouseOver:()=>setSel(i),children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx("span",{fg:theme.accent,children:cp.hash.slice(0,7).padEnd(9)}),$jsx("span",{fg:theme.textMuted,children:ago(cp.timestamp).padEnd(12)}),$jsx("span",{fg:on?theme.text:theme.textMuted,children:trunc5(cp.message,56)})]})},cp.hash)})})})]})},openRollback=(dialog,gw,toast)=>dialog.replace($jsx(RollbackDialog,{gw,toast,dialog}));var import_react122=__toESM(require_react_production(),1);var tag=(m2,theme)=>m2.role==="user"?{label:"\u25B8 You",fg:theme.info}:m2.role==="assistant"?{label:"\u25C2 Agent",fg:theme.success}:m2.role==="tool"?{label:`\u2699 ${m2.name??"tool"}`,fg:theme.warning}:{label:"\xB7 system",fg:theme.textMuted},flatten2=(t2)=>{if(typeof t2==="string")return t2;if(!Array.isArray(t2))return"";for(let p of t2)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")return p.text;return""},body=(m2)=>m2.role==="tool"?m2.context??"":flatten2(m2.text),HistoryDialog=(props)=>{let theme=useTheme().theme,[rows3,setRows]=import_react122.useState(null),[err,setErr]=import_react122.useState("");import_react122.useEffect(()=>{props.gw.request("session.history").then((r)=>setRows(r.messages??[])).catch((e)=>{setErr(e.message),setRows([])})},[props.gw]);let n=rows3?.length??0,h2=Math.min(34,Math.max(8,n+5));return $jsxs("box",{flexDirection:"column",width:110,height:h2,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Session History"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:err?theme.error:theme.textMuted,children:err?`\u26A0 ${err}`:`${n} messages \xB7 server-authoritative \xB7 Esc to close`})}),$jsx("box",{height:1}),rows3===null?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading\u2026"})}):n===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Empty \u2014 no turns yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",children:rows3.map((m2,i)=>{let t2=tag(m2,theme);return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:14,flexShrink:0,children:$jsx("text",{fg:t2.fg,children:trunc5(t2.label,13)})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:m2.role==="tool"||m2.role==="system"?theme.textMuted:theme.text,children:body(m2).replace(/\n/g," ")})})]},i)})})})]})},openHistory=(dialog,gw)=>dialog.replace($jsx(HistoryDialog,{gw}));var import_react123=__toESM(require_react_production(),1);var InfoDialog=(props)=>{let theme=useTheme().theme,body2=props.rows.filter((r)=>r[1]!==void 0);return $jsxs("box",{flexDirection:"column",minWidth:52,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),props.lines?.length?$jsx("box",{flexDirection:"column",children:props.lines.map((line4,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.text,children:line4})},i))}):null,$jsx("box",{flexDirection:"column",children:$jsx(KVBlock,{rows:body2})}),props.note?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.note})}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"Esc to close"})})]})};function openStatus(dialog,info3,sid2){let toolsets=Object.keys(info3?.tools??{}),nTools=Object.values(info3?.tools??{}).reduce((n,v2)=>n+v2.length,0),mcp=info3?.mcp_servers??[],up=mcp.filter((s)=>s.connected).length;dialog.replace($jsx(InfoDialog,{title:"Status",rows:[["Version",info3?.version||"\u2014"],["Model",info3?.model||"\u2014"],["Profile",activeProfileName()],["Home",hermesPath("")],["CWD",info3?.cwd||process.cwd()],["Session",sid2||"\u2014"],["Tools",`${nTools} in ${toolsets.length} toolset${toolsets.length===1?"":"s"}`],["Skills",String(Object.values(info3?.skills??{}).reduce((n,v2)=>n+v2.length,0))],["MCP",mcp.length?`${up}/${mcp.length} connected`:void 0]]}))}var UsageDialog=({gw})=>{let theme=useTheme().theme,[u3,setU]=import_react123.useState(null),[err,setErr]=import_react123.useState("");if(import_react123.useEffect(()=>{gw.request("session.usage").then(setU).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]),err)return $jsx(InfoDialog,{title:"Usage",rows:[["Error",err,theme.error]]});if(!u3)return $jsx(InfoDialog,{title:"Usage",rows:[["","\u2026"]]});let ctx=u3.context_max?`${fmt(u3.context_used??0)} / ${fmt(u3.context_max)} (${Math.round(u3.context_percent??0)}%)`:void 0;return $jsx(InfoDialog,{title:"Usage",lines:u3.credits_lines,note:u3.cost_status==="estimated"?"cost is estimated":void 0,rows:[["Model",u3.model||"\u2014"],["API calls",String(u3.calls??0)],["Input",fmt(u3.input??0)],["Output",fmt(u3.output??0)],["Cache r/w",u3.cache_read||u3.cache_write?`${fmt(u3.cache_read??0)} / ${fmt(u3.cache_write??0)}`:void 0],["Reasoning",u3.reasoning?fmt(u3.reasoning):void 0],["Total",fmt(u3.total??0)],["Context",ctx],["Cost",u3.cost_usd!=null?cost2(u3.cost_usd):void 0,theme.accent]]})},openUsage=(dialog,gw)=>dialog.replace($jsx(UsageDialog,{gw})),ProfileDialog=()=>{let[p,setP]=import_react123.useState(void 0),active=activeProfileName();if(import_react123.useEffect(()=>{listProfiles().then((ps)=>setP(ps.find((x2)=>x2.name===active)??null)).catch(()=>setP(null))},[]),p===void 0)return $jsx(InfoDialog,{title:"Profile",rows:[["","\u2026"]]});return $jsx(InfoDialog,{title:"Profile",note:p?void 0:"profile directory not found",rows:[["Active",active],["Home",p?.path??hermesPath("")],["Model",p?.model??"\u2014"],["Provider",p?.provider??"\u2014"],["Skills",p?String(p.skill_count):void 0],["Gateway",p?.gateway_running?"running":"stopped"],["Sticky",p?.is_sticky?"yes":void 0],["Alias",p?.is_default?void 0:p?.has_alias?`~/.local/bin/${active}`:"\u2014"],[".env",p?.has_env?"present":"\u2014"]]})},openProfile=(dialog)=>dialog.replace($jsx(ProfileDialog,{}));var import_react124=__toESM(require_react_production(),1);import{spawnSync as spawnSync3}from"child_process";import{existsSync as existsSync25}from"fs";var CHAFA=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa"];function whichChafa(){for(let p of CHAFA)if(existsSync25(p))return p;return null}function render(path7,w2,h2){let bin=whichChafa();if(!bin)return{err:"chafa not installed (brew/apt install chafa)"};let full=path7.startsWith("~")?path7.replace(/^~/,process.env.HOME??""):path7;if(!existsSync25(full))return{err:`file not found: ${full}`};let r=spawnSync3(bin,[`--size=${w2}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8"});if(r.status!==0)return{err:r.stderr||`chafa exit ${r.status}`};return{rows:parseChafa(r.stdout)}}var ChafaDialog=({path:path7})=>{let theme=useTheme().theme,[w2]=import_react124.useState(80),[h2]=import_react124.useState(28),result=import_react124.useMemo(()=>render(path7,w2,h2),[path7,w2,h2]);return $jsxs("box",{flexDirection:"column",minWidth:w2+4,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsxs("strong",{children:["chafa demo \xB7 ",path7]})})}),result.err?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:result.err})}):$jsx("box",{flexDirection:"column",children:result.rows.map((row4,i)=>$jsx("text",{children:row4.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.borderSubtle,children:[result.rows?`${result.rows.length} rows \xB7 ${result.rows.reduce((a,r)=>a+r.length,0)} cells \xB7 `:"","Esc to close"]})})]})};function openChafa(dialog,path7){dialog.replace($jsx(ChafaDialog,{path:path7}))}var import_react126=__toESM(require_react_production(),1);import{tmpdir as tmpdir6}from"os";import{join as join24}from"path";import{rm}from"fs/promises";async function editInEditor(renderer,seed){let cmd=process.env.VISUAL||process.env.EDITOR;if(!cmd)return;let path7=join24(tmpdir6(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text4=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text4.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text4.trim()||void 0}var exports_selection={};__export(exports_selection,{yank:()=>yank,key:()=>key4,Selection:()=>exports_selection});function yank(renderer,toast){let text4=renderer.getSelection()?.getSelectedText();if(!text4)return!1;return copy2(text4).then(()=>toast?.push("Copied to clipboard","info")).catch(()=>toast?.push("Clipboard write failed","err")),renderer.clearSelection(),!0}function key4(renderer,evt,toast){let sel=renderer.getSelection();if(!sel?.getSelectedText())return!1;if(evt.ctrl&&evt.name==="c")return yank(renderer,toast),!0;if(evt.name==="escape")return renderer.clearSelection(),!0;let focus=renderer.currentFocusedRenderable;if(focus&&sel.selectedRenderables.includes(focus))return!1;return renderer.clearSelection(),!1}var SGR_MOUSE_BLOB_RE=/^(?:\x1b\[|\^\[\[)?<?\d+(?:;\d+){1,2}[Mm]$/,SGR_MOUSE_RESIDUE_RE=/^\d+(?:;\d+){1,2}[Mm]$/;function isDegradedMouseInput(key5){return[key5.raw,key5.sequence,key5.name].some((v2)=>typeof v2==="string"&&isDegradedMouseBlob(v2))}function isDegradedMouseBlob(text4){if(!text4||/\s/.test(text4))return!1;return SGR_MOUSE_BLOB_RE.test(text4)||SGR_MOUSE_RESIDUE_RE.test(text4)}var DEFAULT_VOICE_KEY={mod:"ctrl",ch:"b",raw:"ctrl+b"},MOD_ALIASES={alt:"alt",ctrl:"ctrl",control:"ctrl",option:"alt",opt:"alt"};function parseVoiceRecordKey(raw2){if(typeof raw2!=="string"||!raw2.trim())return DEFAULT_VOICE_KEY;let lower=raw2.trim().toLowerCase(),parts2=lower.split("+").map((p)=>p.trim()).filter(Boolean);if(parts2.length<2)return DEFAULT_VOICE_KEY;if(parts2.length>2)return DEFAULT_VOICE_KEY;let[modRaw,chRaw]=parts2,mod=MOD_ALIASES[modRaw];if(!mod)return DEFAULT_VOICE_KEY;if(chRaw.length!==1)return DEFAULT_VOICE_KEY;if(mod==="ctrl"&&(chRaw==="c"||chRaw==="d"||chRaw==="l"))return DEFAULT_VOICE_KEY;return{mod,ch:chRaw,raw:lower}}function formatVoiceRecordKey(v2){return`${v2.mod[0].toUpperCase()+v2.mod.slice(1)}+${v2.ch.toUpperCase()}`}function isVoiceToggleKey(key5,configured2=DEFAULT_VOICE_KEY){if(key5.name.toLowerCase()!==configured2.ch)return!1;if(key5.shift)return!1;switch(configured2.mod){case"ctrl":return key5.ctrl&&!key5.meta&&!key5.super;case"alt":return key5.meta&&!key5.ctrl&&!key5.super}}function redraw(renderer){resolveRenderLib().clearTerminal(renderer.rendererPtr),renderer.currentRenderBuffer.clear(RGBA.fromValues(0,0,0,0)),renderer.requestRender()}var INTERRUPT_MS=5000,DOUBLE_TAB_MS=400,QUIT_MS=2000;function useAppKeys(o){let renderer=useRenderer(),keys=useKeys(),lastEsc=import_react126.useRef(0),lastTab=import_react126.useRef(0),lastQuit=import_react126.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react126.useEffect(()=>{let found2=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found2.length===0)return;let first=found2[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found2.length>1?` (+${found2.length-1} more)`:""))},[keys.table]),useKeyboard((key5)=>{let c=o.composer.current;if(isDegradedMouseInput(key5)){key5.stopPropagation();return}if(exports_selection.key(renderer,key5)){key5.stopPropagation();return}if(keys.match("input.clear",key5)&&c&&!c.isEmpty()){let v2=c.value().trim();if(v2.length>=20)c.remember(v2);c.set(""),lastQuit.current=0,key5.stopPropagation();return}if(keys.match("input.stash",key5)){o.onStash(),key5.stopPropagation();return}if(keys.match("app.exit",key5)){let now2=Date.now();if(now2-lastQuit.current<QUIT_MS)return o.onQuit();lastQuit.current=now2,o.onQuitArm(keys.print("app.exit")),key5.stopPropagation();return}if(keys.match("app.suspend",key5)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key5)){redraw(renderer),key5.stopPropagation();return}if(keys.match("app.sidebar",key5)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(o.voiceRecordKey&&o.onVoiceRecord&&isVoiceToggleKey(key5,o.voiceRecordKey)){o.onVoiceRecord(),key5.stopPropagation();return}if(c?.mode()==="shell"){if(key5.name==="escape"){c.setMode("normal"),key5.stopPropagation();return}if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c.caret()===0){c.setMode("normal"),key5.stopPropagation();return}}if(keys.match("session.steer",key5)){o.onSteer(),key5.stopPropagation();return}if(keys.match("queue.flush",key5)&&o.streaming&&o.queued>0){o.onFlushQueue(),key5.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(o.onPromptKey(key5)){key5.stopPropagation();return}}if(keys.match("editor.open",key5)&&!o.streaming){let seed=c?.value()??"";editInEditor(renderer,seed).then((out)=>{if(out===void 0){if(!process.env.VISUAL&&!process.env.EDITOR)o.onNotice("Set $EDITOR or $VISUAL to use the external editor");return}c?.set(out),o.setFocusRegion("input")});return}if(keys.match("tab.prev",key5)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key5)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key5.shift&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name==="left"){o.cycleSub(-1),key5.stopPropagation();return}if(key5.name==="right"){o.cycleSub(1),key5.stopPropagation();return}}if(keys.leader&&!key5.ctrl&&!key5.meta&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(key5.meta&&!key5.ctrl&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(c?.popOpen()){if(key5.name==="escape")return c.popCancel();if(key5.name==="up"){c.popNav(-1),key5.stopPropagation();return}if(key5.name==="down"){c.popNav(1),key5.stopPropagation();return}if(key5.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key5)&&!o.streaming){if(o.tab===o.chatTab){o.setFocusRegion((r)=>r==="input"?"content":"input");return}if(o.focusRegion==="input"){o.setFocusRegion("content");return}let now2=Date.now();if(now2-lastTab.current<DOUBLE_TAB_MS)o.setFocusRegion("input"),lastTab.current=0,key5.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key5)){if(!o.streaming&&o.onEscape?.())return;if(o.streaming){let now2=Date.now();if(now2-lastEsc.current<INTERRUPT_MS){o.onInterrupt(),lastEsc.current=0;return}lastEsc.current=now2,o.onInterruptNotice();return}if(o.tab===o.chatTab&&o.focusRegion==="content")o.setFocusRegion("input");return}if(keys.match("reply.copy",key5))return o.onCopyLast();if(keys.match("clipboard.attach",key5)){o.onAttachClipboard(),key5.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if((key5.name==="!"||key5.name==="1"&&key5.shift)&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"&&c&&c.mode()==="normal"&&!c.popOpen()&&c.caret()===0){c.setMode("shell"),key5.stopPropagation();return}if(key5.name==="up")return void c?.historyUp();if(key5.name==="down")return void c?.historyDown();if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c?.isEmpty()&&o.onDetachLast()){key5.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name.length===1&&key5.name!==" "){let ch=key5.shift&&/[a-z]/.test(key5.name)?key5.name.toUpperCase():key5.name;o.setFocusRegion("input"),c?.insert(ch),key5.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid2,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY){let banner=sid2?`
4190
+ `).filter(Boolean);return $jsxs("box",{flexDirection:"column",width:110,height:Math.min(34,Math.max(8,lines3.length+5)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Gateway Logs"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[lines3.length," lines \xB7 stderr + protocol \xB7 Esc to close"]})}),$jsx("box",{height:1}),lines3.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No log output captured."})}):$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",children:lines3.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:ERRLIKE.test(l)?theme.error:theme.textMuted,children:l.length>106?l.slice(0,105)+"\u2026":l})},i))})})]})},openLogs=(dialog)=>dialog.replace($jsx(LogsDialog,{}));var import_react118=__toESM(require_react_production(),1);var ThemePickerDialog=({onConfirm})=>{let ctx=useTheme(),dialog=useDialog(),options=ctx.names.map((n)=>({title:n,value:n})),onMove=import_react118.useCallback((opt)=>{ctx.set(opt.value)},[ctx]),onSelect=import_react118.useCallback((opt)=>{ctx.set(opt.value),onConfirm(),dialog.clear()},[ctx,dialog,onConfirm]),flip=import_react118.useCallback(()=>{ctx.setMode(ctx.mode==="dark"?"light":"dark")},[ctx]),onKey=import_react118.useCallback((key4)=>{if(key4.name!=="tab")return!1;return flip(),!0},[flip]),footer=$jsx("box",{height:1,onMouseDown:flip,children:$jsxs("text",{fg:ctx.theme.textMuted,children:[$jsx("span",{children:"Mode: "}),$jsx("span",{fg:ctx.mode==="light"?ctx.theme.warning:ctx.theme.accent,children:ctx.mode}),$jsx("span",{children:" \xB7 Tab/click: toggle"})]})});return $jsx(DialogSelect,{title:"Switch Theme",options,current:ctx.name,onSelect,onMove,onKey,placeholder:"Search themes...",footer})},openThemePicker=(dialog,ctx)=>{let{name:saved,mode}=ctx,confirmed=!1;dialog.replace($jsx(ThemePickerDialog,{onConfirm:()=>{confirmed=!0}}),()=>{if(confirmed)return;ctx.set(saved),ctx.setMode(mode)})};var import_react119=__toESM(require_react_production(),1);import{homedir as homedir8}from"os";import{join as join23}from"path";var trunc6=(s,n)=>s.length<=n?s:s.slice(0,n-1)+"\u2026",defaultDirs=()=>{let hermesHome2=process.env.HERMES_HOME||join23(homedir8(),".hermes");return[BUNDLED_EIKON_DIR,join23(hermesHome2,"eikons")]},EikonPickerDialog=(props)=>{let theme=useTheme().theme,dialog=useDialog(),dirs2=props.dirs??defaultDirs(),found2=import_react119.useMemo(()=>listEikons(dirs2),[dirs2]),[cursor,setCursor]=import_react119.useState(0),cur=found2[cursor],parsed=import_react119.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]);useListKeys({active:!0,count:found2.length,setSel:setCursor,onActivate:()=>{if(cur)props.onSelect(cur.meta.name.toLowerCase()),dialog.clear()}});let w2=(parsed?.meta.width??48)+2,h2=Math.max(parsed?.meta.height??24,12);return $jsxs("box",{flexDirection:"column",width:40+w2,height:h2+4,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Pick Avatar"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${found2.length} found \xB7 \u2191\u2193 nav \xB7 Enter select \xB7 Esc close`})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx("box",{width:38,marginRight:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:found2.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No .eikon files found."})},"empty"):found2.map((e,i)=>{let on=i===cursor;return $jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>setCursor(i),children:[$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:$jsx("strong",{children:trunc6(e.meta.name,34)})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${e.meta.author??"\u2014"} \xB7 ${e.meta.states.length} states`})})]},e.path)})})})}),$jsx("box",{flexGrow:1,flexDirection:"column",overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur?.path??"none"):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No preview."})},"blank")})]})]})},openEikonPicker=(dialog,onSelect)=>dialog.replace($jsx(EikonPickerDialog,{onSelect}));var import_react120=__toESM(require_react_production(),1);var RollbackDialog=(props)=>{let theme=useTheme().theme,[data2,setData]=import_react120.useState(props.initial??null),[sel,setSel]=import_react120.useState(props.sel??0),[diff,setDiff]=import_react120.useState(null),[confirm,setConfirm]=import_react120.useState(!1);import_react120.useEffect(()=>{if(props.initial)return;props.gw.request("rollback.list").then(setData).catch((e)=>setData({enabled:!1,checkpoints:[],...{err:e.message}}))},[props.gw,props.initial]);let points=data2?.checkpoints??[],cur=points[sel],open2=(cp)=>{props.gw.request("rollback.diff",{hash:cp.hash}).then(setDiff).catch((e)=>props.toast.error(e))},back=()=>{setDiff(null),setConfirm(!1),props.dialog.replace($jsx(RollbackDialog,{gw:props.gw,toast:props.toast,dialog:props.dialog,initial:data2??void 0,sel}))},restore=(cp)=>{props.gw.request("rollback.restore",{hash:cp.hash}).then((r)=>{if(!r.success)throw Error("restore rejected");let n=r.history_removed;props.toast.show({variant:"success",message:`Restored ${cp.hash.slice(0,7)}${n?` \xB7 ${n} turns removed`:""}`}),props.dialog.clear()}).catch((e)=>{props.toast.show({variant:"error",message:`Restore failed: ${e.message}`}),props.dialog.clear()})},keys=useKeys();if(useKeyboard((key4)=>{if(diff){if(confirm){if(keys.match("dialog.confirm",key4))return restore(cur);if(keys.match("dialog.deny",key4)||keys.match("dialog.cancel",key4))return setConfirm(!1),back();return}if(keys.match("dialog.cancel",key4))return back();if(key4.name==="r")return setConfirm(!0);return}if(!data2?.enabled)return;handleListKey(keys,key4,{count:points.length,setSel,onActivate:()=>{if(cur)open2(cur)}})}),!data2)return $jsx("box",{width:60,height:3,children:$jsx("text",{fg:theme.textMuted,children:"Loading checkpoints\u2026"})});if(!data2.enabled)return $jsxs("box",{flexDirection:"column",width:60,height:5,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Checkpoints disabled"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enable checkpoints in config to use /rollback."})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to close"})})]});if(diff){let body=diff.rendered||diff.diff||diff.stat||"(empty diff)";return $jsxs("box",{flexDirection:"column",width:110,height:30,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Rollback \xB7 "})}),$jsx("span",{fg:theme.accent,children:cur.hash.slice(0,7)}),$jsx("span",{fg:theme.textMuted,children:` ${trunc5(cur.message,70)}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:diff.stat||" "})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx(DiffBlock,{text:body})})}),$jsx("box",{height:1}),confirm?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.warning,children:$jsx("strong",{children:"Restore this checkpoint? "})}),$jsx("span",{fg:theme.textMuted,children:"[y] restore [n] cancel"})]})}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[r] restore \xB7 Esc back"})})]})}return $jsxs("box",{flexDirection:"column",width:90,height:Math.min(28,Math.max(8,points.length+6)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Rollback"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${points.length} checkpoints \xB7 \u2191\u2193 navigate Enter diff Esc close`})}),$jsx("box",{height:1}),points.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No checkpoints yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:points.map((cp,i)=>{let on=i===sel;return $jsx("box",{height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),open2(cp)},onMouseOver:()=>setSel(i),children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx("span",{fg:theme.accent,children:cp.hash.slice(0,7).padEnd(9)}),$jsx("span",{fg:theme.textMuted,children:ago(cp.timestamp).padEnd(12)}),$jsx("span",{fg:on?theme.text:theme.textMuted,children:trunc5(cp.message,56)})]})},cp.hash)})})})]})},openRollback=(dialog,gw,toast)=>dialog.replace($jsx(RollbackDialog,{gw,toast,dialog}));var import_react122=__toESM(require_react_production(),1);var tag=(m2,theme)=>m2.role==="user"?{label:"\u25B8 You",fg:theme.info}:m2.role==="assistant"?{label:"\u25C2 Agent",fg:theme.success}:m2.role==="tool"?{label:`\u2699 ${m2.name??"tool"}`,fg:theme.warning}:{label:"\xB7 system",fg:theme.textMuted},flatten2=(t2)=>{if(typeof t2==="string")return t2;if(!Array.isArray(t2))return"";for(let p of t2)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")return p.text;return""},body=(m2)=>m2.role==="tool"?m2.context??"":flatten2(m2.text),HistoryDialog=(props)=>{let theme=useTheme().theme,[rows3,setRows]=import_react122.useState(null),[err,setErr]=import_react122.useState("");import_react122.useEffect(()=>{props.gw.request("session.history").then((r)=>setRows(r.messages??[])).catch((e)=>{setErr(e.message),setRows([])})},[props.gw]);let n=rows3?.length??0,h2=Math.min(34,Math.max(8,n+5));return $jsxs("box",{flexDirection:"column",width:110,height:h2,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Session History"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:err?theme.error:theme.textMuted,children:err?`\u26A0 ${err}`:`${n} messages \xB7 server-authoritative \xB7 Esc to close`})}),$jsx("box",{height:1}),rows3===null?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading\u2026"})}):n===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Empty \u2014 no turns yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",children:rows3.map((m2,i)=>{let t2=tag(m2,theme);return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:14,flexShrink:0,children:$jsx("text",{fg:t2.fg,children:trunc5(t2.label,13)})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:m2.role==="tool"||m2.role==="system"?theme.textMuted:theme.text,children:body(m2).replace(/\n/g," ")})})]},i)})})})]})},openHistory=(dialog,gw)=>dialog.replace($jsx(HistoryDialog,{gw}));var import_react123=__toESM(require_react_production(),1);var InfoDialog=(props)=>{let theme=useTheme().theme,body2=props.rows.filter((r)=>r[1]!==void 0);return $jsxs("box",{flexDirection:"column",minWidth:52,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),props.lines?.length?$jsx("box",{flexDirection:"column",children:props.lines.map((line4,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.text,children:line4})},i))}):null,$jsx("box",{flexDirection:"column",children:$jsx(KVBlock,{rows:body2})}),props.note?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.note})}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"Esc to close"})})]})};function openStatus(dialog,info3,sid2){let toolsets=Object.keys(info3?.tools??{}),nTools=Object.values(info3?.tools??{}).reduce((n,v2)=>n+v2.length,0),mcp=info3?.mcp_servers??[],up=mcp.filter((s)=>s.connected).length;dialog.replace($jsx(InfoDialog,{title:"Status",rows:[["Version",info3?.version||"\u2014"],["Model",info3?.model||"\u2014"],["Profile",activeProfileName()],["Home",hermesPath("")],["CWD",info3?.cwd||process.cwd()],["Session",sid2||"\u2014"],["Tools",`${nTools} in ${toolsets.length} toolset${toolsets.length===1?"":"s"}`],["Skills",String(Object.values(info3?.skills??{}).reduce((n,v2)=>n+v2.length,0))],["MCP",mcp.length?`${up}/${mcp.length} connected`:void 0]]}))}var UsageDialog=({gw})=>{let theme=useTheme().theme,[u3,setU]=import_react123.useState(null),[err,setErr]=import_react123.useState("");if(import_react123.useEffect(()=>{gw.request("session.usage").then(setU).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]),err)return $jsx(InfoDialog,{title:"Usage",rows:[["Error",err,theme.error]]});if(!u3)return $jsx(InfoDialog,{title:"Usage",rows:[["","\u2026"]]});let ctx=u3.context_max?`${fmt(u3.context_used??0)} / ${fmt(u3.context_max)} (${Math.round(u3.context_percent??0)}%)`:void 0;return $jsx(InfoDialog,{title:"Usage",lines:u3.credits_lines,note:u3.cost_status==="estimated"?"cost is estimated":void 0,rows:[["Model",u3.model||"\u2014"],["API calls",String(u3.calls??0)],["Input",fmt(u3.input??0)],["Output",fmt(u3.output??0)],["Cache r/w",u3.cache_read||u3.cache_write?`${fmt(u3.cache_read??0)} / ${fmt(u3.cache_write??0)}`:void 0],["Reasoning",u3.reasoning?fmt(u3.reasoning):void 0],["Total",fmt(u3.total??0)],["Context",ctx],["Cost",u3.cost_usd!=null?cost2(u3.cost_usd):void 0,theme.accent]]})},openUsage=(dialog,gw)=>dialog.replace($jsx(UsageDialog,{gw})),ProfileDialog=()=>{let[p,setP]=import_react123.useState(void 0),active=activeProfileName();if(import_react123.useEffect(()=>{listProfiles().then((ps)=>setP(ps.find((x2)=>x2.name===active)??null)).catch(()=>setP(null))},[]),p===void 0)return $jsx(InfoDialog,{title:"Profile",rows:[["","\u2026"]]});return $jsx(InfoDialog,{title:"Profile",note:p?void 0:"profile directory not found",rows:[["Active",active],["Home",p?.path??hermesPath("")],["Model",p?.model??"\u2014"],["Provider",p?.provider??"\u2014"],["Skills",p?String(p.skill_count):void 0],["Gateway",p?.gateway_running?"running":"stopped"],["Sticky",p?.is_sticky?"yes":void 0],["Alias",p?.is_default?void 0:p?.has_alias?`~/.local/bin/${active}`:"\u2014"],[".env",p?.has_env?"present":"\u2014"]]})},openProfile=(dialog)=>dialog.replace($jsx(ProfileDialog,{}));var import_react124=__toESM(require_react_production(),1);import{spawnSync as spawnSync3}from"child_process";import{existsSync as existsSync25}from"fs";var CHAFA=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa"];function whichChafa(){for(let p of CHAFA)if(existsSync25(p))return p;return null}function render(path7,w2,h2){let bin=whichChafa();if(!bin)return{err:"chafa not installed (brew/apt install chafa)"};let full=path7.startsWith("~")?path7.replace(/^~/,process.env.HOME??""):path7;if(!existsSync25(full))return{err:`file not found: ${full}`};let r=spawnSync3(bin,[`--size=${w2}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8"});if(r.status!==0)return{err:r.stderr||`chafa exit ${r.status}`};return{rows:parseChafa(r.stdout)}}var ChafaDialog=({path:path7})=>{let theme=useTheme().theme,[w2]=import_react124.useState(80),[h2]=import_react124.useState(28),result=import_react124.useMemo(()=>render(path7,w2,h2),[path7,w2,h2]);return $jsxs("box",{flexDirection:"column",minWidth:w2+4,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsxs("strong",{children:["chafa demo \xB7 ",path7]})})}),result.err?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:result.err})}):$jsx("box",{flexDirection:"column",children:result.rows.map((row4,i)=>$jsx("text",{children:row4.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.borderSubtle,children:[result.rows?`${result.rows.length} rows \xB7 ${result.rows.reduce((a,r)=>a+r.length,0)} cells \xB7 `:"","Esc to close"]})})]})};function openChafa(dialog,path7){dialog.replace($jsx(ChafaDialog,{path:path7}))}var import_react126=__toESM(require_react_production(),1);import{tmpdir as tmpdir6}from"os";import{join as join24}from"path";import{rm}from"fs/promises";async function editInEditor(renderer,seed){let cmd=process.env.VISUAL||process.env.EDITOR;if(!cmd)return;let path7=join24(tmpdir6(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text4=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text4.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text4.trim()||void 0}var exports_selection={};__export(exports_selection,{yank:()=>yank,key:()=>key4,Selection:()=>exports_selection});function yank(renderer,toast){let text4=renderer.getSelection()?.getSelectedText();if(!text4)return!1;return copy2(text4).then(()=>toast?.push("Copied to clipboard","info")).catch(()=>toast?.push("Clipboard write failed","err")),renderer.clearSelection(),!0}function key4(renderer,evt,toast){let sel=renderer.getSelection();if(!sel?.getSelectedText())return!1;if(evt.ctrl&&evt.name==="c")return yank(renderer,toast),!0;if(evt.name==="escape")return renderer.clearSelection(),!0;let focus=renderer.currentFocusedRenderable;if(focus&&sel.selectedRenderables.includes(focus))return!1;return renderer.clearSelection(),!1}var SGR_MOUSE_BLOB_RE=/^(?:\x1b\[|\^\[\[)?<?\d+(?:;\d+){1,2}[Mm]$/,SGR_MOUSE_RESIDUE_RE=/^\d+(?:;\d+){1,2}[Mm]$/;function isDegradedMouseInput(key5){return[key5.raw,key5.sequence,key5.name].some((v2)=>typeof v2==="string"&&isDegradedMouseBlob(v2))}function isDegradedMouseBlob(text4){if(!text4||/\s/.test(text4))return!1;return SGR_MOUSE_BLOB_RE.test(text4)||SGR_MOUSE_RESIDUE_RE.test(text4)}var DEFAULT_VOICE_KEY={mod:"ctrl",ch:"b",raw:"ctrl+b"},MOD_ALIASES={alt:"alt",ctrl:"ctrl",control:"ctrl",option:"alt",opt:"alt"};function parseVoiceRecordKey(raw2){if(typeof raw2!=="string"||!raw2.trim())return DEFAULT_VOICE_KEY;let lower=raw2.trim().toLowerCase(),parts2=lower.split("+").map((p)=>p.trim()).filter(Boolean);if(parts2.length<2)return DEFAULT_VOICE_KEY;if(parts2.length>2)return DEFAULT_VOICE_KEY;let[modRaw,chRaw]=parts2,mod=MOD_ALIASES[modRaw];if(!mod)return DEFAULT_VOICE_KEY;if(chRaw.length!==1)return DEFAULT_VOICE_KEY;if(mod==="ctrl"&&(chRaw==="c"||chRaw==="d"||chRaw==="l"))return DEFAULT_VOICE_KEY;return{mod,ch:chRaw,raw:lower}}function formatVoiceRecordKey(v2){return`${v2.mod[0].toUpperCase()+v2.mod.slice(1)}+${v2.ch.toUpperCase()}`}function isVoiceToggleKey(key5,configured2=DEFAULT_VOICE_KEY){if(key5.name.toLowerCase()!==configured2.ch)return!1;if(key5.shift)return!1;switch(configured2.mod){case"ctrl":return key5.ctrl&&!key5.meta&&!key5.super;case"alt":return key5.meta&&!key5.ctrl&&!key5.super}}function redraw(renderer){resolveRenderLib().clearTerminal(renderer.rendererPtr),renderer.currentRenderBuffer.clear(RGBA.fromValues(0,0,0,0)),renderer.requestRender()}var INTERRUPT_MS=5000,DOUBLE_TAB_MS=400,QUIT_MS=2000;function useAppKeys(o){let renderer=useRenderer(),keys=useKeys(),lastEsc=import_react126.useRef(0),lastTab=import_react126.useRef(0),lastQuit=import_react126.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react126.useEffect(()=>{let found2=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found2.length===0)return;let first=found2[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found2.length>1?` (+${found2.length-1} more)`:""))},[keys.table]),useKeyboard((key5)=>{let c=o.composer.current;if(isDegradedMouseInput(key5)){key5.stopPropagation();return}if(exports_selection.key(renderer,key5)){key5.stopPropagation();return}if(keys.match("input.clear",key5)&&c&&!c.isEmpty()){let v2=c.value().trim();if(v2.length>=20)c.remember(v2);c.set(""),lastQuit.current=0,key5.stopPropagation();return}if(keys.match("input.stash",key5)){o.onStash(),key5.stopPropagation();return}if(keys.match("app.exit",key5)){let now2=Date.now();if(now2-lastQuit.current<QUIT_MS)return o.onQuit();lastQuit.current=now2,o.onQuitArm(keys.print("app.exit")),key5.stopPropagation();return}if(keys.match("app.suspend",key5)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key5)){redraw(renderer),key5.stopPropagation();return}if(keys.match("app.sidebar",key5)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(o.voiceRecordKey&&o.onVoiceRecord&&isVoiceToggleKey(key5,o.voiceRecordKey)){o.onVoiceRecord(),key5.stopPropagation();return}if(c?.mode()==="shell"){if(key5.name==="escape"){c.setMode("normal"),key5.stopPropagation();return}if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c.caret()===0){c.setMode("normal"),key5.stopPropagation();return}}if(keys.match("session.steer",key5)){o.onSteer(),key5.stopPropagation();return}if(keys.match("queue.flush",key5)&&o.streaming&&o.queued>0){o.onFlushQueue(),key5.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(o.onPromptKey(key5)){key5.stopPropagation();return}}if(keys.match("editor.open",key5)&&!o.streaming){let seed=c?.value()??"";editInEditor(renderer,seed).then((out)=>{if(out===void 0){if(!process.env.VISUAL&&!process.env.EDITOR)o.onNotice("Set $EDITOR or $VISUAL to use the external editor");return}c?.set(out),o.setFocusRegion("input")});return}if(keys.match("tab.prev",key5)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key5)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key5.shift&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name==="left"){o.cycleSub(-1),key5.stopPropagation();return}if(key5.name==="right"){o.cycleSub(1),key5.stopPropagation();return}}if(keys.leader&&!key5.ctrl&&!key5.meta&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(key5.meta&&!key5.ctrl&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(c?.popOpen()){if(key5.name==="escape"){c.popCancel(),key5.stopPropagation();return}if(key5.name==="up"){c.popNav(-1),key5.stopPropagation();return}if(key5.name==="down"){c.popNav(1),key5.stopPropagation();return}if(key5.name==="tab"||key5.name==="return"){c.popAccept(),key5.stopPropagation();return}return}if(keys.match("focus.cycle",key5)&&!o.streaming){if(o.tab===o.chatTab){o.setFocusRegion((r)=>r==="input"?"content":"input");return}if(o.focusRegion==="input"){o.setFocusRegion("content");return}let now2=Date.now();if(now2-lastTab.current<DOUBLE_TAB_MS)o.setFocusRegion("input"),lastTab.current=0,key5.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key5)){if(!o.streaming&&o.onEscape?.())return;if(o.streaming){let now2=Date.now();if(now2-lastEsc.current<INTERRUPT_MS){o.onInterrupt(),lastEsc.current=0;return}lastEsc.current=now2,o.onInterruptNotice();return}if(o.tab===o.chatTab&&o.focusRegion==="content")o.setFocusRegion("input");return}if(keys.match("reply.copy",key5))return o.onCopyLast();if(keys.match("clipboard.attach",key5)){o.onAttachClipboard(),key5.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if((key5.name==="!"||key5.name==="1"&&key5.shift)&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"&&c&&c.mode()==="normal"&&!c.popOpen()&&c.caret()===0){c.setMode("shell"),key5.stopPropagation();return}if(key5.name==="up"){let before=c?.value();return void(c?.historyUp()&&c?.value()!==before&&key5.stopPropagation())}if(key5.name==="down"){let before=c?.value();return void(c?.historyDown()&&c?.value()!==before&&key5.stopPropagation())}if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c?.isEmpty()&&o.onDetachLast()){key5.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name.length===1&&key5.name!==" "){let ch=key5.shift&&/[a-z]/.test(key5.name)?key5.name.toUpperCase():key5.name;o.setFocusRegion("input"),c?.insert(ch),key5.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid2,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY){let banner=sid2?`
4188
4191
  continue herm --resume ${sid2}${title?` \u2014 ${title.slice(0,60)}`:""}
4189
4192
 
4190
4193
  `:`
@@ -4208,26 +4211,26 @@ ${lines3.join(`
4208
4211
  `).length});return new Response(body2,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}if(path7==="/logs"){let n=Number(url2.searchParams.get("n"))||200;return new Response(bridge.logs(n),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}let pm=path7.match(/^\/plugin\/([^/]+)$/);if(pm&&req.method==="POST"){let body2=await req.json(),ok=await bridge.plugin(pm[1],body2.on!==!1);return json2({id:pm[1],on:body2.on!==!1,ok})}if(path7==="/push"&&req.method==="POST"){let body2=await req.json();if(!body2.type)return json2({error:"type required"},400);return bridge.push(body2),json2({pushed:body2.type})}if(path7==="/perf"){let d2=data();if(!d2)return json2({error:"PERF not enabled"},400);return json2(d2)}if(path7==="/tabs"){let ms2=Number(url2.searchParams.get("delay")||"500");for(let i=0;i<=TAB_MAX;i++)bridge.setTab(i),await new Promise((r)=>setTimeout(r,ms2));return bridge.setTab(CHAT_TAB),json2({cycled:TAB_MAX+1,delay:ms2})}if(path7==="/mem"){mem("control:snapshot");let m2=process.memoryUsage();return json2({rss:Math.round(m2.rss/1024/1024),heap:Math.round(m2.heapUsed/1024/1024),heapTotal:Math.round(m2.heapTotal/1024/1024),external:Math.round(m2.external/1024/1024)})}return json2({error:"not found",routes:["GET /status","GET /tab/:n","POST /send {message}","POST /key {name, ctrl?, shift?, meta?, raw?, safe?}","POST /keys {keys: [{name, ...}], delay?, safe?}","POST /type {text, delay?, safe?}","POST /input {text}","POST /plugin/:id {on}","POST /push {type, payload?}","GET /quit","GET /frame ?grep=pat&json=1","GET /logs ?n=200","GET /focus","GET /perf","GET /tabs","GET /mem"]},404)}function start(){if(!enabled2)return;Bun.serve({port:PORT,hostname:BIND,fetch:handle});let w2=warning();if(w2){process.stderr.write(`\x1B[33m[control] WARNING: ${w2.message}\x1B[0m
4209
4212
  `);return}process.stderr.write(`\x1B[90m[control] http://${BIND}:${PORT}\x1B[0m
4210
4213
  `)}var import_react136=__toESM(require_react_production(),1);function select(dialog,opts){return new Promise((res)=>{let settled=!1,done2=(v2)=>{if(settled)return;settled=!0,res(v2),dialog.clear()};dialog.replace($jsx(DialogSelect,{title:opts.title,options:opts.options,placeholder:opts.placeholder,onSelect:(o)=>done2(o)}),()=>done2(null))})}function locate3(routes,name){let lower=name.toLowerCase(),hit2=TAB_SLASH[lower];if(hit2)return hit2;let i=[...routes.keys()].findIndex((n)=>n.toLowerCase()===lower);if(i<0)return;return{tab:TABS.length+i,sub:0}}function createApi(input){return{renderer:input.renderer,theme:{get current(){return input.theme.current.theme},get name(){return input.theme.current.name},get mode(){return input.theme.current.mode},set:(name)=>input.theme.current.set(name),setMode:(mode)=>input.theme.current.setMode(mode),has:(name)=>input.theme.current.has(name)},get keys(){return input.keys.current},ui:{dialog:input.dialog,toast:(o)=>input.toast.show({variant:o.variant??"info",title:o.title,message:o.message}),confirm:(o)=>openConfirm(input.dialog,o),prompt:(o)=>openTextPrompt(input.dialog,o),alert:(title,body2)=>openAlert(input.dialog,title,body2),select:(o)=>select(input.dialog,o)},kv:{get:(key5,fallback)=>{return get2("plugin")?.[key5]??fallback},set:(key5,value)=>{let bag=get2("plugin")??{};set("plugin",{...bag,[key5]:value})}},get client(){return input.gw.current},event:{on:(fn)=>{let c=input.gw.current,h2=(ev)=>fn(ev);return c.on("event",h2),()=>c.off("event",h2)}},route:{register:(defs)=>{for(let d2 of defs)input.routes.set(d2.name,d2);return input.bump(),()=>{for(let d2 of defs)input.routes.delete(d2.name);input.bump()}},navigate:(name,sub2)=>{let at=locate3(input.routes,name);if(!at)return;input.nav.current?.(at.tab,sub2??at.sub)},get current(){return input.cur.current?.()}},command:{register:(cmds)=>input.cmd.register(cmds)},slots:{register(){throw Error("slots.register is only available inside a plugin's tui() factory")}},eikon:{rasterizer:{register:(r)=>register(r)}},lifecycle:{signal:new AbortController().signal,onDispose:()=>()=>{}}}}function createScope(id,fail2){let ctrl=new AbortController,list3=[],done2=!1,onDispose=(fn)=>{if(done2)return()=>{};let key5=Symbol();return list3.push({key:key5,fn}),()=>{list3=list3.filter((x2)=>x2.key!==key5)}},track=(fn)=>{if(!fn)return()=>{};let ran=!1,drop2=()=>{},wrapped=()=>{if(ran)return;return ran=!0,drop2(),fn()};return drop2=onDispose(wrapped),wrapped},race=(fn,left)=>new Promise((res)=>{let t2=setTimeout(()=>res("timeout"),left);Promise.resolve().then(fn).then(()=>{clearTimeout(t2),res("ok")}).catch((e)=>{clearTimeout(t2),res(e instanceof Error?e:Error(String(e)))})}),dispose=async()=>{if(done2)return;done2=!0,ctrl.abort();let queue=[...list3].reverse();list3=[];let until2=Date.now()+5000;for(let item of queue){let left=until2-Date.now();if(left<=0){fail2(`[plugin:${id}] dispose budget exhausted`);return}let out=await race(item.fn,left);if(out==="ok")continue;if(out==="timeout"){fail2(`[plugin:${id}] dispose timed out`);return}fail2(`[plugin:${id}] dispose threw`,out)}};return{lifecycle:{signal:ctrl.signal,onDispose},track,dispose}}var import_react133=__toESM(require_react_production(),1);var fmt4=(d2)=>[d2.getHours(),d2.getMinutes(),d2.getSeconds()].map((n)=>String(n).padStart(2,"0")).join(":");function Clock(props){let[now2,set2]=import_react133.useState(()=>new Date);return import_react133.useEffect(()=>{let t2=setInterval(()=>set2(new Date),1000);return()=>clearInterval(t2)},[]),$jsx("text",{fg:props.api.theme.current.textMuted,wrapMode:"none",children:fmt4(now2)})}var plugin={id:"demo.clock",enabled:!1,tui(api){api.slots.register({order:100,slots:{app_bottom:()=>$jsx(Clock,{api})}})}},clock_default=plugin;var import_react134=__toESM(require_react_production(),1);import{readdirSync as readdirSync10,statSync as statSync10}from"fs";import{join as join26,basename as basename16}from"path";import{homedir as homedir9}from"os";var PREVIEW_MAX=200000,read3=(dir2)=>{return(dir2==="/"?[]:[{name:"..",dir:!0}]).concat(readdirSync10(dir2,{withFileTypes:!0}).filter((d2)=>!d2.name.startsWith(".")).sort((a,b2)=>a.isDirectory()===b2.isDirectory()?a.name.localeCompare(b2.name):a.isDirectory()?-1:1).map((d2)=>({name:d2.name,dir:d2.isDirectory()})))},isMd=(name)=>/\.(md|markdown|mdx)$/i.test(name);function Files(props){let api=props.api,theme=api.theme.current,[dir2,setDir]=import_react134.useState(()=>homedir9()),[sel,setSel]=import_react134.useState(0),[preview2,setPreview]=import_react134.useState(""),[err,setErr]=import_react134.useState(""),rows3=import_react134.useMemo(()=>{setErr("");try{return read3(dir2)}catch(e){return setErr(String(e.message??e)),[]}},[dir2]);import_react134.useEffect(()=>{setSel((s)=>Math.min(s,Math.max(0,rows3.length-1)))},[rows3.length]);let active=rows3[sel];import_react134.useEffect(()=>{if(!active||active.dir){setPreview("");return}let path7=join26(dir2,active.name),cancel=!1;return(async()=>{let st=statSync10(path7);if(st.size>PREVIEW_MAX){if(!cancel)setPreview(`(file too large \u2014 ${st.size} bytes)`);return}let text4=await Bun.file(path7).text();if(!cancel)setPreview(text4)})().catch((e)=>{if(!cancel)setPreview(`(read error: ${e})`)}),()=>{cancel=!0}},[dir2,active?.name,active?.dir]);let enter=()=>{if(!active)return;if(active.name===".."){setDir((d2)=>d2==="/"?"/":join26(d2,"..")),setSel(0);return}if(active.dir)setDir((d2)=>join26(d2,active.name)),setSel(0)};return useKeyboard((key5)=>{if(key5.name==="left"){setDir((d2)=>d2==="/"?"/":join26(d2,"..")),setSel(0);return}handleListKey(api.keys,key5,{count:rows3.length,setSel,onActivate:enter})}),$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsx("box",{height:1,flexShrink:0,paddingX:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:dir2})}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{width:32,flexShrink:0,flexDirection:"column",border:!0,borderColor:theme.border,children:[rows3.map((e,i)=>$jsx("box",{height:1,paddingX:1,backgroundColor:i===sel?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===sel?theme.selectedListItemText:e.dir?theme.accent:theme.text,wrapMode:"none",children:(e.dir?"\u25B8 ":" ")+e.name})},e.name)),err?$jsx("box",{height:1,paddingX:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",children:err})}):null]}),$jsx("box",{flexGrow:1,flexDirection:"column",border:!0,borderColor:theme.border,children:active&&!active.dir?$jsxs($Fragment,{children:[$jsx("box",{height:1,flexShrink:0,paddingX:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[basename16(active.name),isMd(active.name)?" \xB7 markdown":""]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:preview2})})]}):$jsx("box",{paddingX:1,children:$jsx("text",{fg:theme.textMuted,children:"Select a file to preview."})})})]})]})}var plugin2={id:"demo.files",enabled:!1,tui(api){api.route.register([{name:"Files",description:"File browser",render:()=>$jsx(Files,{api})}]),api.command.register([{title:"Files: open browser",value:"plugin.files.open",category:"Plugin",onSelect:()=>api.route.navigate("Files")}])}},files_default=plugin2;var INTERNAL=[clock_default,files_default];var KV_ENABLED="enabled",Ctx7=import_react136.createContext(null);function fail2(msg,err){let tail=err instanceof Error?`: ${err.message}`:err!==void 0?`: ${String(err)}`:"";console.error(msg+tail)}function enabledMap(){let v2=get2("plugin")?.[KV_ENABLED];return v2&&typeof v2==="object"?v2:{}}function persist2(id,on){let bag=get2("plugin")??{},map={...enabledMap(),[id]:on};set("plugin",{...bag,[KV_ENABLED]:map})}function scoped(base2,reg,id,scope){let n=0;return{...base2,slots:{register(p){let sid2=n++?`${id}:${n}`:id;return scope.track(reg.register({...p,id:sid2}))}},route:{register:(defs)=>scope.track(base2.route.register(defs)),navigate:base2.route.navigate,get current(){return base2.route.current}},event:{on:(fn)=>scope.track(base2.event.on(fn))},command:{register:(cmds)=>scope.track(base2.command.register(cmds))},eikon:{rasterizer:{register:(r)=>scope.track(base2.eikon.rasterizer.register(r))}},kv:{get:(key5,fb)=>base2.kv.get(`${id}.${key5}`,fb),set:(key5,v2)=>base2.kv.set(`${id}.${key5}`,v2)},lifecycle:scope.lifecycle}}var CELLS=new WeakMap;function ctxFor(renderer,themeRef){let hit2=CELLS.get(renderer);if(hit2)return hit2.themeRef=themeRef,hit2.ctx;let cell={themeRef,ctx:{}};return Object.defineProperty(cell.ctx,"theme",{get:()=>cell.themeRef.current.theme,enumerable:!0}),CELLS.set(renderer,cell),cell.ctx}function PluginProvider(props){let list3=props.plugins??INTERNAL,renderer=useRenderer(),themeCtx=useTheme(),keys=useKeys(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),gw=useGateway(),themeRef=import_react136.useRef(themeCtx);themeRef.current=themeCtx;let keysRef=import_react136.useRef(keys);keysRef.current=keys;let gwRef=import_react136.useRef(gw);gwRef.current=gw;let navRef=import_react136.useRef(null),curRef=import_react136.useRef(null),routes=import_react136.useRef(new Map).current,[rev2,bump2]=import_react136.useReducer((x2)=>x2+1,0),reg=import_react136.useMemo(()=>createReactSlotRegistry(renderer,ctxFor(renderer,themeRef),{onPluginError:(e)=>fail2(`[plugin:${e.pluginId}] ${e.phase} error in slot "${e.slot}"`,e.error)}),[renderer]),Slot2=import_react136.useMemo(()=>createSlot(reg),[reg]),api=import_react136.useMemo(()=>createApi({renderer,theme:themeRef,keys:keysRef,dialog,toast,gw:gwRef,cmd,routes,bump:bump2,nav:navRef,cur:curRef}),[renderer,dialog,toast,cmd,routes]),entries2=import_react136.useRef(new Map),[gen,force]=import_react136.useReducer((x2)=>x2+1,0),activate=async(id,write=!0)=>{let e=entries2.current.get(id);if(!e)return!1;if(e.enabled=!0,write)persist2(id,!0);if(e.scope)return!0;let scope=createScope(id,fail2),ok=await Promise.resolve().then(()=>e.plugin.tui(scoped(api,reg,id,scope))).then(()=>!0).catch((err)=>{return fail2(`[plugin:${id}] activation failed`,err),e.error=String(err?.message??err),!1});if(!ok||!e.enabled)return await scope.dispose(),force(),ok&&!0;return e.scope=scope,e.error=void 0,force(),!0},deactivate=async(id,write=!0)=>{let e=entries2.current.get(id);if(!e)return!1;if(e.enabled=!1,write)persist2(id,!1);let scope=e.scope;if(e.scope=void 0,scope)await scope.dispose();return force(),!0},started=import_react136.useRef(!1);import_react136.useEffect(()=>{if(started.current)return;started.current=!0;let on=enabledMap();for(let p of list3)entries2.current.set(p.id,{plugin:p,enabled:on[p.id]??p.enabled??!0});return(async()=>{for(let[id,e]of entries2.current)if(e.enabled)await activate(id,!1)})(),()=>{for(let[,e]of entries2.current)e.scope?.dispose();entries2.current.clear(),routes.clear(),reg.clear()}},[]);let value=import_react136.useMemo(()=>({Slot:Slot2,routes:[...routes.values()],bind:(nav,current2)=>{navRef.current=nav,curRef.current=current2},status:()=>[...entries2.current.values()].map((e)=>({id:e.plugin.id,enabled:e.enabled,active:!!e.scope,error:e.error})),has:(slot2)=>reg.resolveEntries(slot2).length>0,activate:(id)=>activate(id),deactivate:(id)=>deactivate(id)}),[Slot2,routes,rev2,gen]);return $jsx(Ctx7.Provider,{value,children:props.children})}var usePlugins=makeUse(Ctx7,"usePlugins");function useBridge(o){let gw=useGateway(),renderer=useRenderer(),plugins=usePlugins(),state2=import_react138.useRef(o);state2.current=o,import_react138.useEffect(()=>{if(!enabled2)return;setBridge({tab:()=>state2.current.tab,setTab:o.setTab,send:(msg)=>{let s=state2.current;if(!s.ready||s.streaming)return;s.dispatch({kind:"user",text:msg}),gw.request("prompt.submit",{text:msg}).catch(()=>{}),s.setTab(CHAT_TAB)},ready:()=>state2.current.ready,streaming:()=>state2.current.streaming,messages:()=>state2.current.messages.length,session:()=>state2.current.sid,input:()=>state2.current.composer.current?.value()??"",setInput:(v2)=>state2.current.composer.current?.set(v2),focusRegion:()=>state2.current.focusRegion,setFocusRegion:o.setFocusRegion,renderer:()=>renderer,logs:(n)=>gw.tail(n),plugin:(id,on)=>on?plugins.activate(id):plugins.deactivate(id),push:(ev)=>gw.emit("event",ev)})},[gw,renderer,plugins])}var import_react146=__toESM(require_react_production(),1);var winDrive=(s,off=0)=>s.length>=off+3&&/[A-Za-z]/.test(s[off])&&s[off+1]===":"&&(s[off+2]==="\\"||s[off+2]==="/");function looksLikePath(s){let t2=s.trim();if(!t2||t2.includes(`
4211
- `))return!1;if(t2.startsWith("file://"))return!0;if(t2.startsWith("/")||t2.startsWith("~")||t2.startsWith("./")||t2.startsWith("../"))return!0;if(winDrive(t2))return!0;let q5=t2[0];if(q5==='"'||q5==="'"){let inner=t2[1];if(inner==="/"||inner==="~")return!0;if(winDrive(t2,1))return!0}return!1}var import_react140=__toESM(require_react_production(),1);var SEP=new Set(["-","_","/"," ","."]);function boundary(hay,i){if(i===0)return!0;let prev=hay[i-1];if(SEP.has(prev))return!0;if(prev===prev.toLowerCase()&&hay[i]!==hay[i].toLowerCase())return!0;return!1}function score(needle,hay){if(!needle)return 0;let n=needle.toLowerCase(),h2=hay.toLowerCase(),pts=0,from2=0,prev=-2;for(let i=0;i<n.length;i++){let at=h2.indexOf(n[i],from2);if(at<0)return 0;if(pts+=1,at===0)pts+=8;if(at===prev+1)pts+=5;if(at!==prev+1&&boundary(hay,at))pts+=4;pts-=(at-(prev<0?0:prev+1))*0.1,prev=at,from2=at+1}if(h2.startsWith(n))pts+=100;return pts-hay.length*0.01}function best(q5,cmd){return cmd.aliases.reduce((m2,a)=>Math.max(m2,score(q5,a)),score(q5,cmd.name))}function rank(list3,q5){if(!q5)return[...list3];return list3.map((cmd)=>({cmd,s:best(q5,cmd)})).filter((r)=>r.s>0).sort((a,b2)=>b2.s-a.s).map((r)=>r.cmd)}function useSlashPopover(input,cmds){let[cursor,setCursor]=import_react140.useState(0),popover=import_react140.useMemo(()=>{let subs3=matchSub(cmds,input);if(subs3)return subs3;let m2=input.match(/^\/(\S*)$/);return m2?rank(cmds,m2[1]):null},[input,cmds]),active=popover?Math.max(0,Math.min(cursor,popover.length-1)):0;import_react140.useEffect(()=>{setCursor((c)=>c===0?c:0)},[input]);let ghost=import_react140.useMemo(()=>{if(!popover||popover.length===0)return"";let best2=popover[active];if(!best2||best2.name.includes(" "))return"";let m2=input.match(/^\/(\S*)$/);if(!m2)return"";let typed=m2[1];if(typed.length<2)return"";if(!best2.name.toLowerCase().startsWith(typed.toLowerCase()))return"";return best2.name.slice(typed.length)},[input,popover,active]),open2=popover!==null&&popover.length>0;return{popover,cursor:active,setCursor,ghost,open:open2}}var import_react141=__toESM(require_react_production(),1);var exports_frecency={};__export(exports_frecency,{score:()=>score2,frecency:()=>exports_frecency,bump:()=>bump2,_reset:()=>_reset});import{join as join27}from"path";import{existsSync as existsSync27,readFileSync as readFileSync21,writeFileSync as writeFileSync10,appendFileSync,mkdirSync as mkdirSync8}from"fs";var MAX2=1000,file3=()=>join27(configDir(),"frecency.jsonl"),data2=null;function load6(){if(!existsSync27(file3()))return{};let rows3=readFileSync21(file3(),"utf-8").split(`
4214
+ `))return!1;if(t2.startsWith("file://"))return!0;if(t2.startsWith("/")||t2.startsWith("~")||t2.startsWith("./")||t2.startsWith("../"))return!0;if(winDrive(t2))return!0;let q5=t2[0];if(q5==='"'||q5==="'"){let inner=t2[1];if(inner==="/"||inner==="~")return!0;if(winDrive(t2,1))return!0}return!1}var import_react140=__toESM(require_react_production(),1);var SEP=new Set(["-","_","/"," ","."]);function boundary(hay,i){if(i===0)return!0;let prev=hay[i-1];if(SEP.has(prev))return!0;if(prev===prev.toLowerCase()&&hay[i]!==hay[i].toLowerCase())return!0;return!1}function score(needle,hay){if(!needle)return 0;let n=needle.toLowerCase(),h2=hay.toLowerCase(),pts=0,from2=0,prev=-2;for(let i=0;i<n.length;i++){let at=h2.indexOf(n[i],from2);if(at<0)return 0;if(pts+=1,at===0)pts+=8;if(at===prev+1)pts+=5;if(at!==prev+1&&boundary(hay,at))pts+=4;pts-=(at-(prev<0?0:prev+1))*0.1,prev=at,from2=at+1}if(h2.startsWith(n))pts+=100;return pts-hay.length*0.01}function best(q5,cmd){return cmd.aliases.reduce((m2,a)=>Math.max(m2,score(q5,a)),score(q5,cmd.name))}function rank(list3,q5){if(!q5)return[...list3];return list3.map((cmd)=>({cmd,s:best(q5,cmd)})).filter((r)=>r.s>0).sort((a,b2)=>b2.s-a.s).map((r)=>r.cmd)}function boundary2(ch){return ch===void 0||/\s/.test(ch)||"({\"'`".includes(ch)}function tag2(s){return s?`${s.start}:${s.end}:${s.text}`:""}function exact(spot,cmds){let m2=spot.query.match(/^(\S+)(?:\s+(\S.*))?$/);if(!m2)return!1;return cmds.some((c)=>c.name===m2[1]||c.aliases.includes(m2[1]))&&(m2[2]!==void 0||spot.query===m2[1])}function slashTokenAt(input,caret=input.length){let off=Math.max(0,Math.min(caret,input.length));if(/^\/[A-Za-z0-9_-]*$/.test(input))return{text:input,query:input.slice(1),start:0,end:input.length,whole:!0};let line4=input.lastIndexOf(`
4215
+ `,Math.max(0,off-1))+1,slash3=input.lastIndexOf("/",off);if(slash3<line4)return null;if(!boundary2(input[slash3-1]))return null;if(input[slash3-1]==="("&&input[slash3-2]==="]")return null;if(input[slash3-1]==="[")return null;let query=input.slice(slash3+1).match(/^[A-Za-z0-9_-]*/)?.[0]??"",end=slash3+1+query.length;if(input[end]==="/")return null;if(slash3===line4&&off>end&&/^\s+[^\n]*$/.test(input.slice(end,off)))return{text:input.slice(slash3,off),query:input.slice(slash3+1,off),start:slash3,end:off,whole:!0};if(off>end||off<slash3)return null;if(!query&&input[slash3+1]==="/")return null;return{text:input.slice(slash3,end),query,start:slash3,end,whole:!1}}function replaceSlashToken(input,spot,cmd){let text4=`/${cmd.name}${cmd.name.includes(" ")?" ":""}`;return input.slice(0,spot.start)+text4+input.slice(spot.end)}function useSlashPopover(input,cmds,caret=input.length){let[cursor,setCursor]=import_react140.useState(0),[dismissed,setDismissed]=import_react140.useState(null),spot=import_react140.useMemo(()=>slashTokenAt(input,caret),[input,caret]),key5=tag2(spot),popover=import_react140.useMemo(()=>{if(!spot||dismissed===key5)return null;if(spot.whole&&exact(spot,cmds))return null;let subs3=matchSub(cmds,spot.text);if(subs3)return subs3;return rank(cmds,spot.query)},[spot,cmds,dismissed,key5]),active=popover?Math.max(0,Math.min(cursor,popover.length-1)):0;import_react140.useEffect(()=>{setCursor((c)=>c===0?c:0),setDismissed((d2)=>d2&&d2!==key5?null:d2)},[key5]);let ghost=import_react140.useMemo(()=>{if(!popover||popover.length===0)return"";let hit2=popover[active];if(!hit2||hit2.name.includes(" "))return"";if(!spot||!/^\/\S*$/.test(spot.text))return"";let typed=spot.query;if(typed.length<2)return"";if(!hit2.name.toLowerCase().startsWith(typed.toLowerCase()))return"";return hit2.name.slice(typed.length)},[spot,popover,active]),open2=popover!==null&&popover.length>0;return{popover,cursor:active,setCursor,ghost,open:open2,spot,dismiss:(next2,off=next2?.length??caret)=>setDismissed(tag2(next2===void 0?spot:slashTokenAt(next2,off)))}}var import_react141=__toESM(require_react_production(),1);var exports_frecency={};__export(exports_frecency,{score:()=>score2,frecency:()=>exports_frecency,bump:()=>bump2,_reset:()=>_reset});import{join as join27}from"path";import{existsSync as existsSync27,readFileSync as readFileSync21,writeFileSync as writeFileSync10,appendFileSync,mkdirSync as mkdirSync8}from"fs";var MAX2=1000,file3=()=>join27(configDir(),"frecency.jsonl"),data2=null;function load6(){if(!existsSync27(file3()))return{};let rows3=readFileSync21(file3(),"utf-8").split(`
4212
4216
  `).filter(Boolean).map((l)=>{try{return JSON.parse(l)}catch{return null}}).filter((e)=>e!==null),latest2={};for(let e of rows3)latest2[e.path]=e;let kept=Object.values(latest2).sort((a,b2)=>b2.at-a.at).slice(0,MAX2);if(kept.length<rows3.length)mkdirSync8(configDir(),{recursive:!0}),writeFileSync10(file3(),kept.map((e)=>JSON.stringify(e)).join(`
4213
4217
  `)+`
4214
4218
  `,"utf-8");return Object.fromEntries(kept.map((e)=>[e.path,e]))}function ensure2(){return data2??=load6()}function score2(p){let e=ensure2()[p];if(!e)return 0;let days=(Date.now()-e.at)/86400000;return e.n/(1+days)}function bump2(p){let d2=ensure2(),prev=d2[p],e={path:p,n:(prev?.n??0)+1,at:Date.now()};if(d2[p]=e,mkdirSync8(configDir(),{recursive:!0}),appendFileSync(file3(),JSON.stringify(e)+`
4215
4219
  `,"utf-8"),Object.keys(d2).length>MAX2){let kept=Object.values(d2).sort((a,b2)=>b2.at-a.at).slice(0,MAX2);data2=Object.fromEntries(kept.map((x2)=>[x2.path,x2])),writeFileSync10(file3(),kept.map((x2)=>JSON.stringify(x2)).join(`
4216
4220
  `)+`
4217
- `,"utf-8")}}function _reset(){data2=null}var KEYWORDS=[{text:"@diff",display:"@diff",meta:"working-tree diff"},{text:"@staged",display:"@staged",meta:"staged changes"},{text:"@git:1",display:"@git:1",meta:"last 1 commit"},{text:"@git:3",display:"@git:3",meta:"last 3 commits"},{text:"@git:5",display:"@git:5",meta:"last 5 commits"},{text:"@url:",display:"@url:<\u2026>",meta:"fetch a URL"},{text:"@folder:",display:"@folder:<path>",meta:"recurse directory"}];function match3(word){let q5=word.toLowerCase();return KEYWORDS.filter((k2)=>k2.text.toLowerCase().startsWith(q5)&&k2.text!==word)}function atWordAt(input,cursor=input.length){if(input.startsWith("/"))return null;let i=cursor;while(i>0&&!/\s/.test(input[i-1]))i--;if(input[i]!=="@")return null;let j2=cursor;while(j2<input.length&&!/\s/.test(input[j2]))j2++;return{word:input.slice(i,j2),start:i}}function useAtRefPopover(input,cursor){let gw=useGateway(),ready=useGatewayReady(),[items,setItems]=import_react141.useState([]),[sel,setCursor]=import_react141.useState(0),seq=import_react141.useRef(0),dismissed=import_react141.useRef(null),spot=atWordAt(input,cursor);return import_react141.useEffect(()=>{if(!spot||!ready){setItems([]),setCursor(0);return}if(dismissed.current===spot.word)return;dismissed.current=null;let me2=++seq.current,fixed=match3(spot.word),t2=setTimeout(()=>{gw.request("complete.path",{word:spot.word}).then((r)=>{if(seq.current!==me2)return;let seen=new Set(fixed.map((k2)=>k2.text)),ranked=(r.items??[]).filter((i)=>!seen.has(i.text)).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems([...fixed,...ranked]),setCursor(0)}).catch(()=>{if(seq.current===me2)setItems(fixed),setCursor(0)})},120);return()=>clearTimeout(t2)},[spot?.word,ready,gw]),{open:spot!==null&&items.length>0,items,cursor:sel,setCursor,accept:(src3,idx2=sel,off)=>{let at=atWordAt(src3,off),it=items[idx2];if(!at||!it)return null;if(it.text.includes(":")&&!it.text.endsWith(":"))exports_frecency.bump(it.text);let trail2=it.text.endsWith(":")||it.text.endsWith("/")?"":" ";return src3.slice(0,at.start)+it.text+trail2+src3.slice(at.start+at.word.length)},dismiss:()=>{seq.current++,dismissed.current=spot?.word??null,setItems([])}}}var import_react142=__toESM(require_react_production(),1);var TAB_PATH_RE=/((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))[^\s]*)$/;function looksLikeSlashCommand(text4){return/^\/[^\s/]*(?:\s|$)/.test(text4)}function clear(setItems,setCursor,setReplace){setItems([]),setCursor(0),setReplace(0)}function completionRequest(input){let slash3=looksLikeSlashCommand(input),word=slash3?null:input.match(TAB_PATH_RE)?.[1]??null;if(!slash3&&!word)return null;if(slash3&&/^\/model(?:\s|$)/.test(input))return null;if(slash3)return{method:"complete.slash",params:{text:input},replaceFrom:1};return{method:"complete.path",params:{word},replaceFrom:input.length-word.length}}function acceptCompletion(input,item,replaceFrom){let replace=item.text.startsWith("/")&&input.startsWith("/")?0:replaceFrom,left=input.slice(0,replace);if(item.text.includes(":"))exports_frecency.bump(item.text);let space=item.text.endsWith("/")||/\s$/.test(item.text)?"":" ";return left+item.text+space}function useCompletion(input,blocked,gw){let[items,setItems]=import_react142.useState([]),[cursor,setCursor]=import_react142.useState(0),[replaceFrom,setReplace]=import_react142.useState(0),seq=import_react142.useRef(0),dismissed=import_react142.useRef(null);return import_react142.useEffect(()=>{if(blocked){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace);return}let req=completionRequest(input);if(!req){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace);return}if(dismissed.current===input)return;dismissed.current=null;let me2=++seq.current,t2=setTimeout(()=>{gw.request(req.method,req.params).then((r)=>{if(seq.current!==me2)return;let ranked=(r.items??[]).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems(ranked),setCursor(0),setReplace(req.method==="complete.slash"?r.replace_from??req.replaceFrom:req.replaceFrom)}).catch((e)=>{if(seq.current!==me2)return;setItems([{text:"",display:"completion unavailable",meta:e instanceof Error&&e.message?e.message:"unavailable"}]),setCursor(0),setReplace(req.replaceFrom)})},60);return()=>clearTimeout(t2)},[blocked,gw,input]),{open:items.length>0,items,cursor,setCursor,replaceFrom,dismiss:()=>{seq.current++,dismissed.current=input,clear(setItems,setCursor,setReplace)}}}var import_react143=__toESM(require_react_production(),1);import{join as join28}from"path";import{existsSync as existsSync28,mkdirSync as mkdirSync9,readFileSync as readFileSync22,appendFileSync as appendFileSync2,writeFileSync as writeFileSync11}from"fs";var MAX3=500,file4=()=>join28(configDir(),"history");function parse5(line4){if(line4[0]==="{"){let j2=safe2(line4);if(j2&&typeof j2.input==="string")return{input:j2.input,parts:Array.isArray(j2.parts)?j2.parts:[]}}return{input:line4.replace(/\0/g,`
4221
+ `,"utf-8")}}function _reset(){data2=null}var KEYWORDS=[{text:"@diff",display:"@diff",meta:"working-tree diff"},{text:"@staged",display:"@staged",meta:"staged changes"},{text:"@git:1",display:"@git:1",meta:"last 1 commit"},{text:"@git:3",display:"@git:3",meta:"last 3 commits"},{text:"@git:5",display:"@git:5",meta:"last 5 commits"},{text:"@url:",display:"@url:<\u2026>",meta:"fetch a URL"},{text:"@folder:",display:"@folder:<path>",meta:"recurse directory"}];function match3(word){let q5=word.toLowerCase();return KEYWORDS.filter((k2)=>k2.text.toLowerCase().startsWith(q5)&&k2.text!==word)}function atWordAt(input,cursor=input.length){if(input.startsWith("/"))return null;let i=cursor;while(i>0&&!/\s/.test(input[i-1]))i--;if(input[i]!=="@")return null;let j2=cursor;while(j2<input.length&&!/\s/.test(input[j2]))j2++;return{word:input.slice(i,j2),start:i}}function useAtRefPopover(input,cursor){let gw=useGateway(),ready=useGatewayReady(),[items,setItems]=import_react141.useState([]),[sel,setCursor]=import_react141.useState(0),seq=import_react141.useRef(0),dismissed=import_react141.useRef(null),spot=atWordAt(input,cursor);return import_react141.useEffect(()=>{if(!spot||!ready){setItems([]),setCursor(0);return}if(dismissed.current===spot.word)return;dismissed.current=null;let me2=++seq.current,fixed=match3(spot.word),t2=setTimeout(()=>{gw.request("complete.path",{word:spot.word}).then((r)=>{if(seq.current!==me2)return;let seen=new Set(fixed.map((k2)=>k2.text)),ranked=(r.items??[]).filter((i)=>!seen.has(i.text)).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems([...fixed,...ranked]),setCursor(0)}).catch(()=>{if(seq.current===me2)setItems(fixed),setCursor(0)})},120);return()=>clearTimeout(t2)},[spot?.word,ready,gw]),{open:spot!==null&&items.length>0,items,cursor:sel,setCursor,accept:(src3,idx2=sel,off)=>{let at=atWordAt(src3,off),it=items[idx2];if(!at||!it)return null;if(it.text.includes(":")&&!it.text.endsWith(":"))exports_frecency.bump(it.text);let trail2=it.text.endsWith(":")||it.text.endsWith("/")?"":" ";return src3.slice(0,at.start)+it.text+trail2+src3.slice(at.start+at.word.length)},dismiss:()=>{seq.current++,dismissed.current=spot?.word??null,setItems([])}}}var import_react142=__toESM(require_react_production(),1);var TAB_PATH_RE=/((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))[^\s]*)$/;function clear(setItems,setCursor,setReplace,setEnd){setItems([]),setCursor(0),setReplace(0),setEnd(0)}function completionRequest(input){if(/^\/[A-Za-z0-9_-]+$/.test(input))return null;let word=input.match(TAB_PATH_RE)?.[1]??null;if(!word)return null;return{method:"complete.path",params:{word},replaceFrom:input.length-word.length,replaceTo:input.length}}function acceptCompletion(input,item,replaceFrom,replaceTo=input.length){let replace=item.text.startsWith("/")&&input[replaceFrom-1]==="/"?replaceFrom-1:item.text.startsWith("/")&&input.startsWith("/")?0:replaceFrom,left=input.slice(0,replace),right=input.slice(replaceTo);if(item.text.includes(":"))exports_frecency.bump(item.text);let space=item.text.endsWith("/")||/\s$/.test(item.text)||/^\s/.test(right)?"":" ";return left+item.text+space+right}function useCompletion(input,blocked,gw,req){let[items,setItems]=import_react142.useState([]),[cursor,setCursor]=import_react142.useState(0),[replaceFrom,setReplace]=import_react142.useState(0),[replaceTo,setEnd]=import_react142.useState(0),seq=import_react142.useRef(0),dismissed=import_react142.useRef(null),reqKey=req?JSON.stringify(req):"";return import_react142.useEffect(()=>{if(blocked){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace,setEnd);return}let next2=req??completionRequest(input);if(!next2){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace,setEnd);return}if(dismissed.current===input)return;dismissed.current=null;let me2=++seq.current,t2=setTimeout(()=>{gw.request(next2.method,next2.params).then((r)=>{if(seq.current!==me2)return;let ranked=(r.items??[]).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems(ranked),setCursor(0),setReplace(next2.method==="complete.slash"?next2.replaceFrom+((r.replace_from??1)-1):next2.replaceFrom),setEnd(next2.replaceTo)}).catch((e)=>{if(seq.current!==me2)return;setItems([{text:"",display:"completion unavailable",meta:e instanceof Error&&e.message?e.message:"unavailable"}]),setCursor(0),setReplace(next2.replaceFrom),setEnd(next2.replaceTo)})},60);return()=>clearTimeout(t2)},[blocked,gw,input,reqKey]),{open:items.length>0,items,cursor,setCursor,replaceFrom,replaceTo,dismiss:()=>{seq.current++,dismissed.current=input,clear(setItems,setCursor,setReplace,setEnd)}}}var import_react143=__toESM(require_react_production(),1);import{join as join28}from"path";import{existsSync as existsSync28,mkdirSync as mkdirSync9,readFileSync as readFileSync22,appendFileSync as appendFileSync2,writeFileSync as writeFileSync11}from"fs";var MAX3=500,file4=()=>join28(configDir(),"history");function parse5(line4){if(line4[0]==="{"){let j2=safe2(line4);if(j2&&typeof j2.input==="string")return{input:j2.input,parts:Array.isArray(j2.parts)?j2.parts:[]}}return{input:line4.replace(/\0/g,`
4218
4222
  `),parts:[]}}function safe2(s){try{return JSON.parse(s)}catch{return null}}function load7(){let FILE=file4();if(!existsSync28(FILE))return[];return readFileSync22(FILE,"utf-8").split(`
4219
4223
  `).filter(Boolean).map(parse5).slice(-MAX3).reverse()}function enc3(e){if(e.parts.length===0)return JSON.stringify({input:e.input});return JSON.stringify({input:e.input,parts:e.parts})}function useInputHistory(input,restore){let hist=import_react143.useRef(null);if(hist.current===null)hist.current=load7();let[,bump3]=import_react143.useState(0),idx2=import_react143.useRef(-1),stash=import_react143.useRef({input:"",parts:[]}),push3=import_react143.useCallback((entry2)=>{idx2.current=-1,stash.current={input:"",parts:[]};let e=typeof entry2==="string"?{input:entry2,parts:[]}:entry2;if(!e.input&&e.parts.length===0)return;let h2=hist.current,top=h2[0];if(top&&top.input===e.input&&sameParts(top.parts,e.parts))return;h2.unshift(e);let DIR=configDir(),FILE=file4();if(!existsSync28(DIR))mkdirSync9(DIR,{recursive:!0});if(h2.length>MAX3)h2.length=MAX3,writeFileSync11(FILE,[...h2].reverse().map(enc3).join(`
4220
4224
  `)+`
4221
4225
  `,"utf-8");else appendFileSync2(FILE,enc3(e)+`
4222
- `,"utf-8");bump3((n)=>n+1)},[]),up=import_react143.useCallback(()=>{let h2=hist.current;if(h2.length===0)return;if(idx2.current===-1)stash.current={input,parts:[]};let next2=Math.min(idx2.current+1,h2.length-1);idx2.current=next2,restore(h2[next2])},[input,restore]),down=import_react143.useCallback(()=>{if(idx2.current===-1)return;let next2=idx2.current-1;idx2.current=next2,restore(next2===-1?stash.current:hist.current[next2])},[restore]);return{push:push3,up,down}}function sameParts(a,b2){if(a.length!==b2.length)return!1;for(let i=0;i<a.length;i++)if(a[i]?.type!==b2[i]?.type)return!1;return!0}var STYLE={file:"extmark.file",agent:"extmark.agent",paste:"extmark.paste"};function styles(syntax2,theme){let ensure3=(name,def2)=>{let id=syntax2.getStyleId(name);if(id!==null)return id;return syntax2.registerStyle(name,def2)};return{file:ensure3(STYLE.file,{fg:theme.accent}),agent:ensure3(STYLE.agent,{fg:theme.primary,italic:!0}),paste:ensure3(STYLE.paste,{fg:theme.textMuted})}}class PartsBuffer{ta;ex;typeId;style;list=[];map=new Map;constructor(ta,style){this.ta=ta,this.ex=ta.extmarks,this.style=style,this.typeId=this.ex.registerType("prompt-part")}text(){return this.ta.plainText}alive(){return!this.ta.isDestroyed}insertText(str4){if(!this.alive())return;this.ta.insertText(str4)}insertPart(part,virtualText){if(!this.alive())return;let start2=this.ta.visualCursor.offset,end=start2+visualLen(virtualText);this.ta.insertText(virtualText+" ");let id=this.ex.create({start:start2,end,virtual:!0,styleId:styleFor(part.type,this.style),typeId:this.typeId}),idx2=this.list.length;this.list.push(withSource(part,start2,end,virtualText)),this.map.set(id,idx2)}sync(){if(!this.alive())return;let alive=this.ex.getAllForTypeId(this.typeId),next2=[],nextMap=new Map;for(let m2 of alive){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(!p)continue;nextMap.set(m2.id,next2.length),next2.push(rangeTo(p,m2.start,m2.end))}this.list=next2,this.map=nextMap}parts(){return this.sync(),this.list}toSnapshot(){return{v:1,input:this.text(),parts:[...this.parts()]}}fromSnapshot(snap2){if(!this.alive())return;this.ta.setText(snap2.input),this.ex.clear(),this.list=[],this.map=new Map;for(let p of snap2.parts){let r=rangeOf(p);if(!r)continue;let id=this.ex.create({start:r.start,end:r.end,virtual:!0,styleId:styleFor(p.type,this.style),typeId:this.typeId});this.map.set(id,this.list.length),this.list.push(p)}this.ta.gotoBufferEnd()}clear(){if(this.list=[],this.map=new Map,!this.alive())return;this.ta.setText(""),this.ex.clear()}expand(){if(!this.alive())return{text:"",parts:[]};this.sync();let text4=this.text(),marks=this.ex.getAllForTypeId(this.typeId).sort((a,b2)=>b2.start-a.start);for(let m2 of marks){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(p?.type!=="text")continue;text4=text4.slice(0,m2.start)+p.text+text4.slice(m2.end)}return{text:text4,parts:this.list.filter((p)=>p.type!=="text")}}}function visualLen(s){let B3=globalThis.Bun;return B3?.stringWidth?B3.stringWidth(s):s.length}function styleFor(k2,s){if(k2==="file")return s.file;if(k2==="agent")return s.agent;return s.paste}function withSource(p,start2,end,value){if(p.type==="file")return{...p,source:p.source??{type:"file",path:"",text:{start:start2,end,value}}};if(p.type==="agent")return{...p,source:{start:start2,end,value}};return{...p,source:{text:{start:start2,end,value}}}}function rangeTo(p,start2,end){if(p.type==="file"){let src4=p.source??{type:"file",path:"",text:{start:start2,end,value:""}};return{...p,source:{...src4,text:{...src4.text,start:start2,end}}}}if(p.type==="agent"){let src4=p.source??{start:start2,end,value:""};return{...p,source:{...src4,start:start2,end}}}let src3=p.source??{text:{start:start2,end,value:""}};return{...p,source:{text:{...src3.text,start:start2,end}}}}function rangeOf(p){if(p.type==="file")return p.source?.text;if(p.type==="agent")return p.source;return p.source?.text}var import_react144=__toESM(require_react_production(),1);var MAX_VISIBLE=10;function badge2(source2,theme){if(source2==="skill")return theme.success;if(source2==="plugin")return theme.info;if(source2==="mcp")return theme.warning;return null}var SlashPopover=import_react144.memo(({commands:cmds,cursor,onCursor,onSelect})=>{let theme=useTheme().theme;if(cmds.length===0)return $jsx("box",{border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height:3,children:$jsx("text",{fg:theme.textMuted,children:"No matching commands"})});let rows3=import_react144.useMemo(()=>{let start3=Math.max(0,Math.min(cursor-2,cmds.length-MAX_VISIBLE)),items=cmds.slice(start3,start3+MAX_VISIBLE);return[{type:"header",cat:cmds[cursor]?.category??items[0]?.category??"Command"},...items.map((cmd,i)=>({type:"cmd",cmd,idx:start3+i}))]},[cmds,cursor]),start2=rows3.find((r)=>r.type==="cmd")?.idx??0,clipped=cmds.length>MAX_VISIBLE,above=clipped&&start2>0,below=clipped&&start2+MAX_VISIBLE<cmds.length,height=rows3.length+2+(above?1:0)+(below?1:0);return $jsxs("box",{flexDirection:"column",border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height,children:[above?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191 more"})}):null,rows3.map((row4)=>{if(row4.type==="header")return $jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:$jsx("strong",{children:row4.cat})})})},`h-${row4.cat}`);let active=row4.idx===cursor,color=badge2(row4.cmd.source,theme);return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseOver:()=>onCursor(row4.idx),onMouseDown:()=>onSelect(row4.cmd),paddingLeft:2,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:active?theme.primary:theme.text,children:["/",row4.cmd.name]}),row4.cmd.argsHint?$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.argsHint]}):null,$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.description]})]})}),$jsxs("box",{height:1,flexDirection:"row",children:[color?$jsx("text",{children:$jsxs("span",{fg:color,children:[" ",row4.cmd.source]})}):null,row4.cmd.keybind?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.keybind]})}):null]})]},`c-${row4.idx}-${row4.cmd.name}`)}),below?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2193 more"})}):null]})});var import_react145=__toESM(require_react_production(),1);var MAX_VISIBLE2=10,AtRefPopover=import_react145.memo(({items,cursor,onCursor,onSelect})=>{let theme=useTheme().theme,start2=Math.max(0,Math.min(cursor-2,items.length-MAX_VISIBLE2)),visible2=items.slice(start2,start2+MAX_VISIBLE2),above=start2>0,below=start2+MAX_VISIBLE2<items.length,height=visible2.length+2+(above?1:0)+(below?1:0);return $jsxs("box",{flexDirection:"column",border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height,children:[above?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191 more"})}):null,visible2.map((it,j2)=>{let i=start2+j2,active=i===cursor;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseOver:()=>onCursor(i),onMouseDown:()=>onSelect(i),paddingLeft:2,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:active?theme.primary:theme.text,children:it.display}),it.text!==it.display?$jsx("span",{fg:theme.textMuted,children:` ${it.text}`}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:it.meta})})]},it.text)}),below?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2193 more"})}):null]})});var MAX_ROWS=6;function fmt5(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}var Composer=import_react146.memo(import_react146.forwardRef((props,ref)=>{let theme=useTheme().theme,syntaxStyle=useTheme().syntaxStyle,gw=useGateway(),keys=useKeys(),bg2=useBackground(),ta=import_react146.useRef(null),buf=import_react146.useRef(null),sids=import_react146.useMemo(()=>styles(syntaxStyle,theme),[syntaxStyle,theme]),[input,setInput]=import_react146.useState(""),[caret,setCaret]=import_react146.useState(0),[mode,setMode]=import_react146.useState("normal"),modeRef=import_react146.useRef(mode);modeRef.current=mode;let head=import_react146.useMemo(()=>{let i=input.indexOf(`
4223
- `);return i<0?input:input.slice(0,i)},[input]),pop3=useSlashPopover(mode==="normal"?head:"",props.cmds),atSpot=mode==="normal"?atWordAt(input,caret):null,at=useAtRefPopover(mode==="normal"?input:"",caret),comp=useCompletion(mode==="normal"&&!atSpot?head:"",mode!=="normal"||pop3.open,gw),write=import_react146.useCallback((v2)=>{if(buf.current?.clear(),v2)ta.current?.setText(v2);ta.current?.gotoBufferEnd(),setInput(v2)},[]),restore=import_react146.useCallback((e)=>{if(e.parts.length===0){write(e.input);return}buf.current?.fromSnapshot({v:1,input:e.input,parts:[...e.parts]}),setInput(e.input)},[write]),hist=useInputHistory(input,restore),bindings=import_react146.useMemo(()=>[...toBindings(keys.chord("input.submit"),"submit"),...toBindings(keys.chord("input.newline"),"newline")],[keys]),live=import_react146.useRef({pop:pop3,at,comp,props,input});live.current={pop:pop3,at,comp,props,input};let wasDirty=import_react146.useRef(!1);import_react146.useEffect(()=>{let dirty2=input.trim().length>0;if(dirty2===wasDirty.current)return;wasDirty.current=dirty2,live.current.props.onDirty?.(dirty2)},[input]);let select2=(c)=>{if(c.name.includes(" ")){write(`/${c.name} `);return}write(""),live.current.props.onSlash(c)},atAccept=(idx2)=>{let off=ta.current?.cursorOffset,src3=live.current.input,which=idx2??live.current.at.cursor,it=live.current.at.items[which];if(!it)return;let a=atWordAt(src3,off),trail2=it.text.endsWith(":")||it.text.endsWith("/"),b2=buf.current;if(trail2||!b2||!ta.current||!a){let next2=live.current.at.accept(src3,idx2,off);if(next2!==null)write(next2);return}if(it.text.includes(":"))exports_frecency.bump(it.text);let eb=ta.current.editBuffer,s=eb.offsetToPosition(a.start),e=eb.offsetToPosition(a.start+a.word.length);if(!s||!e)return;ta.current.deleteRange(s.row,s.col,e.row,e.col),ta.current.cursorOffset=a.start;let part={type:"file",mime:"text/uri-list",filename:it.text,source:{type:"file",path:it.text,text:{start:a.start,end:a.start+it.text.length,value:it.text}}};b2.insertPart(part,it.text),setInput(ta.current.plainText)},paste=import_react146.useCallback((e)=>{e.preventDefault();let raw2=decodePasteBytes(e.bytes).replace(/\r\n?/g,`
4226
+ `,"utf-8");bump3((n)=>n+1)},[]),up=import_react143.useCallback(()=>{let h2=hist.current;if(h2.length===0)return;if(idx2.current===-1)stash.current={input,parts:[]};let next2=Math.min(idx2.current+1,h2.length-1);idx2.current=next2,restore(h2[next2])},[input,restore]),down=import_react143.useCallback(()=>{if(idx2.current===-1)return;let next2=idx2.current-1;idx2.current=next2,restore(next2===-1?stash.current:hist.current[next2])},[restore]);return{push:push3,up,down}}function sameParts(a,b2){if(a.length!==b2.length)return!1;for(let i=0;i<a.length;i++)if(a[i]?.type!==b2[i]?.type)return!1;return!0}var STYLE={file:"extmark.file",agent:"extmark.agent",paste:"extmark.paste"};function styles(syntax2,theme){let ensure3=(name,def2)=>{let id=syntax2.getStyleId(name);if(id!==null)return id;return syntax2.registerStyle(name,def2)};return{file:ensure3(STYLE.file,{fg:theme.accent}),agent:ensure3(STYLE.agent,{fg:theme.primary,italic:!0}),paste:ensure3(STYLE.paste,{fg:theme.textMuted})}}class PartsBuffer{ta;ex;typeId;style;list=[];map=new Map;constructor(ta,style){this.ta=ta,this.ex=ta.extmarks,this.style=style,this.typeId=this.ex.registerType("prompt-part")}text(){return this.ta.plainText}alive(){return!this.ta.isDestroyed}insertText(str4){if(!this.alive())return;this.ta.insertText(str4)}insertPart(part,virtualText){if(!this.alive())return;let start2=this.ta.visualCursor.offset,end=start2+visualLen(virtualText);this.ta.insertText(virtualText+" ");let id=this.ex.create({start:start2,end,virtual:!0,styleId:styleFor(part.type,this.style),typeId:this.typeId}),idx2=this.list.length;this.list.push(withSource(part,start2,end,virtualText)),this.map.set(id,idx2)}sync(){if(!this.alive())return;let alive=this.ex.getAllForTypeId(this.typeId),next2=[],nextMap=new Map;for(let m2 of alive){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(!p)continue;nextMap.set(m2.id,next2.length),next2.push(rangeTo(p,m2.start,m2.end))}this.list=next2,this.map=nextMap}parts(){return this.sync(),this.list}toSnapshot(){return{v:1,input:this.text(),parts:[...this.parts()]}}fromSnapshot(snap2){if(!this.alive())return;this.ta.setText(snap2.input),this.ex.clear(),this.list=[],this.map=new Map;for(let p of snap2.parts){let r=rangeOf(p);if(!r)continue;let id=this.ex.create({start:r.start,end:r.end,virtual:!0,styleId:styleFor(p.type,this.style),typeId:this.typeId});this.map.set(id,this.list.length),this.list.push(p)}this.ta.gotoBufferEnd()}clear(){if(this.list=[],this.map=new Map,!this.alive())return;this.ta.setText(""),this.ex.clear()}expand(){if(!this.alive())return{text:"",parts:[]};this.sync();let text4=this.text(),marks=this.ex.getAllForTypeId(this.typeId).sort((a,b2)=>b2.start-a.start);for(let m2 of marks){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(p?.type!=="text")continue;text4=text4.slice(0,m2.start)+p.text+text4.slice(m2.end)}return{text:text4,parts:this.list.filter((p)=>p.type!=="text")}}}function visualLen(s){let B3=globalThis.Bun;return B3?.stringWidth?B3.stringWidth(s):s.length}function styleFor(k2,s){if(k2==="file")return s.file;if(k2==="agent")return s.agent;return s.paste}function withSource(p,start2,end,value){if(p.type==="file")return{...p,source:p.source??{type:"file",path:"",text:{start:start2,end,value}}};if(p.type==="agent")return{...p,source:{start:start2,end,value}};return{...p,source:{text:{start:start2,end,value}}}}function rangeTo(p,start2,end){if(p.type==="file"){let src4=p.source??{type:"file",path:"",text:{start:start2,end,value:""}};return{...p,source:{...src4,text:{...src4.text,start:start2,end}}}}if(p.type==="agent"){let src4=p.source??{start:start2,end,value:""};return{...p,source:{...src4,start:start2,end}}}let src3=p.source??{text:{start:start2,end,value:""}};return{...p,source:{text:{...src3.text,start:start2,end}}}}function rangeOf(p){if(p.type==="file")return p.source?.text;if(p.type==="agent")return p.source;return p.source?.text}var import_react144=__toESM(require_react_production(),1);var MAX_VISIBLE=10;function badge2(source2,theme){if(source2==="skill")return theme.success;if(source2==="plugin")return theme.info;if(source2==="mcp")return theme.warning;return null}var SlashPopover=import_react144.memo(({commands:cmds,cursor,onCursor,onSelect})=>{let theme=useTheme().theme;if(cmds.length===0)return $jsx("box",{border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height:3,children:$jsx("text",{fg:theme.textMuted,children:"No matching commands"})});let rows3=import_react144.useMemo(()=>{let start3=Math.max(0,Math.min(cursor-2,cmds.length-MAX_VISIBLE)),items=cmds.slice(start3,start3+MAX_VISIBLE);return[{type:"header",cat:cmds[cursor]?.category??items[0]?.category??"Command"},...items.map((cmd,i)=>({type:"cmd",cmd,idx:start3+i}))]},[cmds,cursor]),start2=rows3.find((r)=>r.type==="cmd")?.idx??0,clipped=cmds.length>MAX_VISIBLE,above=clipped&&start2>0,below=clipped&&start2+MAX_VISIBLE<cmds.length,height=rows3.length+2+(above?1:0)+(below?1:0);return $jsxs("box",{flexDirection:"column",border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height,children:[above?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191 more"})}):null,rows3.map((row4)=>{if(row4.type==="header")return $jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:$jsx("strong",{children:row4.cat})})})},`h-${row4.cat}`);let active=row4.idx===cursor,color=badge2(row4.cmd.source,theme);return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseOver:()=>onCursor(row4.idx),onMouseDown:()=>onSelect(row4.cmd),paddingLeft:2,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:active?theme.primary:theme.text,children:["/",row4.cmd.name]}),row4.cmd.argsHint?$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.argsHint]}):null,$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.description]})]})}),$jsxs("box",{height:1,flexDirection:"row",children:[color?$jsx("text",{children:$jsxs("span",{fg:color,children:[" ",row4.cmd.source]})}):null,row4.cmd.keybind?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.keybind]})}):null]})]},`c-${row4.idx}-${row4.cmd.name}`)}),below?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2193 more"})}):null]})});var import_react145=__toESM(require_react_production(),1);var MAX_VISIBLE2=10,AtRefPopover=import_react145.memo(({items,cursor,onCursor,onSelect})=>{let theme=useTheme().theme,start2=Math.max(0,Math.min(cursor-2,items.length-MAX_VISIBLE2)),visible2=items.slice(start2,start2+MAX_VISIBLE2),above=start2>0,below=start2+MAX_VISIBLE2<items.length,height=visible2.length+2+(above?1:0)+(below?1:0);return $jsxs("box",{flexDirection:"column",border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height,children:[above?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191 more"})}):null,visible2.map((it,j2)=>{let i=start2+j2,active=i===cursor;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseOver:()=>onCursor(i),onMouseDown:()=>onSelect(i),paddingLeft:2,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:active?theme.primary:theme.text,children:it.display}),it.text!==it.display?$jsx("span",{fg:theme.textMuted,children:` ${it.text}`}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:it.meta})})]},it.text)}),below?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2193 more"})}):null]})});var MAX_ROWS=6;function fmt5(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}var Composer=import_react146.memo(import_react146.forwardRef((props,ref)=>{let theme=useTheme().theme,syntaxStyle=useTheme().syntaxStyle,gw=useGateway(),keys=useKeys(),bg2=useBackground(),ta=import_react146.useRef(null),buf=import_react146.useRef(null),sids=import_react146.useMemo(()=>styles(syntaxStyle,theme),[syntaxStyle,theme]),[input,setInput]=import_react146.useState(""),[caret,setCaret]=import_react146.useState(0),[mode,setMode]=import_react146.useState("normal"),modeRef=import_react146.useRef(mode);modeRef.current=mode;let pop3=useSlashPopover(mode==="normal"?input:"",props.cmds,caret),atSpot=mode==="normal"?atWordAt(input,caret):null,at=useAtRefPopover(mode==="normal"?input:"",caret),slashReq=pop3.spot&&!pop3.open&&pop3.spot.query?{method:"complete.slash",params:{text:pop3.spot.text},replaceFrom:pop3.spot.start+1,replaceTo:pop3.spot.end}:null,comp=useCompletion(mode==="normal"&&!atSpot?input:"",mode!=="normal"||pop3.open,gw,slashReq),write=import_react146.useCallback((v2)=>{if(buf.current?.clear(),v2)ta.current?.setText(v2);ta.current?.gotoBufferEnd(),setInput(v2)},[]),restore=import_react146.useCallback((e)=>{if(e.parts.length===0){write(e.input);return}buf.current?.fromSnapshot({v:1,input:e.input,parts:[...e.parts]}),setInput(e.input)},[write]),hist=useInputHistory(input,restore),bindings=import_react146.useMemo(()=>[...toBindings(keys.chord("input.submit"),"submit"),...toBindings(keys.chord("input.newline"),"newline")],[keys]),live=import_react146.useRef({pop:pop3,at,comp,props,input});live.current={pop:pop3,at,comp,props,input};let wasDirty=import_react146.useRef(!1);import_react146.useEffect(()=>{let dirty2=input.trim().length>0;if(dirty2===wasDirty.current)return;wasDirty.current=dirty2,live.current.props.onDirty?.(dirty2)},[input]);let select2=(c)=>{let spot=live.current.pop.spot;if(spot&&!spot.whole){write(replaceSlashToken(live.current.input,spot,c));return}if(c.name.includes(" ")){write(`/${c.name} `);return}write(""),live.current.props.onSlash(c)},fill=(c)=>{let p=live.current.pop;if(!p.spot)return;let next2=replaceSlashToken(live.current.input,p.spot,c);p.dismiss(next2),write(next2)},atAccept=(idx2)=>{let off=ta.current?.cursorOffset,src3=live.current.input,which=idx2??live.current.at.cursor,it=live.current.at.items[which];if(!it)return;let a=atWordAt(src3,off),trail2=it.text.endsWith(":")||it.text.endsWith("/"),b2=buf.current;if(trail2||!b2||!ta.current||!a){let next2=live.current.at.accept(src3,idx2,off);if(next2!==null)write(next2);return}if(it.text.includes(":"))exports_frecency.bump(it.text);let eb=ta.current.editBuffer,s=eb.offsetToPosition(a.start),e=eb.offsetToPosition(a.start+a.word.length);if(!s||!e)return;ta.current.deleteRange(s.row,s.col,e.row,e.col),ta.current.cursorOffset=a.start;let part={type:"file",mime:"text/uri-list",filename:it.text,source:{type:"file",path:it.text,text:{start:a.start,end:a.start+it.text.length,value:it.text}}};b2.insertPart(part,it.text),setInput(ta.current.plainText)},paste=import_react146.useCallback((e)=>{e.preventDefault();let raw2=decodePasteBytes(e.bytes).replace(/\r\n?/g,`
4224
4227
  `),text4=/[^\n]/.test(raw2)?raw2.replace(/\n+$/,""):raw2;if(!text4){live.current.props.onAttachClipboard?.();return}let verbatim=()=>ta.current?.insertText(text4);if(looksLikePath(text4)){gw.request("input.detect_drop",{text:text4}).then((r)=>{if(!r.matched)return verbatim();if(r.is_image){let{path:path7,count:count4,name,width,height,token_estimate}=r;if(live.current.props.onAttach?.({attached:!0,path:path7,count:count4,name,width,height,token_estimate}),!r.text.startsWith("[User attached"))ta.current?.insertText(r.text+" ");return}ta.current?.insertText(r.text+" ")}).catch(verbatim);return}if(text4.split(`
4225
- `).length<5)return verbatim();gw.request("paste.collapse",{text:text4}).then((r)=>ta.current?.insertText(r.placeholder+" ")).catch(verbatim)},[gw]),submit4=()=>{if(live.current.at.open)return atAccept();let cc=live.current.comp;if(cc.open){let it=cc.items[cc.cursor];if(!it||!it.text)return;write(acceptCompletion(live.current.input,it,cc.replaceFrom));return}let p=live.current.pop;if(p.open){let c=p.popover?.[p.cursor];if(c)select2(c);return}let exp=buf.current?.expand()??{text:live.current.input,parts:[]};if(modeRef.current==="shell"){let cmd=exp.text.trim();if(!cmd)return;hist.push({input:cmd,parts:exp.parts}),write(""),setMode("normal"),live.current.props.onShell?.(cmd);return}let text4=exp.text.trim();if(live.current.props.streaming){if(!text4||!live.current.props.canSubmitPrompt)return;if(hist.push({input:text4,parts:exp.parts}),write(""),text4.startsWith("/"))return void live.current.props.onSend(text4,exp.parts);live.current.props.onEnqueue?.(text4);return}let hasAtt=(live.current.props.attachments?.length??0)>0;if(!text4&&!hasAtt){live.current.props.onEmptyEnter?.();return}if(!live.current.props.canSubmitPrompt)return;if(text4)hist.push({input:text4,parts:exp.parts});write(""),live.current.props.onSend(text4,exp.parts)};import_react146.useImperativeHandle(ref,()=>({value:()=>live.current.input,set:write,insert:(text4)=>ta.current?.insertText(text4),remember:hist.push,lines:()=>ta.current?.lineCount??1,isEmpty:()=>live.current.input.trim().length===0,mode:()=>modeRef.current,setMode,caret:()=>ta.current?.cursorOffset??0,popOpen:()=>live.current.pop.open||live.current.at.open||live.current.comp.open,popNav:(d2)=>{let a=live.current.at;if(a.open)return a.setCursor((c)=>Math.max(0,Math.min(a.items.length-1,c+d2)));let cc=live.current.comp;if(cc.open)return cc.setCursor((c)=>Math.max(0,Math.min(cc.items.length-1,c+d2)));let max=(live.current.pop.popover?.length??1)-1;pop3.setCursor((c)=>Math.max(0,Math.min(max,c+d2)))},popAccept:()=>{if(live.current.at.open)return atAccept();let cc=live.current.comp;if(cc.open){let it=cc.items[cc.cursor];if(it?.text)write(acceptCompletion(live.current.input,it,cc.replaceFrom));return}let p=live.current.pop,c=p.popover?.[p.cursor];if(c)write(`/${c.name}${c.name.includes(" ")?" ":""}`)},popCancel:()=>{let a=live.current.at;if(a.open)return a.dismiss();let cc=live.current.comp;if(cc.open)return cc.dismiss();write("")},historyUp:()=>{let t2=ta.current;if(!t2||modeRef.current==="shell")return!1;let buf2=live.current.input;if(t2.cursorOffset>0&&buf2.lastIndexOf(`
4228
+ `).length<5)return verbatim();gw.request("paste.collapse",{text:text4}).then((r)=>ta.current?.insertText(r.placeholder+" ")).catch(verbatim)},[gw]),submit4=()=>{if(live.current.at.open)return atAccept();let cc=live.current.comp;if(cc.open){let it=cc.items[cc.cursor];if(!it||!it.text)return;write(acceptCompletion(live.current.input,it,cc.replaceFrom,cc.replaceTo));return}let p=live.current.pop;if(p.open){let c=p.popover?.[p.cursor];if(c)fill(c);return}let exp=buf.current?.expand()??{text:live.current.input,parts:[]};if(modeRef.current==="shell"){let cmd=exp.text.trim();if(!cmd)return;hist.push({input:cmd,parts:exp.parts}),write(""),setMode("normal"),live.current.props.onShell?.(cmd);return}let text4=exp.text.trim();if(live.current.props.streaming){if(!text4||!live.current.props.canSubmitPrompt)return;if(hist.push({input:text4,parts:exp.parts}),write(""),text4.startsWith("/"))return void live.current.props.onSend(text4,exp.parts);live.current.props.onEnqueue?.(text4);return}let hasAtt=(live.current.props.attachments?.length??0)>0;if(!text4&&!hasAtt){live.current.props.onEmptyEnter?.();return}if(!live.current.props.canSubmitPrompt)return;if(text4)hist.push({input:text4,parts:exp.parts});write(""),live.current.props.onSend(text4,exp.parts)};import_react146.useImperativeHandle(ref,()=>({value:()=>live.current.input,set:write,insert:(text4)=>ta.current?.insertText(text4),remember:hist.push,lines:()=>ta.current?.lineCount??1,isEmpty:()=>live.current.input.trim().length===0,mode:()=>modeRef.current,setMode,caret:()=>ta.current?.cursorOffset??0,popOpen:()=>live.current.pop.open||live.current.at.open||live.current.comp.open,popNav:(d2)=>{let a=live.current.at;if(a.open)return a.setCursor((c)=>Math.max(0,Math.min(a.items.length-1,c+d2)));let cc=live.current.comp;if(cc.open)return cc.setCursor((c)=>Math.max(0,Math.min(cc.items.length-1,c+d2)));let max=(live.current.pop.popover?.length??1)-1;pop3.setCursor((c)=>Math.max(0,Math.min(max,c+d2)))},popAccept:()=>{if(live.current.at.open)return atAccept();let cc=live.current.comp;if(cc.open){let it=cc.items[cc.cursor];if(it?.text)write(acceptCompletion(live.current.input,it,cc.replaceFrom,cc.replaceTo));return}let p=live.current.pop,c=p.popover?.[p.cursor];if(c)fill(c)},popCancel:()=>{let a=live.current.at;if(a.open)return a.dismiss();let cc=live.current.comp;if(cc.open)return cc.dismiss();let p=live.current.pop;if(p.open&&p.spot&&!p.spot.whole)return p.dismiss();write("")},historyUp:()=>{let t2=ta.current;if(!t2||modeRef.current==="shell")return!1;let buf2=live.current.input;if(t2.cursorOffset>0&&buf2.lastIndexOf(`
4226
4229
  `,t2.cursorOffset-1)>=0)return!1;if(buf2.includes(`
4227
4230
  `)&&t2.cursorOffset!==0)return t2.cursorOffset=0,!0;return hist.up(),!0},historyDown:()=>{let t2=ta.current;if(!t2||modeRef.current==="shell")return!1;let buf2=live.current.input;if(buf2.indexOf(`
4228
4231
  `,t2.cursorOffset)>=0)return!1;if(buf2.includes(`
4229
4232
  `)&&t2.cursorOffset!==buf2.length)return t2.cursorOffset=buf2.length,!0;return hist.down(),!0}}),[hist.up,hist.down,pop3.setCursor,write]);let sidsRef=import_react146.useRef(sids);sidsRef.current=sids;let taRef=import_react146.useCallback((r)=>{if(ta.current=r,r&&!buf.current)buf.current=new PartsBuffer(r,sidsRef.current);if(!r)buf.current=null},[]),label2=!props.ready?"Connecting...":props.streaming?props.status||"Generating...":"Ready",dot=props.ready?props.streaming?theme.warning:theme.success:theme.error,rows3=Math.min(MAX_ROWS,Math.max(1,input.split(`
4230
- `).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop3.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop3.popover,cursor:pop3.cursor,onCursor:pop3.setCursor,onSelect:select2})}):props.focused&&at.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:at.items,cursor:at.cursor,onCursor:at.setCursor,onSelect:atAccept})}):props.focused&&comp.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:comp.items,cursor:comp.cursor,onCursor:comp.setCursor,onSelect:(idx2)=>{let it=comp.items[idx2];if(it?.text)write(acceptCompletion(input,it,comp.replaceFrom))}})}):null,(props.queue?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,children:props.queue.map((q5,i)=>$jsx("box",{height:1,onMouseDown:()=>props.onDequeue?.(i),children:$jsxs("text",{children:[$jsxs("span",{fg:theme.borderSubtle,children:[i===0?"\u256D":"\u2502"," "]}),$jsxs("span",{fg:theme.textMuted,children:["\u23F8 ",i+1,". ",trunc5(q5,60)]})]})},i))}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,gap:1,children:props.attachments.map((a)=>a.path?$jsx(ChafaImage,{path:a.path,width:60},`p-${a.path}`):null)}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"row",flexWrap:"wrap",gap:1,paddingX:1,paddingBottom:1,children:props.attachments.map((a,i)=>$jsxs("text",{children:[$jsx("span",{bg:theme.accent,fg:theme.background,children:" img "}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[" ",a.name??`image ${i+1}`," "]}),a.width&&a.height?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[a.width,"\xD7",a.height," "]}):null,a.token_estimate?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:["~",fmt5(a.token_estimate),"t "]}):null,$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.textMuted,children:"\u232B to detach"})]},a.path??i))}):null,$jsxs("box",{border:!0,borderStyle:"single",borderColor:mode==="shell"?theme.primary:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:mode==="shell"?"$":">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:taRef,syntaxStyle,onContentChange:()=>{let t2=ta.current;setInput(t2?.plainText??""),setCaret(t2?.cursorOffset??0)},onCursorChange:()=>{if(!live.current.input.includes("@"))return;let off=ta.current?.cursorOffset??0;setCaret((c)=>c===off?c:off)},onSubmit:submit4,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder:mode==="shell"?"Run a shell command (30s cap, cwd) \u2014 esc or \u232B to exit":props.streaming?"Type to queue... (Enter queues, click chip to edit)":"Message Hermes... (/ for commands, Shift+Enter for newline)",focused:props.focused,textColor:theme.text,focusedTextColor:theme.text,placeholderColor:theme.textMuted,cursorColor:theme.text,backgroundColor:"transparent",focusedBackgroundColor:"transparent",flexGrow:1}),pop3.ghost&&props.focused&&rows3===1?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop3.ghost})}):null]}),$jsxs("box",{height:1,flexDirection:"row",paddingX:1,children:[$jsxs("text",{children:[$jsx("span",{fg:dot,children:"\u25CF "}),$jsx("span",{fg:theme.textMuted,children:mode==="shell"?"Shell":label2}),mode==="shell"?$jsx("span",{fg:theme.textMuted,children:" esc exit shell mode"}):props.streaming&&props.escHint?$jsx("span",{fg:theme.warning,children:" esc again to interrupt"}):props.streaming?$jsx("span",{fg:theme.textMuted,children:" esc\xD72 interrupt"}):null]}),$jsx("box",{flexGrow:1}),props.streaming&&(props.queue?.length??0)>0?$jsxs("text",{fg:theme.textMuted,children:[keys.print("queue.flush")," to send queued now "]}):null,bg2.count>0?$jsxs("text",{fg:theme.text,children:["\u25B6 ",bg2.count," "]}):null,props.model?$jsx("text",{fg:theme.textMuted,children:props.model}):null]})]})}));var import_react147=__toESM(require_react_production(),1);init_sessions_db();var normalize3=(sid2)=>sid2.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user2=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user2)messages.push(...transcriptToMessages([{role:"user",text:user2}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.resume",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target2);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react147.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),{id:res.session_id,info:res.info}},[gw]),activate=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.activate",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.session_key??id);let history=res.messages?.length?transcriptToMessages(res.messages):[],running2=Boolean(res.running||res.status==="working"||res.status==="waiting");return{id,info:res.info,messages:[...history,...inflightMessages(res.inflight)],running:running2,startedAt:res.started_at?res.started_at*1000:void 0,status:res.status}},[gw]),busy=import_react147.useCallback(async()=>{try{return(await gw.request("agents.list")).processes?.some((p)=>p.status==="running")??!1}catch{return!1}},[gw]),close=import_react147.useCallback(async(sid2,opts)=>{if(!sid2)return!1;if(opts?.preserveBackground&&await busy())return!1;try{return await gw.request("session.close",{session_id:sid2}),!0}catch{return!1}},[gw,busy]),boot2=import_react147.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target2=launch.sid??exports_sessions_db.lastReal()?.id;if(!target2)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target2)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target2} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row4=last3?exports_sessions_db.byId(last3):null;if(row4?.message_count===0&&row4.parent_session_id==null)try{return await resume(row4.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react147.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react147.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react147.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react147.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react147.useMemo(()=>({boot:boot2,create,resume,activate,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,activate,close,interrupt,branch2,compress,undo])}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache3.clear(),resetKanban(),exports_preferences.reload(),home2.reset()}var import_react148=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react148.useState(p.seconds);import_react148.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(exports_preferences.get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid2)=>{if(!sid2)return;io.goalState(sid2).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid2)===s.goal)return;fired.set(sid2,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react150=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react150.useState(!1),[recording,setRecording]=import_react150.useState(!1),[processing,setProcessing]=import_react150.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react150.useState(),[tts,setTts]=import_react150.useState(!1),[onTranscript,setTranscript]=import_react150.useState(null),setOnTranscript=import_react150.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react150.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react150.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react150.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react150.useCallback(async(action,sid2)=>{try{let r=await gw("voice.toggle",{action,session_id:sid2});if(r.enabled!==void 0)setEnabled(r.enabled);if(r.tts!==void 0)setTts(r.tts);if(r.record_key)setRecordKeyRaw(r.record_key);let label2=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label2}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react150.useCallback(async(sid2)=>{if(!enabled3){sys("voice: mode is off \u2014 enable with /voice on");return}let starting=!recording,action=starting?"start":"stop";if(starting)setRecording(!0);else setRecording(!1),setProcessing(!1);try{let r=await gw("voice.record",{action,session_id:sid2});if(starting&&r.status!=="recording"){if(setRecording(!1),r.status==="busy")setProcessing(!0),sys("voice: still transcribing; try again shortly")}}catch(e){if(starting)setRecording(!1);sys(`voice error: ${e instanceof Error?e.message:"gateway error"}`)}},[enabled3,recording,gw,sys]);return{state:state2,toggle,record:record2,setEnabled,setRecording,setProcessing,setRecordKey:setRecordKeyRaw,keyLabel,onTranscript,setOnTranscript}}function VoiceIndicator({voice,keyLabel}){let theme=useTheme().theme;if(!voice.enabled&&!voice.recording&&!voice.processing)return null;let text4,fg2=theme.text;if(voice.recording)text4="\u25CF recording",fg2=theme.error;else if(voice.processing)text4="\u25CC transcribing",fg2=theme.warning;else text4=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text4," "]})})}function sessionCapabilities(input){let sessionConnected=Boolean(input.sid),metadataHydrated=input.ready;return{sessionConnected,metadataHydrated,canSubmitPrompt:sessionConnected,canDispatchGatewayCommand:sessionConnected,canDrainQueue:sessionConnected&&!input.streaming}}var BUSY_RE=/session busy|waiting for model response/i,App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react152.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react152.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react152.useState(!1),[sid2,setSid]=import_react152.useState(""),sidRef=import_react152.useRef(sid2);sidRef.current=sid2;let capabilities=sessionCapabilities({sid:sid2,ready,streaming:turn.streaming}),[tab,setTab]=import_react152.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react152.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react152.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react152.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react152.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react152.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react152.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react152.useState(!1),[usage,setUsage]=import_react152.useState(void 0),[info3,setInfo]=import_react152.useState(null),[title,setTitle]=import_react152.useState(""),caption=title.trim(),titleRef=import_react152.useRef(caption);titleRef.current=caption,import_react152.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react152.useEffect(()=>{let w2=warning();if(!w2)return;toast.show({variant:"warning",title:"control server exposed",message:w2.message,duration:15000})},[toast]);let[focusRegion,setFocusRegion]=import_react152.useState("input"),goToTab=import_react152.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react152.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react152.useState(""),[escHint,setEscHint]=import_react152.useState(!1),[eikon,setEikon]=import_react152.useState(void 0),[queue,setQueue]=import_react152.useState([]),[busy,setBusy]=import_react152.useState("queue"),turnRef=import_react152.useRef(turn);turnRef.current=turn;let queueRef=import_react152.useRef(queue);queueRef.current=queue;let launchRef=import_react152.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react152.useState(launch.splash!==!1),[switching,setSwitching]=import_react152.useState(!1),summoned=import_react152.useRef(!1),[composing,setComposing]=import_react152.useState(!1),splashLast=import_react152.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react152.useMemo(()=>info3?{agentVersion:info3.version,behind:info3.update_behind,model:info3.model}:void 0,[info3?.version,info3?.update_behind,info3?.model]),splashLastProp=import_react152.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react152.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react152.useState([]),[cloudH,setCloudH]=import_react152.useState(CLOUD_MIN),[pick2,setPick]=import_react152.useState(void 0),[skin,setSkin]=import_react152.useState(()=>deriveSkin(void 0)),inflight=import_react152.useRef(!1),hold=import_react152.useRef(!1),[pulse,setPulse]=import_react152.useState(0),settle=import_react152.useCallback(()=>{if(!hold.current)return;hold.current=!1,setPulse((n)=>n+1)},[]),undone=import_react152.useRef([]),sessionStart=import_react152.useRef(Date.now()),composer2=import_react152.useRef(null),promptRef=import_react152.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react152.useRef(cmds);cmdsRef.current=cmds;let sys=import_react152.useCallback((text4)=>dispatch({kind:"system",text:text4}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react152.useEffect(()=>{voice.setOnTranscript((text4)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text4),0)})},[]);let[errorPulse,setErrorPulse]=import_react152.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react152.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react152.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react152.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react152.useRef(turn.streaming);import_react152.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react152.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react152.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react152.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react152.useRef(()=>{}),steer=import_react152.useCallback((text4)=>{let v2=text4.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),openSteer=import_react152.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react152.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt"){hold.current=!0,setQueue((q5)=>[t2,...q5]),intr.current();return}setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react152.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse,settle});intr.current=stream.doInterrupt;let reset4=import_react152.useCallback(()=>{stream.interrupted.current=!1,hold.current=!1,toast.clear("credits.depleted"),undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[toast]),newSession=import_react152.useCallback(async()=>{let prev=sidRef.current;if(reset4(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev,{preserveBackground:!0});try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset4,session,gw]),switchSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(setReady(!0),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev,{preserveBackground:!0});setSplash(!1),summoned.current=!1}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,gw]),liveStatus=(state2,running2=!1)=>{if(state2==="waiting")return"waiting for input\u2026";if(state2==="starting")return"starting agent\u2026";return running2||state2==="working"?"running\u2026":"ready"},activateSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.activate(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(sessionStart.current=res.startedAt??Date.now(),dispatch({kind:"load.live",messages:res.messages,streaming:res.running}),setStatus(liveStatus(res.status,res.running)),setReady(!0),setSplash(!1),summoned.current=!1,prev&&prev!==res.id)toast.show({variant:"info",message:"switched live session"})}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,toast,gw]),switchProfile=import_react152.useCallback((newHome,name)=>{rehome(newHome),reset4(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset4,goToTab,gwRestart,toast,gw]),loadEikon=import_react152.useCallback((path7)=>{try{setEikon(parseEikonFile(path7))}catch{setEikon(void 0)}},[]),eikonName=usePref("eikon"),eikonRev=import_react152.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react152.useEffect(()=>{let p=eikonName&&exports_eikon.baked(eikonName)||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonName,eikonRev,skin.skin?.name,loadEikon]);let turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text4),setFocusRegion("input")},[gw]),fork2=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await activateSession(res.session_id),composer2.current?.set(text4),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,activateSession]),msgMenu=import_react152.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react152.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),sendRef=import_react152.useRef(()=>{}),slash3=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,capabilities,info:info3,sid:sid2,title:caption,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,activateSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react152.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sidRef.current,titleRef.current,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve10(cmdsRef.current,name);if("hit"in r)return slash3(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text4=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text4=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text4].filter(Boolean).join(`
4233
+ `).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop3.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop3.popover,cursor:pop3.cursor,onCursor:pop3.setCursor,onSelect:select2})}):props.focused&&at.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:at.items,cursor:at.cursor,onCursor:at.setCursor,onSelect:atAccept})}):props.focused&&comp.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:comp.items,cursor:comp.cursor,onCursor:comp.setCursor,onSelect:(idx2)=>{let it=comp.items[idx2];if(it?.text)write(acceptCompletion(input,it,comp.replaceFrom,comp.replaceTo))}})}):null,(props.queue?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,children:props.queue.map((q5,i)=>$jsx("box",{height:1,onMouseDown:()=>props.onDequeue?.(i),children:$jsxs("text",{children:[$jsxs("span",{fg:theme.borderSubtle,children:[i===0?"\u256D":"\u2502"," "]}),$jsxs("span",{fg:theme.textMuted,children:["\u23F8 ",i+1,". ",trunc5(q5,60)]})]})},i))}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,gap:1,children:props.attachments.map((a)=>a.path?$jsx(ChafaImage,{path:a.path,width:60},`p-${a.path}`):null)}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"row",flexWrap:"wrap",gap:1,paddingX:1,paddingBottom:1,children:props.attachments.map((a,i)=>$jsxs("text",{children:[$jsx("span",{bg:theme.accent,fg:theme.background,children:" img "}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[" ",a.name??`image ${i+1}`," "]}),a.width&&a.height?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[a.width,"\xD7",a.height," "]}):null,a.token_estimate?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:["~",fmt5(a.token_estimate),"t "]}):null,$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.textMuted,children:"\u232B to detach"})]},a.path??i))}):null,$jsxs("box",{border:!0,borderStyle:"single",borderColor:mode==="shell"?theme.primary:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:mode==="shell"?"$":">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:taRef,syntaxStyle,onContentChange:()=>{let t2=ta.current;setInput(t2?.plainText??""),setCaret(t2?.cursorOffset??0)},onCursorChange:()=>{if(!live.current.input.includes("@")&&!live.current.input.includes("/"))return;let off=ta.current?.cursorOffset??0;setCaret((c)=>c===off?c:off)},onSubmit:submit4,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder:mode==="shell"?"Run a shell command (30s cap, cwd) \u2014 esc or \u232B to exit":props.streaming?"Type to queue... (Enter queues, click chip to edit)":"Message Hermes... (/ for commands, Shift+Enter for newline)",focused:props.focused,textColor:theme.text,focusedTextColor:theme.text,placeholderColor:theme.textMuted,cursorColor:theme.text,backgroundColor:"transparent",focusedBackgroundColor:"transparent",flexGrow:1}),pop3.ghost&&props.focused&&rows3===1&&pop3.spot?.whole?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop3.ghost})}):null]}),$jsxs("box",{height:1,flexDirection:"row",paddingX:1,children:[$jsxs("text",{children:[$jsx("span",{fg:dot,children:"\u25CF "}),$jsx("span",{fg:theme.textMuted,children:mode==="shell"?"Shell":label2}),mode==="shell"?$jsx("span",{fg:theme.textMuted,children:" esc exit shell mode"}):props.streaming&&props.escHint?$jsx("span",{fg:theme.warning,children:" esc again to interrupt"}):props.streaming?$jsx("span",{fg:theme.textMuted,children:" esc\xD72 interrupt"}):null]}),$jsx("box",{flexGrow:1}),props.streaming&&(props.queue?.length??0)>0?$jsxs("text",{fg:theme.textMuted,children:[keys.print("queue.flush")," to send queued now "]}):null,bg2.count>0?$jsxs("text",{fg:theme.text,children:["\u25B6 ",bg2.count," "]}):null,props.model?$jsx("text",{fg:theme.textMuted,children:props.model}):null]})]})}));var import_react147=__toESM(require_react_production(),1);init_sessions_db();var normalize3=(sid2)=>sid2.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user2=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user2)messages.push(...transcriptToMessages([{role:"user",text:user2}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.resume",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target2);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react147.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),{id:res.session_id,info:res.info}},[gw]),activate=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.activate",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.session_key??id);let history=res.messages?.length?transcriptToMessages(res.messages):[],running2=Boolean(res.running||res.status==="working"||res.status==="waiting");return{id,info:res.info,messages:[...history,...inflightMessages(res.inflight)],running:running2,startedAt:res.started_at?res.started_at*1000:void 0,status:res.status}},[gw]),busy=import_react147.useCallback(async()=>{try{return(await gw.request("agents.list")).processes?.some((p)=>p.status==="running")??!1}catch{return!1}},[gw]),close=import_react147.useCallback(async(sid2,opts)=>{if(!sid2)return!1;if(opts?.preserveBackground&&await busy())return!1;try{return await gw.request("session.close",{session_id:sid2}),!0}catch{return!1}},[gw,busy]),boot2=import_react147.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target2=launch.sid??exports_sessions_db.lastReal()?.id;if(!target2)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target2)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target2} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row4=last3?exports_sessions_db.byId(last3):null;if(row4?.message_count===0&&row4.parent_session_id==null)try{return await resume(row4.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react147.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react147.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react147.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react147.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react147.useMemo(()=>({boot:boot2,create,resume,activate,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,activate,close,interrupt,branch2,compress,undo])}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache3.clear(),resetKanban(),exports_preferences.reload(),home2.reset()}var import_react148=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react148.useState(p.seconds);import_react148.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(exports_preferences.get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid2)=>{if(!sid2)return;io.goalState(sid2).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid2)===s.goal)return;fired.set(sid2,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react150=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react150.useState(!1),[recording,setRecording]=import_react150.useState(!1),[processing,setProcessing]=import_react150.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react150.useState(),[tts,setTts]=import_react150.useState(!1),[onTranscript,setTranscript]=import_react150.useState(null),setOnTranscript=import_react150.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react150.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react150.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react150.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react150.useCallback(async(action,sid2)=>{try{let r=await gw("voice.toggle",{action,session_id:sid2});if(r.enabled!==void 0)setEnabled(r.enabled);if(r.tts!==void 0)setTts(r.tts);if(r.record_key)setRecordKeyRaw(r.record_key);let label2=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label2}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react150.useCallback(async(sid2)=>{if(!enabled3){sys("voice: mode is off \u2014 enable with /voice on");return}let starting=!recording,action=starting?"start":"stop";if(starting)setRecording(!0);else setRecording(!1),setProcessing(!1);try{let r=await gw("voice.record",{action,session_id:sid2});if(starting&&r.status!=="recording"){if(setRecording(!1),r.status==="busy")setProcessing(!0),sys("voice: still transcribing; try again shortly")}}catch(e){if(starting)setRecording(!1);sys(`voice error: ${e instanceof Error?e.message:"gateway error"}`)}},[enabled3,recording,gw,sys]);return{state:state2,toggle,record:record2,setEnabled,setRecording,setProcessing,setRecordKey:setRecordKeyRaw,keyLabel,onTranscript,setOnTranscript}}function VoiceIndicator({voice,keyLabel}){let theme=useTheme().theme;if(!voice.enabled&&!voice.recording&&!voice.processing)return null;let text4,fg2=theme.text;if(voice.recording)text4="\u25CF recording",fg2=theme.error;else if(voice.processing)text4="\u25CC transcribing",fg2=theme.warning;else text4=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text4," "]})})}function sessionCapabilities(input){let sessionConnected=Boolean(input.sid),metadataHydrated=input.ready;return{sessionConnected,metadataHydrated,canSubmitPrompt:sessionConnected,canDispatchGatewayCommand:sessionConnected,canDrainQueue:sessionConnected&&!input.streaming}}var BUSY_RE=/session busy|waiting for model response/i,App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react152.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react152.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react152.useState(!1),[sid2,setSid]=import_react152.useState(""),sidRef=import_react152.useRef(sid2);sidRef.current=sid2;let capabilities=sessionCapabilities({sid:sid2,ready,streaming:turn.streaming}),[tab,setTab]=import_react152.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react152.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react152.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react152.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react152.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react152.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react152.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react152.useState(!1),[usage,setUsage]=import_react152.useState(void 0),[info3,setInfo]=import_react152.useState(null),[title,setTitle]=import_react152.useState(""),caption=title.trim(),titleRef=import_react152.useRef(caption);titleRef.current=caption,import_react152.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react152.useEffect(()=>{let w2=warning();if(!w2)return;toast.show({variant:"warning",title:"control server exposed",message:w2.message,duration:15000})},[toast]);let[focusRegion,setFocusRegion]=import_react152.useState("input"),goToTab=import_react152.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react152.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react152.useState(""),[escHint,setEscHint]=import_react152.useState(!1),[eikon,setEikon]=import_react152.useState(void 0),[queue,setQueue]=import_react152.useState([]),[busy,setBusy]=import_react152.useState("queue"),turnRef=import_react152.useRef(turn);turnRef.current=turn;let queueRef=import_react152.useRef(queue);queueRef.current=queue;let launchRef=import_react152.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react152.useState(launch.splash!==!1),[switching,setSwitching]=import_react152.useState(!1),summoned=import_react152.useRef(!1),[composing,setComposing]=import_react152.useState(!1),splashLast=import_react152.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react152.useMemo(()=>info3?{agentVersion:info3.version,behind:info3.update_behind,model:info3.model}:void 0,[info3?.version,info3?.update_behind,info3?.model]),splashLastProp=import_react152.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react152.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react152.useState([]),[cloudH,setCloudH]=import_react152.useState(CLOUD_MIN),[pick2,setPick]=import_react152.useState(void 0),[skin,setSkin]=import_react152.useState(()=>deriveSkin(void 0)),inflight=import_react152.useRef(!1),hold=import_react152.useRef(!1),[pulse,setPulse]=import_react152.useState(0),settle=import_react152.useCallback(()=>{if(!hold.current)return;hold.current=!1,setPulse((n)=>n+1)},[]),undone=import_react152.useRef([]),sessionStart=import_react152.useRef(Date.now()),composer2=import_react152.useRef(null),promptRef=import_react152.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react152.useRef(cmds);cmdsRef.current=cmds;let sys=import_react152.useCallback((text4)=>dispatch({kind:"system",text:text4}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react152.useEffect(()=>{voice.setOnTranscript((text4)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text4),0)})},[]);let[errorPulse,setErrorPulse]=import_react152.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react152.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react152.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react152.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react152.useRef(turn.streaming);import_react152.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react152.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react152.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react152.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react152.useRef(()=>{}),steer=import_react152.useCallback((text4)=>{let v2=text4.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),openSteer=import_react152.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react152.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt"){hold.current=!0,setQueue((q5)=>[t2,...q5]),intr.current();return}setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react152.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse,settle});intr.current=stream.doInterrupt;let reset4=import_react152.useCallback(()=>{stream.interrupted.current=!1,hold.current=!1,toast.clear("credits.depleted"),undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[toast]),newSession=import_react152.useCallback(async()=>{let prev=sidRef.current;if(reset4(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev,{preserveBackground:!0});try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset4,session,gw]),switchSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(setReady(!0),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev,{preserveBackground:!0});setSplash(!1),summoned.current=!1}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,gw]),liveStatus=(state2,running2=!1)=>{if(state2==="waiting")return"waiting for input\u2026";if(state2==="starting")return"starting agent\u2026";return running2||state2==="working"?"running\u2026":"ready"},activateSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.activate(target2);if(reset4(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(sessionStart.current=res.startedAt??Date.now(),dispatch({kind:"load.live",messages:res.messages,streaming:res.running}),setStatus(liveStatus(res.status,res.running)),setReady(!0),setSplash(!1),summoned.current=!1,prev&&prev!==res.id)toast.show({variant:"info",message:"switched live session"})}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset4,session,goToTab,toast,gw]),switchProfile=import_react152.useCallback((newHome,name)=>{rehome(newHome),reset4(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset4,goToTab,gwRestart,toast,gw]),loadEikon=import_react152.useCallback((path7)=>{try{setEikon(parseEikonFile(path7))}catch{setEikon(void 0)}},[]),eikonName=usePref("eikon"),eikonRev=import_react152.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react152.useEffect(()=>{let p=eikonName&&exports_eikon.baked(eikonName)||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonName,eikonRev,skin.skin?.name,loadEikon]);let turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text4),setFocusRegion("input")},[gw]),fork2=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await activateSession(res.session_id),composer2.current?.set(text4),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,activateSession]),msgMenu=import_react152.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react152.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),sendRef=import_react152.useRef(()=>{}),slash3=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,capabilities,info:info3,sid:sid2,title:caption,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,activateSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react152.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sidRef.current,titleRef.current,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve10(cmdsRef.current,name);if("hit"in r)return slash3(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text4=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text4=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text4].filter(Boolean).join(`
4231
4234
  `):text4;gw.request("prompt.submit",{text:text4}).then(()=>{dispatch({kind:"user",text:withMedia}),setAttachments([]),undone.current=[],setTab(CHAT_TAB)}).catch((e)=>{let msg=e instanceof Error?e.message:String(e);if(BUSY_RE.test(msg)){inflight.current=!0,setQueue((q5)=>[text4,...q5]),setStatus("queued for next turn"),toast.show({variant:"info",message:"queued for next turn"}),setTimeout(()=>{inflight.current=!1,setPulse((n)=>n+1)},400);return}inflight.current=!1,dispatch({kind:"system",text:`submit failed: ${msg}`}),toast.show({variant:"error",message:msg})})},[gw,slash3,attachments,toast]);sendRef.current=send;let onShell=import_react152.useCallback((command)=>{setSplash(!1),dispatch({kind:"system",text:`$ ${command}`}),setStatus("running\u2026"),gw.request("shell.exec",{command}).then((r)=>{let out=(r.stdout??"").trimEnd(),err=(r.stderr??"").trimEnd(),body2=[out,err&&`stderr:
4232
4235
  ${err}`].filter(Boolean).join(`
4233
4236
  `);if(dispatch({kind:"system",text:body2||`(exit ${r.code??0})`}),(r.code??0)!==0)toast.show({variant:"warning",message:`exit ${r.code}`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`})).finally(()=>setStatus(""))},[gw,toast]),onSend=import_react152.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react152.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react152.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react152.useEffect(()=>{if(!capabilities.canDrainQueue||inflight.current||hold.current||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[capabilities.canDrainQueue,queue,send,pulse]);let dequeue=import_react152.useCallback((i)=>{let item=queueRef.current[i];if(item===void 0)return;setQueue((q5)=>q5.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[]),extra=plugins.routes,all2=import_react152.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react152.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react152.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;return next2===cur?prev:{...prev,[tab]:next2}})},[tab]);useAppKeys({tab,tabMax,chatTab:CHAT_TAB,setTab,subCount,cycleSub,focusRegion,setFocusRegion,streaming:turn.streaming,dialogOpen:dialog.open,composer:composer2,onPromptKey:(k2)=>promptRef.current?.feed(k2)??!1,onEscape:()=>{if(!splash||!summoned.current)return!1;return setSplash(!1),summoned.current=!1,!0},onInterrupt:stream.doInterrupt,queued:queue.length,onFlushQueue:()=>{hold.current=!0,stream.doInterrupt()},onQuit:()=>quit(renderer,sid2,caption,gw),onQuitArm:(label2)=>toast.show({variant:"info",message:`${label2} again to quit`}),onInterruptNotice:()=>{setEscHint(!0),setTimeout(()=>setEscHint(!1),5000)},onCopyLast:()=>{let m2=[...turnRef.current.messages].reverse().find((x2)=>x2.role==="assistant"&&text(x2));if(m2)copy2(text(m2))},onAttachClipboard:attachClipboard,onDetachLast:()=>{if(attachments.length===0)return!1;return setAttachments((a)=>a.slice(0,-1)),!0},onNotice:(text4)=>dispatch({kind:"system",text:text4}),onToggleSidebar:()=>setHideSidebar((v2)=>!v2),onSteer:openSteer,onStash:()=>{let c=composer2.current,v2=c?.value().trim()??"";if(!v2){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});c?.set(e.text);return}let n=exports_stash.push(v2);c?.set(""),toast.show({variant:"info",message:`stashed (${n})`})},voiceRecordKey:voice.state.recordKey,voiceEnabled:voice.state.enabled,onVoiceRecord:()=>voice.record(sidRef.current)}),useBridge({tab,ready,streaming:turn.streaming,messages:turn.messages,sid:sid2,focusRegion,setTab,setFocusRegion,dispatch,composer:composer2});let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react152.useCallback((id,label2,ok)=>dispatch({kind:"prompt.answered",id,label:label2,ok}),[]),promptWire=import_react152.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react152.useEffect(()=>{if(prompt&&tab!==CHAT_TAB)setTab(CHAT_TAB)},[prompt?.id]);let content=()=>{let inner=(()=>{switch(tab){case CHAT_TAB:return $jsx(Chat,{messages:turn.messages,streaming:turn.streaming,prompt:promptWire,cloud,cloudH,pick:pick2,onResize:setCloudH,onPick,onClose:closeCloud,onRewind:msgMenu});case SESSIONS_TAB:return $jsx(SessionsGroup,{focused:contentFocused,sub:subTabs[SESSIONS_TAB]??0,setSub:sessSub,onSwitch:switchSession,onActivateLive:activateSession,currentId:sid2,messages:turn.messages,sessionStart:sessionStart.current,info:info3??void 0,usage});case AUTOMATION_TAB:return $jsx(Automation,{focused:contentFocused,sub:subTabs[AUTOMATION_TAB]??0,setSub:autoSub,sessionId:sid2,onSwitchProfile:switchProfile});case CONFIG_TAB:return $jsx(ConfigGroup,{focused:contentFocused,sub:subTabs[CONFIG_TAB]??0,setSub:cfgSub});case EIKON_TAB:return $jsx(EikonGroup,{focused:contentFocused,sub:subTabs[EIKON_TAB]??0,setSub:eikSub});default:{let r=extra[tab-TABS.length];return r?r.render():null}}})(),name=all2[tab]?.name??"unknown";return $jsx(import_react152.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react152.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt,sidebarVisible=dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar;return $jsx(import_react152.Profiler,{id:"shell",onRender,children:$jsx(SkinProvider,{value:skin,children:$jsxs("box",{width:"100%",height:"100%",flexDirection:"column",backgroundColor:theme.background,onMouseUp,children:[$jsx(TabBar,{tabs:all2,activeTab:tab,onTabChange:goToTab}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsxs("box",{flexGrow:1,position:"relative",children:[content(),splash&&tab===CHAT_TAB?$jsx(Splash,{info:splashInfo,last:summoned.current?void 0:splashLastProp,composing,news,loading:switching||!info3}):null]}),$jsxs("box",{flexShrink:0,zIndex:1,children:[$jsx(VoiceIndicator,{voice:voice.state,keyLabel:voice.keyLabel}),$jsx(Composer,{ref:composer2,focused:inputFocused,canSubmitPrompt:capabilities.canSubmitPrompt,ready,streaming:turn.streaming,status,model:info3?.model,escHint,queue,attachments,cmds,onSend,onSlash:slash3,onShell,onAttach,onAttachClipboard:attachClipboard,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})]})]}),sidebarVisible?$jsx(import_react152.Profiler,{id:"sidebar",onRender,children:$jsx(Sidebar,{agentState,info:info3,usage,eikon,profile:activeProfileName(),title:caption,cloud:tab===0&&cloud,pulse:turn.streaming,onAvatar,onAvatarHold})}):null]}),plugins.has("app_bottom")?$jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx(plugins.Slot,{name:"app_bottom",mode:"single_winner",sid:sid2,tab,streaming:turn.streaming})}):null]})})})};var EIKON_CLI_USAGE=`herm eikon \u2014 install and manage Herm avatars
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herm-tui",
3
- "version": "1.9.0-dev.33",
3
+ "version": "1.9.0-dev.35",
4
4
  "description": "A modern TUI for Hermes Agent",
5
5
  "license": "MIT",
6
6
  "repository": {