herm-tui 1.8.1-dev.2 → 1.8.1-dev.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +5 -5
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -3668,7 +3668,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
3668
3668
|
`);buf=parts.pop()||"";for(let line of parts)if(line)cb(line)}if(buf.trim())cb(buf)}catch{}}class GatewayClient extends EventEmitter10{proc=null;id=0;logs=[];pending=new Map;buf=[];exit;ok=!1;timer=null;sub=!1;root(){return hermesAgentRoot()}push(ev){if(ev.type==="gateway.ready"){if(this.ok=!0,this.timer)clearTimeout(this.timer),this.timer=null}if(this.sub)return void this.emit("event",ev);this.buf.push(ev)}log(line){if(this.logs.push(line)>LOG_MAX)this.logs.splice(0,this.logs.length-LOG_MAX)}dispatch(msg){let id=msg.id,p=id?this.pending.get(id):void 0;if(p){if(this.pending.delete(id),msg.error){let err=msg.error;p.reject(Error(typeof err?.message==="string"?err.message:"request failed"))}else p.resolve(msg.result);return}if(msg.method==="event"){let ev=asEvent(msg.params);if(ev)this.push(ev)}}fail(err){for(let p of this.pending.values())p.reject(err);this.pending.clear()}start(){let root=this.root(),bin=python(root),cwd=process.env.HERMES_CWD||process.cwd(),env2={...process.env};if(!env2.TERMINAL_CWD)env2.TERMINAL_CWD=cwd;let pp=env2.PYTHONPATH?.trim();if(env2.PYTHONPATH=pp?`${root}${delimiter}${pp}`:root,this.ok=!1,this.buf=[],this.exit=void 0,this.proc)try{this.proc.kill()}catch{}if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(()=>{if(this.ok)return;this.log(`[startup] timed out (python=${bin}, cwd=${cwd})`),this.push({type:"gateway.start_timeout",payload:{cwd,python:bin}})},STARTUP_MS);let proc=Bun.spawn([bin,"-u","-m","tui_gateway.entry"],{cwd,env:env2,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(this.proc=proc,this.proc.stdout)lines(this.proc.stdout,(raw)=>{try{this.dispatch(JSON.parse(raw))}catch{let preview=raw.trim().slice(0,LOG_PREVIEW)||"(empty)";this.log(`[protocol] malformed: ${preview}`),this.push({type:"gateway.protocol_error",payload:{preview}})}});if(this.proc.stderr)lines(this.proc.stderr,(raw)=>{let line=raw.trim();if(!line)return;this.log(line),this.push({type:"gateway.stderr",payload:{line}})});proc.exited.then((code)=>{if(this.proc!==proc)return;if(this.timer)clearTimeout(this.timer),this.timer=null;if(this.fail(Error(`gateway exited${code===null?"":` (${code})`}`)),this.sub)this.emit("exit",code);else this.exit=code})}drain(){if(this.sub)return;this.sub=!0;for(let ev of this.buf.splice(0))this.emit("event",ev);if(this.exit!==void 0){let code=this.exit;this.exit=void 0,this.emit("exit",code)}}tail(n=20){return this.logs.slice(-Math.max(1,n)).join(`
|
|
3669
3669
|
`)}sid="";setSession(sid){this.sid=sid}request(method,params={}){if(!this.proc||this.proc.exitCode!==null)this.start();let stdin=this.proc?.stdin;if(!stdin||typeof stdin==="number")return Promise.reject(Error("gateway not running"));let rid=`r${++this.id}`,writer=stdin,merged=this.sid&¶ms.session_id===void 0?{session_id:this.sid,...params}:params;return new Promise((resolve4,reject)=>{let timeout=setTimeout(()=>{if(this.pending.delete(rid))reject(Error(`timeout: ${method}`))},REQUEST_MS);this.pending.set(rid,{reject:(e)=>{clearTimeout(timeout),reject(e)},resolve:(v2)=>{clearTimeout(timeout),resolve4(v2)}});try{writer.write(JSON.stringify({jsonrpc:"2.0",id:rid,method,params:merged})+`
|
|
3670
3670
|
`)}catch(e){clearTimeout(timeout),this.pending.delete(rid),reject(e instanceof Error?e:Error(String(e)))}})}kill(){this.proc?.kill()}get ready(){return this.ok}}var Gw=import_react13.createContext(null),GatewayProvider=({client,children})=>{let ref=import_react13.useRef(null);if(!ref.current)ref.current=client??new GatewayClient;let[ready,setReady]=import_react13.useState(ref.current.ready);import_react13.useEffect(()=>{let c=ref.current,onEvent=(ev)=>{if(ev.type==="gateway.ready"||ev.type==="session.info")setReady(!0)};return c.on("event",onEvent),c.start(),c.drain(),()=>{c.off("event",onEvent),c.removeAllListeners(),c.kill()}},[]);let restart=import_react13.useCallback(()=>{setReady(!1),ref.current.start()},[]),value=import_react13.useMemo(()=>({client:ref.current,ready,restart}),[ready,restart]);return $jsx(Gw.Provider,{value,children})};function useGateway(){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGateway() must be inside <GatewayProvider>");return ctx.client}function useGatewayEvent(handler){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGatewayEvent() must be inside <GatewayProvider>");let ref=import_react13.useRef(handler);ref.current=handler,import_react13.useEffect(()=>{let c=ctx.client,fn=(ev)=>ref.current(ev);return c.on("event",fn),c.drain(),()=>{c.off("event",fn)}},[ctx.client])}function useGatewayReady(){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGatewayReady() must be inside <GatewayProvider>");return ctx.ready}function useGatewayRestart(){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGatewayRestart() must be inside <GatewayProvider>");return ctx.restart}function text(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function mid(){return`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var pn=0;function pid(){return`p${++pn}`}var import_react21=__toESM(require_react_production(),1);var import_react20=__toESM(require_react_production(),1);var import_react18=__toESM(require_react_production(),1);var import_react16=__toESM(require_react_production(),1);var import_react14=__toESM(require_react_production(),1);function makeUse(ctx,name){return()=>{let v2=import_react14.useContext(ctx);if(v2===null)throw Error(`${name}() must be used inside its provider`);return v2}}function resolveTheme(theme,mode){let defs=theme.defs??{};function resolve4(c,chain=[]){if(c instanceof RGBA)return c;if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA.fromHex(c);if(chain.includes(c))throw Error(`Circular color reference: ${[...chain,c].join(" -> ")}`);let next=defs[c]??theme.theme[c];if(next===void 0)throw Error(`Color reference "${c}" not found in defs or theme`);return resolve4(next,[...chain,c])}if(typeof c==="number")return ansiToRgba(c);return resolve4(c[mode],chain)}let resolved=Object.fromEntries(Object.entries(theme.theme).filter(([key])=>key!=="selectedListItemText"&&key!=="backgroundMenu"&&key!=="thinkingOpacity").map(([key,value])=>[key,resolve4(value)])),hasList=theme.theme.selectedListItemText!==void 0;resolved.selectedListItemText=hasList?resolve4(theme.theme.selectedListItemText):resolved.background,resolved.backgroundMenu=theme.theme.backgroundMenu!==void 0?resolve4(theme.theme.backgroundMenu):resolved.backgroundElement;let base={...resolved,_hasSelectedListItemText:hasList,thinkingOpacity:theme.theme.thinkingOpacity??0.6},herm=resolveHermTokens(resolved.accent);return{...base,...herm}}function resolveHermTokens(accent){return{hermAvatar:accent}}function ansiToRgba(code){if(code<16){let colors=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff"];return RGBA.fromHex(colors[code]??"#000000")}if(code<232){let idx=code-16,val=(x2)=>x2===0?0:x2*40+55;return RGBA.fromInts(val(Math.floor(idx/36)),val(Math.floor(idx/6)%6),val(idx%6))}if(code<256){let gray=(code-232)*10+8;return RGBA.fromInts(gray,gray,gray)}return RGBA.fromInts(0,0,0)}var PREVIEW={ares:{primary:"#C7A96B",accent:"#DD4A3A",background:"#2A1212"},aura:{primary:"#a277ff",accent:"#a277ff",background:"#0f0f0f"},ayu:{primary:"#59C2FF",accent:"#E6B450",background:"#0B0E14"},carbonfox:{primary:"#33b1ff",accent:"#ff7eb6",background:"#161616"},"catppuccin-frappe":{primary:"#8da4e2",accent:"#f4b8e4",background:"#303446"},"catppuccin-macchiato":{primary:"#8aadf4",accent:"#f5bde6",background:"#24273a"},catppuccin:{primary:"#89b4fa",accent:"#f5c2e7",background:"#1e1e2e"},charizard:{primary:"#FFD39A",accent:"#F29C38",background:"#2B160E"},cobalt2:{primary:"#0088ff",accent:"#2affdf",background:"#193549"},cursor:{primary:"#88c0d0",accent:"#88c0d0",background:"#181818"},daylight:{primary:"#233662",accent:"#597FE9",background:"#101014"},default:{primary:"#FFD700",accent:"#FFBF00",background:"#1a1a2e"},dracula:{primary:"#bd93f9",accent:"#8be9fd",background:"#282a36"},everforest:{primary:"#a7c080",accent:"#d699b6",background:"#2d353b"},flexoki:{primary:"#DA702C",accent:"#8B7EC8",background:"#100F0F"},github:{primary:"#58a6ff",accent:"#39c5cf",background:"#0d1117"},gruvbox:{primary:"#83a598",accent:"#8ec07c",background:"#282828"},kanagawa:{primary:"#7E9CD8",accent:"#D27E99",background:"#1F1F28"},"lucent-orng":{primary:"#EC5B2B",accent:"#FFF7F1",background:"transparent"},material:{primary:"#82aaff",accent:"#89ddff",background:"#263238"},matrix:{primary:"#2eff6a",accent:"#c770ff",background:"#0a0e0a"},mercury:{primary:"#8da4f5",accent:"#8da4f5",background:"#171721"},mono:{primary:"#e6edf3",accent:"#aaaaaa",background:"#1F1F1F"},monokai:{primary:"#66d9ef",accent:"#a6e22e",background:"#272822"},nightowl:{primary:"#82AAFF",accent:"#c792ea",background:"#011627"},nord:{primary:"#88C0D0",accent:"#8FBCBB",background:"#2E3440"},"one-dark":{primary:"#61afef",accent:"#56b6c2",background:"#282c34"},opencode:{primary:"#fab283",accent:"#9d7cd8",background:"#0a0a0a"},orng:{primary:"#EC5B2B",accent:"#FFF7F1",background:"#0a0a0a"},"osaka-jade":{primary:"#2DD5B7",accent:"#549e6a",background:"#111c18"},palenight:{primary:"#82aaff",accent:"#89ddff",background:"#292d3e"},poseidon:{primary:"#A9DFFF",accent:"#5DB8F5",background:"#0F2440"},rosepine:{primary:"#9ccfd8",accent:"#ebbcba",background:"#191724"},sisyphus:{primary:"#F5F5F5",accent:"#E7E7E7",background:"#202020"},slate:{primary:"#7eb8f6",accent:"#8EA8FF",background:"#151C2F"},solarized:{primary:"#268bd2",accent:"#2aa198",background:"#002b36"},synthwave84:{primary:"#36f9f6",accent:"#b084eb",background:"#262335"},tokyonight:{primary:"#82aaff",accent:"#ff966c",background:"#1a1b26"},vercel:{primary:"#0070F3",accent:"#8E4EC6",background:"#000000"},vesper:{primary:"#FFC799",accent:"#FFC799",background:"#101010"},"warm-lightmode":{primary:"#9D681D",accent:"#CE661C",background:"#101014"},zenburn:{primary:"#8cd0d3",accent:"#93e0e3",background:"#3f3f3f"}},NAMES=Object.keys(PREVIEW).sort();var cache=new Map,pending=new Map;async function load(name){let hit=cache.get(name);if(hit)return hit;let inflight=pending.get(name);if(inflight)return inflight;if(!PREVIEW[name])throw Error(`Unknown theme: ${name}`);let p=import(`./themes/${name}.json`).then((m2)=>{let json=m2.default??m2;return cache.set(name,json),pending.delete(name),json});return pending.set(name,p),p}function get(name){return cache.get(name)}async function prime(name){await load(name).catch(()=>{return})}var DEFAULT_THEME="tokyonight",THEME_NAMES=NAMES;function syntax(theme){return SyntaxStyle.fromTheme(rules(theme))}function rules(theme){return[{scope:["default"],style:{foreground:theme.text}},{scope:["comment","comment.documentation"],style:{foreground:theme.syntaxComment,italic:!0}},{scope:["string","symbol"],style:{foreground:theme.syntaxString}},{scope:["number","boolean"],style:{foreground:theme.syntaxNumber}},{scope:["keyword"],style:{foreground:theme.syntaxKeyword,italic:!0}},{scope:["keyword.return","keyword.conditional","keyword.repeat"],style:{foreground:theme.syntaxKeyword,italic:!0}},{scope:["keyword.type"],style:{foreground:theme.syntaxType,bold:!0}},{scope:["keyword.function","function.method"],style:{foreground:theme.syntaxFunction}},{scope:["function","function.call"],style:{foreground:theme.syntaxFunction}},{scope:["variable","variable.parameter"],style:{foreground:theme.syntaxVariable}},{scope:["type"],style:{foreground:theme.syntaxType}},{scope:["operator"],style:{foreground:theme.syntaxOperator}},{scope:["punctuation","punctuation.bracket","punctuation.delimiter"],style:{foreground:theme.syntaxPunctuation}},{scope:["markup.heading"],style:{foreground:theme.markdownHeading,bold:!0}},{scope:["markup.strong"],style:{foreground:theme.markdownStrong,bold:!0}},{scope:["markup.italic"],style:{foreground:theme.markdownEmph,italic:!0}},{scope:["markup.link"],style:{foreground:theme.markdownLink,underline:!0}},{scope:["markup.raw"],style:{foreground:theme.markdownCode}},{scope:["markup.list"],style:{foreground:theme.markdownListItem}}]}var exports_preferences={};__export(exports_preferences,{usePref:()=>usePref,set:()=>set,reset:()=>reset,reload:()=>reload,prefs:()=>exports_preferences,load:()=>load2,get:()=>get2});var import_react15=__toESM(require_react_production(),1);import{join as join5}from"path";import{existsSync as existsSync6,mkdirSync as mkdirSync2,readFileSync,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir2}from"os";import{join as join4}from"path";import{existsSync as existsSync5,mkdirSync,readdirSync,renameSync}from"fs";var HOME=()=>process.env.HOME||homedir2(),HERMES_HOME=()=>process.env.HERMES_HOME||join4(HOME(),".hermes"),migrated=!1;function configDir(){let dir=process.env.HERM_CONFIG_DIR||join4(HERMES_HOME(),"herm");if(!migrated)migrated=!0,maybeMigrateLegacy(dir);return dir}function maybeMigrateLegacy(target){if(process.env.HERM_CONFIG_DIR)return;let legacy=join4(HOME(),".config","herm");if(!existsSync5(legacy)||legacy===target)return;try{if(existsSync5(target)&&readdirSync(target).length>0)return;mkdirSync(target,{recursive:!0});for(let name of readdirSync(legacy)){let src=join4(legacy,name),dst=join4(target,name);if(existsSync5(dst))continue;try{renameSync(src,dst)}catch{}}}catch{}}var DEFAULTS={mouse:!0,targetFps:30};function configFile(){return join5(configDir(),"tui.json")}var cached=null;function reset(){cached=null}function reload(){cached=null;for(let l of listeners)l()}function load2(){if(cached)return cached;let CONFIG_FILE=configFile();try{if(!existsSync6(CONFIG_FILE)){let prefs2={...DEFAULTS};return cached=prefs2,prefs2}let raw=JSON.parse(readFileSync(CONFIG_FILE,"utf-8"));if(raw.eikonPath&&!raw.eikon)raw.eikon=raw.eikonPath.split("/").pop()?.replace(/\.eikon$/,""),delete raw.eikonPath;let prefs={...DEFAULTS,...raw};return cached=prefs,prefs}catch{let prefs={...DEFAULTS};return cached=prefs,prefs}}function save(partial){let current=load2();if(partial)Object.assign(current,partial);cached=current;try{let CONFIG_DIR=configDir();if(!existsSync6(CONFIG_DIR))mkdirSync2(CONFIG_DIR,{recursive:!0});let json=JSON.stringify(current,null,2)+`
|
|
3671
|
-
`;writeFileSync2(configFile(),json,"utf-8")}catch(err){if(process.env.PERF)console.error("[preferences] failed to save:",err)}}function get2(key){return load2()[key]}function set(key,value){if(load2()[key]===value)return;save({[key]:value});for(let l of listeners)l()}var listeners=new Set;function subscribe(l){return listeners.add(l),()=>listeners.delete(l)}function usePref(key){return import_react15.useSyncExternalStore(subscribe,()=>load2()[key])}var Ctx=import_react16.createContext(null),THEMES_SET=new Set(THEME_NAMES),ThemeProvider=({children,initial,mode:initialMode="dark"})=>{let active=usePref("theme")??initial??DEFAULT_THEME,[mode]=import_react16.useState(initialMode),[tick,force]=import_react16.useState(0);import_react16.useEffect(()=>{if(get(active)&&get(DEFAULT_THEME))return;let cancelled=!1,need=[active,DEFAULT_THEME].filter((n)=>!get(n));return Promise.all(need.map((n)=>load(n).catch(()=>{return}))).then(()=>{if(!cancelled)force((n)=>n+1)}),()=>{cancelled=!0}},[active]);let resolved=import_react16.useMemo(()=>{let json=get(active)??get(DEFAULT_THEME);if(!json)return null;try{return resolveTheme(json,mode)}catch{let fallback=get(DEFAULT_THEME);return fallback?resolveTheme(fallback,mode):null}},[active,mode,tick]),set2=import_react16.useCallback((name)=>{if(!THEMES_SET.has(name))return!1;if(set("theme",name),!get(name))load(name).catch(()=>{});return!0},[]),has=import_react16.useCallback((name)=>THEMES_SET.has(name),[]),syntaxStyle=import_react16.useMemo(()=>resolved?syntax(resolved):null,[resolved]),value=import_react16.useMemo(()=>{if(!resolved||!syntaxStyle)return null;return{theme:resolved,syntaxStyle,name:active,mode,set:set2,names:THEME_NAMES,has}},[resolved,syntaxStyle,active,mode,set2,has]);if(!value)return null;return $jsx(Ctx.Provider,{value,children})},useTheme=makeUse(Ctx,"useTheme");var import_react17=__toESM(require_react_production(),1);var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],MS=80,subs=new Set,tick=0,timer=null;function sub(fn){if(subs.add(fn),fn(tick),!timer)timer=setInterval(()=>{tick=(tick+1)%FRAMES.length;for(let s of Array.from(subs))s(tick)},MS);return()=>{if(subs.delete(fn),subs.size===0&&timer)clearInterval(timer),timer=null}}function useGlyph(active){let ref=import_react17.useRef(null);return import_react17.useEffect(()=>{if(!active)return;return sub((n)=>{let node=ref.current;if(node)node.children=[FRAMES[n]]})},[active]),ref}var Spinner=import_react17.memo((props)=>{let theme=useTheme().theme,color=props.color??theme.textMuted,on=exports_preferences.get("animations")!==!1,ref=useGlyph(on);return $jsxs("text",{children:[$jsx("span",{ref,fg:color,children:on?FRAMES[tick]:"\u22EF"}),props.label?$jsxs("span",{fg:color,children:[" ",props.label]}):null]})}),SpinGlyph=import_react17.memo((props)=>{let on=(props.active??!0)&&exports_preferences.get("animations")!==!1,ref=useGlyph(on);return $jsx("span",{ref,fg:props.fg,children:on?FRAMES[tick]:"\u22EF"})});function useSpinnerGlyph(active=!0){let on=exports_preferences.get("animations")!==!1&&active,[n,set2]=import_react17.useState(tick);return import_react17.useEffect(()=>on?sub(set2):void 0,[on]),on?FRAMES[n]:"\u22EF"}var SPEC={terminal:{icon:"$",verb:"",pending:"Writing command\u2026"},process:{icon:"\u229A",verb:"Process",pending:"Managing process\u2026"},execute_code:{icon:"\xBB",verb:"Exec",pending:"Writing script\u2026"},read_file:{icon:"\u2192",verb:"Read",pending:"Reading file\u2026"},write_file:{icon:"\u2190",verb:"Write",pending:"Preparing write\u2026"},patch:{icon:"\u2190",verb:"Edit",pending:"Preparing edit\u2026"},search_files:{icon:"\u2731",verb:"Search",pending:"Searching\u2026"},web_search:{icon:"\u25C8",verb:"Web",pending:"Searching web\u2026"},web_extract:{icon:"%",verb:"Fetch",pending:"Fetching page\u2026"},session_search:{icon:"\u21BA",verb:"Recall",pending:"Searching memory\u2026"},browser_navigate:{icon:"%",verb:"Navigate",pending:"Navigating\u2026"},browser_click:{icon:"\xB7",verb:"Click",pending:"Clicking\u2026"},browser_type:{icon:"\u2328",verb:"Type",pending:"Typing\u2026"},browser_snapshot:{icon:"\u2399",verb:"Snapshot",pending:"Capturing\u2026"},browser_vision:{icon:"\u25C9",verb:"Vision",pending:"Looking\u2026"},vision_analyze:{icon:"\u25C9",verb:"Vision",pending:"Analyzing image\u2026"},todo:{icon:"\u2630",verb:"Todo",pending:"Updating todos\u2026"},memory:{icon:"\u2691",verb:"Memory",pending:"Updating memory\u2026"},clarify:{icon:"?",verb:"Ask",pending:"Asking\u2026"},skill_view:{icon:"\u25C6",verb:"Skill",pending:"Loading skill\u2026"},skills_list:{icon:"\u25C6",verb:"Skills",pending:"Listing skills\u2026"},skill_manage:{icon:"\u25C6",verb:"Skill",pending:"Managing skill\u2026"},delegate_task:{icon:"\u2299",verb:"Delegate",pending:"Spawning agent\u2026"},cronjob:{icon:"\u25F7",verb:"Cron",pending:"Managing cron\u2026"},text_to_speech:{icon:"\u266A",verb:"TTS",pending:"Synthesizing\u2026"},image_generate:{icon:"\u2726",verb:"Image",pending:"Generating image\u2026"},video_generate:{icon:"\u2726",verb:"Video",pending:"Generating video\u2026"}},GENERIC={icon:"\u2699",verb:"",pending:"Running\u2026"};function spec(name){if(name.startsWith("subagent"))return{icon:"\u2299",verb:"Subagent",pending:"Running\u2026"};if(name.startsWith("mcp__")||name.startsWith("mcp:"))return{icon:"\u25C7",verb:"MCP",pending:"Calling\u2026"};return SPEC[name]??GENERIC}function ms(d2){if(d2==null)return"";if(d2<1000)return`${Math.round(d2)}ms`;if(d2<60000)return`${(d2/1000).toFixed(1)}s`;return`${Math.floor(d2/60000)}m${Math.round(d2%60000/1000)}s`}var InlineTool=import_react18.memo((p)=>{let theme=useTheme().theme,[hover,setHover]=import_react18.useState(!1),s=spec(p.part.name),running=p.part.status==="running",failed=p.part.status==="error",spin=useSpinnerGlyph(running),fg2=failed?theme.error:hover&&p.onClick?theme.text:running?theme.text:theme.textMuted;return $jsxs("box",{flexDirection:"column",paddingLeft:3,onMouseOver:p.onClick?()=>setHover(!0):void 0,onMouseOut:p.onClick?()=>setHover(!1):void 0,onMouseDown:p.onClick,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:running?theme.warning:p.iconColor??fg2,children:[running?spin:s.icon," "]}),p.complete??!0?$jsx("span",{fg:fg2,children:p.children}):$jsxs("span",{fg:fg2,children:["~ ",s.pending]}),p.part.duration!=null?$jsxs("span",{fg:theme.textMuted,children:[" ",ms(p.part.duration)]}):null]})}),failed&&p.part.result?$jsx("box",{minHeight:1,paddingLeft:2,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:p.part.result})}):null,p.details?.map((d2)=>$jsxs("box",{flexDirection:"column",paddingLeft:2,marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:d2.label})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:d2.text})})]},d2.label))]})});var import_react19=__toESM(require_react_production(),1);function dur(d2){if(d2==null)return"";let s=d2/1000;return s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m${Math.round(s%60)}s`}var Subagent=import_react19.memo(({tool})=>{let theme=useTheme().theme,[open,setOpen]=import_react19.useState(!1),running=tool.status==="running",failed=tool.status==="error",spin=useSpinnerGlyph(running),trail=tool.trail??[],last=trail[trail.length-1],fg2=failed?theme.error:running?theme.text:theme.textMuted,goal=(tool.goal??tool.preview??"").replace(/\s+/g," ").trim(),sub2=running?last?`\u21B3 ${spec(last.name).verb||last.name} ${last.preview??""}`:trail.length?`\u21B3 ${trail.length} toolcalls`:"":`\u2514 ${trail.length} toolcall${trail.length===1?"":"s"}${tool.duration?` \xB7 ${dur(tool.duration)}`:""}`;return $jsxs("box",{flexDirection:"column",paddingLeft:3+(tool.depth??0)*2,onMouseDown:trail.length?()=>setOpen((o)=>!o):void 0,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:running?theme.warning:fg2,children:[running?spin:"\u2299"," "]}),$jsxs("span",{fg:fg2,children:["Task \u2014 ",goal||"delegating\u2026"]})]})}),open?$jsxs("box",{flexDirection:"column",children:[trail.map((c,i)=>{let s=spec(c.name),lbl=s.verb?`${s.verb} ${c.preview??""}`:c.preview??c.name;return $jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:i<trail.length-1?"\u251C\u2500 ":"\u2514\u2500 "}),$jsxs("span",{fg:theme.textMuted,children:[s.icon," ",lbl]})]})},i)}),tool.result?$jsx("box",{minHeight:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tool.result})}):null]}):sub2?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:sub2})}):null]})});function short(s,n=120){if(!s)return"";let one=s.replace(/\s+/g," ").trim();return one.length>n?one.slice(0,n-1)+"\u2026":one}var Inline=import_react20.memo(({tool})=>{let s=spec(tool.name),body=tool.preview?short(tool.preview):"";return $jsx(InlineTool,{part:tool,complete:!!body||tool.status!=="running",children:s.verb?`${s.verb} ${body}`:body||tool.name})}),Tool=import_react20.memo(({tool,detail="expanded"})=>{if(detail==="hidden"&&tool.status!=="running")return null;if(tool.trail||tool.name==="delegate_task")return $jsx(Subagent,{tool});if(detail!=="expanded")return $jsx(Inline,{tool});let details=[tool.verboseArgs?{label:"Args",text:tool.verboseArgs}:void 0,tool.verboseResult?{label:tool.status==="error"?"Error":"Result",text:tool.verboseResult}:void 0].filter((d2)=>!!d2),s=spec(tool.name),body=tool.preview?short(tool.preview):"";return $jsx(InlineTool,{part:tool,complete:!!body||tool.status!=="running",details,children:s.verb?`${s.verb} ${body}`:body||tool.name})});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_react21.memo((props)=>{let theme=useTheme().theme,refs=import_react21.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_react21.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){return list.reduce((n,p)=>n+(p.type==="thinking"?Math.ceil(p.content.length/80)||1:p.type==="tool"&&p.diff?6:1),0)}var ThoughtCloud=import_react21.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"),tools=all.filter((p)=>p.type==="tool"),[pane,setPane]=import_react21.useState("reasoning");import_react21.useEffect(()=>{if(pane==="reasoning"&&think.length===0&&tools.length>0)setPane("tools");if(pane==="tools"&&tools.length===0&&think.length>0)setPane("reasoning")},[pane,think.length,tools.length]);let body=pane==="reasoning"?think:tools,manual=import_react21.useRef(!1),want=Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,rows(body)+3)),resize=props.onResize;import_react21.useEffect(()=>{if(!manual.current)resize(want)},[want,resize]);let drag=import_react21.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",tools.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,{tool:p,detail:detail==="hidden"?"hidden":"collapsed"})},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_react27=__toESM(require_react_production(),1);var import_react22=__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"),"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>s","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","Walk lineage back (continues from)","sessions"),"sessions.next":def("right","Walk lineage forward (compressed to)","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"]);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,lead){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]??cap(c.name),body=[...mods,name].join("+");if(!c.leader)return body;return lead?`${lead} ${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 cap(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_react22.createContext(null),NO_OVERRIDES=Object.freeze({}),KeysProvider=({children,overrides:fixedOverrides})=>{let renderer=useRenderer(),prefOverrides=usePref("keys"),overrides=fixedOverrides??prefOverrides??NO_OVERRIDES,table=import_react22.useMemo(()=>{let t2=new Map;for(let id of Object.keys(DEFAULTS2))t2.set(id,parse2(overrides[id]??DEFAULTS2[id].chord));return t2},[overrides]),lead=table.get("leader"),leadLabel=print(lead),armed=import_react22.useRef(!1),stolen=import_react22.useRef(null),timer2=import_react22.useRef(null),[,bump]=import_react22.useState(0),disarm=import_react22.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_react22.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(lead,key2)){arm(),key2.stopPropagation();return}if(armed.current)queueMicrotask(disarm)});let value=import_react22.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_react24=__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){let ref=import_react24.useRef(null),id=(i)=>`${prefix}-row-${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_react26=__toESM(require_react_production(),1);var TabStrip=import_react26.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_react27.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_react31=__toESM(require_react_production(),1);var import_react28=__toESM(require_react_production(),1);var default_default=`{"eikon":1,"name":"nous-girl","width":48,"height":24,"author":"kaio","created":"2026-05-04T02:32:53.930Z"}
|
|
3671
|
+
`;writeFileSync2(configFile(),json,"utf-8")}catch(err){if(process.env.PERF)console.error("[preferences] failed to save:",err)}}function get2(key){return load2()[key]}function set(key,value){if(load2()[key]===value)return;save({[key]:value});for(let l of listeners)l()}var listeners=new Set;function subscribe(l){return listeners.add(l),()=>listeners.delete(l)}function usePref(key){return import_react15.useSyncExternalStore(subscribe,()=>load2()[key])}var Ctx=import_react16.createContext(null),THEMES_SET=new Set(THEME_NAMES),ThemeProvider=({children,initial,mode:initialMode="dark"})=>{let active=usePref("theme")??initial??DEFAULT_THEME,[mode]=import_react16.useState(initialMode),[tick,force]=import_react16.useState(0);import_react16.useEffect(()=>{if(get(active)&&get(DEFAULT_THEME))return;let cancelled=!1,need=[active,DEFAULT_THEME].filter((n)=>!get(n));return Promise.all(need.map((n)=>load(n).catch(()=>{return}))).then(()=>{if(!cancelled)force((n)=>n+1)}),()=>{cancelled=!0}},[active]);let resolved=import_react16.useMemo(()=>{let json=get(active)??get(DEFAULT_THEME);if(!json)return null;try{return resolveTheme(json,mode)}catch{let fallback=get(DEFAULT_THEME);return fallback?resolveTheme(fallback,mode):null}},[active,mode,tick]),set2=import_react16.useCallback((name)=>{if(!THEMES_SET.has(name))return!1;if(set("theme",name),!get(name))load(name).catch(()=>{});return!0},[]),has=import_react16.useCallback((name)=>THEMES_SET.has(name),[]),syntaxStyle=import_react16.useMemo(()=>resolved?syntax(resolved):null,[resolved]),value=import_react16.useMemo(()=>{if(!resolved||!syntaxStyle)return null;return{theme:resolved,syntaxStyle,name:active,mode,set:set2,names:THEME_NAMES,has}},[resolved,syntaxStyle,active,mode,set2,has]);if(!value)return null;return $jsx(Ctx.Provider,{value,children})},useTheme=makeUse(Ctx,"useTheme");var import_react17=__toESM(require_react_production(),1);var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],MS=80,subs=new Set,tick=0,timer=null;function sub(fn){if(subs.add(fn),fn(tick),!timer)timer=setInterval(()=>{tick=(tick+1)%FRAMES.length;for(let s of Array.from(subs))s(tick)},MS);return()=>{if(subs.delete(fn),subs.size===0&&timer)clearInterval(timer),timer=null}}function useGlyph(active){let ref=import_react17.useRef(null);return import_react17.useEffect(()=>{if(!active)return;return sub((n)=>{let node=ref.current;if(node)node.children=[FRAMES[n]]})},[active]),ref}var Spinner=import_react17.memo((props)=>{let theme=useTheme().theme,color=props.color??theme.textMuted,on=exports_preferences.get("animations")!==!1,ref=useGlyph(on);return $jsxs("text",{children:[$jsx("span",{ref,fg:color,children:on?FRAMES[tick]:"\u22EF"}),props.label?$jsxs("span",{fg:color,children:[" ",props.label]}):null]})}),SpinGlyph=import_react17.memo((props)=>{let on=(props.active??!0)&&exports_preferences.get("animations")!==!1,ref=useGlyph(on);return $jsx("span",{ref,fg:props.fg,children:on?FRAMES[tick]:"\u22EF"})});function useSpinnerGlyph(active=!0){let on=exports_preferences.get("animations")!==!1&&active,[n,set2]=import_react17.useState(tick);return import_react17.useEffect(()=>on?sub(set2):void 0,[on]),on?FRAMES[n]:"\u22EF"}var SPEC={terminal:{icon:"$",verb:"",pending:"Writing command\u2026"},process:{icon:"\u229A",verb:"Process",pending:"Managing process\u2026"},execute_code:{icon:"\xBB",verb:"Exec",pending:"Writing script\u2026"},read_file:{icon:"\u2192",verb:"Read",pending:"Reading file\u2026"},write_file:{icon:"\u2190",verb:"Write",pending:"Preparing write\u2026"},patch:{icon:"\u2190",verb:"Edit",pending:"Preparing edit\u2026"},search_files:{icon:"\u2731",verb:"Search",pending:"Searching\u2026"},web_search:{icon:"\u25C8",verb:"Web",pending:"Searching web\u2026"},web_extract:{icon:"%",verb:"Fetch",pending:"Fetching page\u2026"},session_search:{icon:"\u21BA",verb:"Recall",pending:"Searching memory\u2026"},browser_navigate:{icon:"%",verb:"Navigate",pending:"Navigating\u2026"},browser_click:{icon:"\xB7",verb:"Click",pending:"Clicking\u2026"},browser_type:{icon:"\u2328",verb:"Type",pending:"Typing\u2026"},browser_snapshot:{icon:"\u2399",verb:"Snapshot",pending:"Capturing\u2026"},browser_vision:{icon:"\u25C9",verb:"Vision",pending:"Looking\u2026"},vision_analyze:{icon:"\u25C9",verb:"Vision",pending:"Analyzing image\u2026"},todo:{icon:"\u2630",verb:"Todo",pending:"Updating todos\u2026"},memory:{icon:"\u2691",verb:"Memory",pending:"Updating memory\u2026"},clarify:{icon:"?",verb:"Ask",pending:"Asking\u2026"},skill_view:{icon:"\u25C6",verb:"Skill",pending:"Loading skill\u2026"},skills_list:{icon:"\u25C6",verb:"Skills",pending:"Listing skills\u2026"},skill_manage:{icon:"\u25C6",verb:"Skill",pending:"Managing skill\u2026"},delegate_task:{icon:"\u2299",verb:"Delegate",pending:"Spawning agent\u2026"},cronjob:{icon:"\u25F7",verb:"Cron",pending:"Managing cron\u2026"},text_to_speech:{icon:"\u266A",verb:"TTS",pending:"Synthesizing\u2026"},image_generate:{icon:"\u2726",verb:"Image",pending:"Generating image\u2026"},video_generate:{icon:"\u2726",verb:"Video",pending:"Generating video\u2026"}},GENERIC={icon:"\u2699",verb:"",pending:"Running\u2026"};function spec(name){if(name.startsWith("subagent"))return{icon:"\u2299",verb:"Subagent",pending:"Running\u2026"};if(name.startsWith("mcp__")||name.startsWith("mcp:"))return{icon:"\u25C7",verb:"MCP",pending:"Calling\u2026"};return SPEC[name]??GENERIC}function ms(d2){if(d2==null)return"";if(d2<1000)return`${Math.round(d2)}ms`;if(d2<60000)return`${(d2/1000).toFixed(1)}s`;return`${Math.floor(d2/60000)}m${Math.round(d2%60000/1000)}s`}var InlineTool=import_react18.memo((p)=>{let theme=useTheme().theme,[hover,setHover]=import_react18.useState(!1),s=spec(p.part.name),running=p.part.status==="running",failed=p.part.status==="error",spin=useSpinnerGlyph(running),fg2=failed?theme.error:hover&&p.onClick?theme.text:running?theme.text:theme.textMuted;return $jsxs("box",{flexDirection:"column",paddingLeft:3,onMouseOver:p.onClick?()=>setHover(!0):void 0,onMouseOut:p.onClick?()=>setHover(!1):void 0,onMouseDown:p.onClick,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:running?theme.warning:p.iconColor??fg2,children:[running?spin:s.icon," "]}),p.complete??!0?$jsx("span",{fg:fg2,children:p.children}):$jsxs("span",{fg:fg2,children:["~ ",s.pending]}),p.part.duration!=null?$jsxs("span",{fg:theme.textMuted,children:[" ",ms(p.part.duration)]}):null]})}),failed&&p.part.result?$jsx("box",{minHeight:1,paddingLeft:2,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:p.part.result})}):null,p.details?.map((d2)=>$jsxs("box",{flexDirection:"column",paddingLeft:2,marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:d2.label})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:d2.text})})]},d2.label))]})});var import_react19=__toESM(require_react_production(),1);function dur(d2){if(d2==null)return"";let s=d2/1000;return s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m${Math.round(s%60)}s`}var Subagent=import_react19.memo(({tool})=>{let theme=useTheme().theme,[open,setOpen]=import_react19.useState(!1),running=tool.status==="running",failed=tool.status==="error",spin=useSpinnerGlyph(running),trail=tool.trail??[],last=trail[trail.length-1],fg2=failed?theme.error:running?theme.text:theme.textMuted,goal=(tool.goal??tool.preview??"").replace(/\s+/g," ").trim(),sub2=running?last?`\u21B3 ${spec(last.name).verb||last.name} ${last.preview??""}`:trail.length?`\u21B3 ${trail.length} toolcalls`:"":`\u2514 ${trail.length} toolcall${trail.length===1?"":"s"}${tool.duration?` \xB7 ${dur(tool.duration)}`:""}`;return $jsxs("box",{flexDirection:"column",paddingLeft:3+(tool.depth??0)*2,onMouseDown:trail.length?()=>setOpen((o)=>!o):void 0,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:running?theme.warning:fg2,children:[running?spin:"\u2299"," "]}),$jsxs("span",{fg:fg2,children:["Task \u2014 ",goal||"delegating\u2026"]})]})}),open?$jsxs("box",{flexDirection:"column",children:[trail.map((c,i)=>{let s=spec(c.name),lbl=s.verb?`${s.verb} ${c.preview??""}`:c.preview??c.name;return $jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:i<trail.length-1?"\u251C\u2500 ":"\u2514\u2500 "}),$jsxs("span",{fg:theme.textMuted,children:[s.icon," ",lbl]})]})},i)}),tool.result?$jsx("box",{minHeight:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tool.result})}):null]}):sub2?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:sub2})}):null]})});function short(s,n=120){if(!s)return"";let one=s.replace(/\s+/g," ").trim();return one.length>n?one.slice(0,n-1)+"\u2026":one}var Inline=import_react20.memo(({tool})=>{let s=spec(tool.name),body=tool.preview?short(tool.preview):"";return $jsx(InlineTool,{part:tool,complete:!!body||tool.status!=="running",children:s.verb?`${s.verb} ${body}`:body||tool.name})}),Tool=import_react20.memo(({tool,detail="expanded"})=>{if(detail==="hidden"&&tool.status!=="running")return null;if(tool.trail||tool.name==="delegate_task")return $jsx(Subagent,{tool});if(detail!=="expanded")return $jsx(Inline,{tool});let details=[tool.verboseArgs?{label:"Args",text:tool.verboseArgs}:void 0,tool.verboseResult?{label:tool.status==="error"?"Error":"Result",text:tool.verboseResult}:void 0].filter((d2)=>!!d2),s=spec(tool.name),body=tool.preview?short(tool.preview):"";return $jsx(InlineTool,{part:tool,complete:!!body||tool.status!=="running",details,children:s.verb?`${s.verb} ${body}`:body||tool.name})});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_react21.memo((props)=>{let theme=useTheme().theme,refs=import_react21.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_react21.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){return list.reduce((n,p)=>n+(p.type==="thinking"?Math.ceil(p.content.length/80)||1:p.type==="tool"&&p.diff?6:1),0)}var ThoughtCloud=import_react21.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"),tools=all.filter((p)=>p.type==="tool"),[pane,setPane]=import_react21.useState("reasoning");import_react21.useEffect(()=>{if(pane==="reasoning"&&think.length===0&&tools.length>0)setPane("tools");if(pane==="tools"&&tools.length===0&&think.length>0)setPane("reasoning")},[pane,think.length,tools.length]);let body=pane==="reasoning"?think:tools,manual=import_react21.useRef(!1),want=Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,rows(body)+3)),resize=props.onResize;import_react21.useEffect(()=>{if(!manual.current)resize(want)},[want,resize]);let drag=import_react21.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",tools.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,{tool:p,detail:detail==="hidden"?"hidden":"collapsed"})},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_react27=__toESM(require_react_production(),1);var import_react22=__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","Walk lineage back (continues from)","sessions"),"sessions.next":def("right","Walk lineage forward (compressed to)","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"]);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,lead){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]??cap(c.name),body=[...mods,name].join("+");if(!c.leader)return body;return lead?`${lead} ${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 cap(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_react22.createContext(null),NO_OVERRIDES=Object.freeze({}),KeysProvider=({children,overrides:fixedOverrides})=>{let renderer=useRenderer(),prefOverrides=usePref("keys"),overrides=fixedOverrides??prefOverrides??NO_OVERRIDES,table=import_react22.useMemo(()=>{let t2=new Map;for(let id of Object.keys(DEFAULTS2))t2.set(id,parse2(overrides[id]??DEFAULTS2[id].chord));return t2},[overrides]),lead=table.get("leader"),leadLabel=print(lead),armed=import_react22.useRef(!1),stolen=import_react22.useRef(null),timer2=import_react22.useRef(null),[,bump]=import_react22.useState(0),disarm=import_react22.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_react22.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(lead,key2)){arm(),key2.stopPropagation();return}if(armed.current)queueMicrotask(disarm)});let value=import_react22.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_react24=__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){let ref=import_react24.useRef(null),id=(i)=>`${prefix}-row-${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_react26=__toESM(require_react_production(),1);var TabStrip=import_react26.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_react27.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_react31=__toESM(require_react_production(),1);var import_react28=__toESM(require_react_production(),1);var default_default=`{"eikon":1,"name":"nous-girl","width":48,"height":24,"author":"kaio","created":"2026-05-04T02:32:53.930Z"}
|
|
3672
3672
|
{"state":"idle","fps":16,"color":"#7aa2f7","frame_count":64,"loop_from":0}
|
|
3673
3673
|
{"f":0,"data":"\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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"}
|
|
3674
3674
|
{"f":1,"data":"\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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\\n\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"}
|
|
@@ -4083,7 +4083,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
4083
4083
|
`),rows2=all.slice(0,CAP2),more=all.length-rows2.length,marks=intraline(rows2),fg2=(l)=>l.startsWith("@@")?theme.accent:l.startsWith("+++")||l.startsWith("---")?theme.textMuted:l.startsWith("+")?theme.success:l.startsWith("-")?theme.error:theme.textMuted;return $jsxs("box",{flexDirection:"column",backgroundColor:theme.backgroundPanel,children:[rows2.map((l,i)=>{let segs=marks[i],bg2=l.startsWith("+")?theme.diffAddedBg:theme.diffRemovedBg;return $jsx("box",{height:1,overflow:"hidden",minWidth:0,children:$jsx("text",{fg:fg2(l),children:segs?$jsxs($Fragment,{children:[l[0],segs.map((s,j2)=>s.hi?$jsx("span",{bg:bg2,children:s.text},j2):s.text)]}):l||" "})},i)}),more>0?$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2026 ",more," more lines"]})}):null]})});var PATH_KEY=/"(?:path|file_path|filename|target|file)"\s*:\s*"((?:\\.|[^"\\])*)"/,DIFF_HEAD_ARROW=/(?:^|\s)a\/+\S.*?\s*\u2192\s*b\/+(\S.+?)\s*$/m,DIFF_HEAD_NEW=/^\+\+\+ b?\/+(\S.*?)\s*$/m,DIFF_HEAD_OLD=/^--- a?\/+(\S.*?)\s*$/m;function pathFor(t2){let args=t2.args;if(args&&/^\s*\{/.test(args)){let m2=sanitize(args).match(PATH_KEY);if(m2)return m2[1]}let sources=[t2.diff,t2.preview].filter((s)=>!!s);for(let s of sources){let c=sanitize(s),m2=c.match(DIFF_HEAD_ARROW)||c.match(DIFF_HEAD_NEW)||c.match(DIFF_HEAD_OLD);if(m2)return m2[1]}return sanitize(t2.preview??t2.name)}var STRIPS=[/^\s*\u250A.*$/,/^\s*[+-]\d+\s*\/\s*[-+]\d+\s*$/,/^\s*\u2026/,/a\/+\S.*?\s*\u2192\s*b\/+\S/];function sanitizeDiff(s){return sanitize(s).split(`
|
|
4084
4084
|
`).filter((l)=>!STRIPS.some((re2)=>re2.test(l))).join(`
|
|
4085
4085
|
`)}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),lines2=diff.split(`
|
|
4086
|
-
`),add=lines2.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines2.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(0);if(tabs.length===0)return null;let cur=tabs[Math.min(active,tabs.length-1)];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===active;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive(i)},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),$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})})]})});var import_react38=__toESM(require_react_production(),1);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","always","deny"],LABELS={once:"Allow once",session:"Allow this session",always:"Always allow",deny:"Deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),done=import_react38.useRef(!1),send=(c)=>{if(done.current)return;done.current=!0,gw.request("approval.respond",{choice:c}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")};return import_react38.useImperativeHandle(ref,()=>({masked:!1,feed:(key2)=>{if(key2.name==="left"||key2.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key2.name==="right"||key2.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key2.name==="return")return send(CHOICES[sel]),!0;if(key2.name==="escape")return send("deny"),!0;let n=digit(key2.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel]),$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("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]}),$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("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 esc deny"})})]})]})}),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:(key2)=>{if(typing){if(key2.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key2.name==="escape")return send(""),!0;if(key2.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key2.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key2.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key2.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:(key2)=>{if(key2.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}),$jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value,onInput:setValue,onSubmit:()=>go(value),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(value.length)})})]}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync8,statSync as statSync2}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&¶ms[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&¶ms[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(text2){return text2.split(`
|
|
4086
|
+
`),add=lines2.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines2.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(0);if(tabs.length===0)return null;let cur=tabs[Math.min(active,tabs.length-1)];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===active;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive(i)},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),$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})})]})});var import_react38=__toESM(require_react_production(),1);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","always","deny"],LABELS={once:"Allow once",session:"Allow this session",always:"Always allow",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),send=(c)=>{if(done.current)return;done.current=!0,gw.request("approval.respond",{choice:c}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text2)=>{let body=text2.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:(key2)=>{if(steering){if(key2.name==="escape")return setSteering(!1),!0;return!1}if(key2.name==="s")return setSteering(!0),setNote(""),!0;if(key2.name==="left"||key2.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key2.name==="right"||key2.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key2.name==="return")return send(CHOICES[sel]),!0;if(key2.name==="escape")return send("deny"),!0;let n=digit(key2.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("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",{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:(key2)=>{if(typing){if(key2.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key2.name==="escape")return send(""),!0;if(key2.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key2.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key2.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key2.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:(key2)=>{if(key2.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}),$jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value,onInput:setValue,onSubmit:()=>go(value),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(value.length)})})]}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync8,statSync as statSync2}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&¶ms[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&¶ms[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(text2){return text2.split(`
|
|
4087
4087
|
`).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(existsSync8(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync8(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=statSync2(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key2=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key2);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(key2,rows2),{rows:rows2}}var basename6=(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((row2,i)=>$jsx("text",{children:row2.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:basename6(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 useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsx("box",{flexDirection:"column",marginBottom:1,backgroundColor:hover?theme.backgroundElement:void 0,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:$jsx(Gutter2,{color:theme.primary,side:"left",children:$jsx("box",{minHeight:1,flexDirection:"column",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}`)})})})})})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsx("box",{flexDirection:"column",marginBottom:1,backgroundColor:hover?theme.backgroundElement:void 0,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:$jsxs(Gutter2,{color:err?theme.error:theme.accent,side:"right",children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]})})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant",firstUser=messages.findIndex((m2)=>m2.role==="user");return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsxs("box",{flexDirection:"column",children:[msg.role==="user"&&i>firstUser?$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"\u2500\u2500\u2500"})}):null,$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})]},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react61=__toESM(require_react_production(),1);var import_react53=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync9}from"fs";import{homedir as homedir4}from"os";import{join as join8}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join8(homedir4(),".hermes"),entry=()=>{let js=join8(import.meta.dirname,"db.worker.js");return new URL(existsSync9(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn=()=>{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))),spawn().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((key2)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key2))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:[$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),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,text2=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:text2})})});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,text2=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(text2.length>w2),!animate){tn.scrollX=0;return}let id,period=text2.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text2.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,text2,p.speed,p.hold]);let body=wraps?text2+GAP+text2:text2;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 Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key2)=>{if(keys.match("dialog.confirm",key2)||keys.match("dialog.accept",key2))return props.onConfirm();if(keys.match("dialog.deny",key2))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((key2)=>{if(key2.name==="s")return props.onPick("save");if(key2.name==="d")return props.onPick("discard");if(key2.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_react51=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react51.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),cost=(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_react52=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync11,statSync as statSync3}from"fs";import{dirname as dirname4,basename as basename7}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync as openSync2,readSync as readSync2,closeSync as closeSync2,readdirSync as readdirSync4,readFileSync as readFileSync3,existsSync as existsSync10}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=(relative2)=>`${home.path}/${relative2}`,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=(relative2,label)=>({file:hermesPath(relative2),relative:relative2,label:label??relative2.split("/").pop()??relative2});function readSkillFrontmatter(source){try{let fd=openSync2(source.file,"r"),buf=Buffer.alloc(2048),n=readSync2(fd,buf,0,2048,0);closeSync2(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
|
|
4088
4088
|
---`,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=readdirSync4(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 readdirSync4(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory()).sort((a,b2)=>b2.name.localeCompare(a.name)).flatMap((e)=>{try{let fd=openSync2(`${base2}/${e.name}/run.json`,"r"),buf=Buffer.alloc(8192),n=readSync2(fd,buf);closeSync2(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 readdirSync4(base2,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let j2=JSON.parse(readFileSync3(`${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=openSync2(source.file,"r"),buf=Buffer.alloc(4096),n=readSync2(fd,buf);closeSync2(fd);let body=buf.toString("utf8",0,n).trim(),line=body.split(`
|
|
4089
4089
|
`).find((l)=>/^[-*\u00B7]/.test(l.trim()));return{source,headline:line?.replace(/^[-*\u00B7]\s*/,"").trim()??"",body}}catch{return null}}async function readConfig(){try{let text2=await Bun.file(hermesPath("config.yaml")).text(),raw=$parse(text2);return{source:makeSource("config.yaml","config.yaml"),model:{default:raw?.model?.default??"unknown",provider:raw?.model?.provider??"auto",base_url:raw?.model?.base_url??""},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 relative2=`memories/${filename}`,content=await Bun.file(hermesPath(relative2)).text(),entryCount=content.split("\xA7").filter((s)=>s.trim()).length;return{source:makeSource(relative2,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 text2=await file.text();return JSON.parse(text2)}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 readdirSync4(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 text2=await Bun.file(hermesPath("SOUL.md")).text();return{source:makeSource("SOUL.md"),charCount:text2.length,tokenEstimate:count2(text2),content:text2}}catch{return null}}async function readToolsFromLatestSession(){try{let dir=hermesPath("sessions");if(!existsSync10(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 relative2=`sessions/${latestPath}`,tools=((await Bun.file(hermesPath(relative2)).json()).tools||[]).map((t2)=>({name:t2?.function?.name??"unknown",descriptionLength:(t2?.function?.description??"").length,paramsLength:JSON.stringify(t2?.function?.parameters??{}).length}));return{source:makeSource(relative2,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(),lines2=full.trimEnd().split(`
|
|
@@ -4150,7 +4150,7 @@ Usage:
|
|
|
4150
4150
|
|
|
4151
4151
|
${n} mapped \xB7 ${r.skipped.length} skipped (no herm equivalent)${r.skipped.length?`:
|
|
4152
4152
|
${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((key2)=>{if(key2.name==="up")return setSel((s)=>Math.max(0,s-1));if(key2.name==="down")return setSel((s)=>Math.min(actionRows.length-1,s+1));if(key2.name==="return"&&cur)return rebind(cur.id);if(key2.name==="r"&&!key2.ctrl&&cur?.override){write(cur.id,void 0);return}if(key2.name==="o"&&!key2.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,lines2=useGateway().tail(200).split(`
|
|
4153
|
-
`).filter(Boolean);return $jsxs("box",{flexDirection:"column",width:110,height:Math.min(34,Math.max(8,lines2.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:[lines2.length," lines \xB7 stderr + protocol \xB7 Esc to close"]})}),$jsx("box",{height:1}),lines2.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:lines2.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_react112=__toESM(require_react_production(),1);var ThemePickerDialog=({onConfirm})=>{let ctx=useTheme(),dialog=useDialog(),options=ctx.names.map((n)=>({title:n,value:n})),onMove=import_react112.useCallback((opt)=>{ctx.set(opt.value)},[ctx]),onSelect=import_react112.useCallback((opt)=>{ctx.set(opt.value),onConfirm(),dialog.clear()},[ctx,dialog,onConfirm]);return $jsx(DialogSelect,{title:"Switch Theme",options,current:ctx.name,onSelect,onMove,placeholder:"Search themes..."})},openThemePicker=(dialog,ctx)=>{let saved=ctx.name,confirmed=!1;dialog.replace($jsx(ThemePickerDialog,{onConfirm:()=>{confirmed=!0}}),()=>{if(!confirmed)ctx.set(saved)})};var import_react113=__toESM(require_react_production(),1);import{readFileSync as readFileSync13}from"fs";import{homedir as homedir8}from"os";import{join as join16}from"path";var trunc6=(s,n)=>s.length<=n?s:s.slice(0,n-1)+"\u2026",defaultDirs=()=>{let hermesHome2=process.env.HERMES_HOME||join16(homedir8(),".hermes");return[BUNDLED_EIKON_DIR,join16(hermesHome2,"eikons")]},EikonPickerDialog=(props)=>{let theme=useTheme().theme,dialog=useDialog(),dirs=props.dirs??defaultDirs(),found=import_react113.useMemo(()=>listEikons(dirs),[dirs]),[cursor,setCursor]=import_react113.useState(0),cur=found[cursor],parsed=import_react113.useMemo(()=>{if(!cur)return;try{return parseEikon(readFileSync13(cur.path,"utf8"))}catch{return}},[cur]);useListKeys({active:!0,count:found.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:`${found.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:found.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No .eikon files found."})},"empty"):found.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 \xB7 ${e.meta.width}\xD7${e.meta.height}`})})]},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_react114=__toESM(require_react_production(),1);var RollbackDialog=(props)=>{let theme=useTheme().theme,[data2,setData]=import_react114.useState(props.initial??null),[sel,setSel]=import_react114.useState(props.sel??0),[diff,setDiff]=import_react114.useState(null),[confirm,setConfirm]=import_react114.useState(!1);import_react114.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((key2)=>{if(diff){if(confirm){if(keys.match("dialog.confirm",key2))return restore(cur);if(keys.match("dialog.deny",key2)||keys.match("dialog.cancel",key2))return setConfirm(!1),back();return}if(keys.match("dialog.cancel",key2))return back();if(key2.name==="r")return setConfirm(!0);return}if(!data2?.enabled)return;handleListKey(keys,key2,{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_react116=__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_react116.useState(null),[err,setErr]=import_react116.useState("");import_react116.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_react117=__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})})}),$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,info2,sid){let toolsets=Object.keys(info2?.tools??{}),nTools=Object.values(info2?.tools??{}).reduce((n,v2)=>n+v2.length,0),mcp=info2?.mcp_servers??[],up=mcp.filter((s)=>s.connected).length;dialog.replace($jsx(InfoDialog,{title:"Status",rows:[["Version",info2?.version||"\u2014"],["Model",info2?.model||"\u2014"],["Profile",activeProfileName()],["Home",hermesPath("")],["CWD",info2?.cwd||process.cwd()],["Session",sid||"\u2014"],["Tools",`${nTools} in ${toolsets.length} toolset${toolsets.length===1?"":"s"}`],["Skills",String(Object.values(info2?.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_react117.useState(null),[err,setErr]=import_react117.useState("");if(import_react117.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",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?cost(u3.cost_usd):void 0,theme.accent]]})},openUsage=(dialog,gw)=>dialog.replace($jsx(UsageDialog,{gw})),ProfileDialog=()=>{let[p,setP]=import_react117.useState(void 0),active=activeProfileName();if(import_react117.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_react118=__toESM(require_react_production(),1);import{spawnSync as spawnSync3}from"child_process";import{existsSync as existsSync19}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(existsSync19(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(!existsSync19(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_react118.useState(80),[h2]=import_react118.useState(28),result=import_react118.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((row2,i)=>$jsx("text",{children:row2.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_react120=__toESM(require_react_production(),1);import{tmpdir as tmpdir3}from"os";import{join as join17}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=join17(tmpdir3(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text2=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text2.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text2.trim()||void 0}var exports_selection={};__export(exports_selection,{yank:()=>yank,key:()=>key2,Selection:()=>exports_selection});function yank(renderer,toast){let text2=renderer.getSelection()?.getSelectedText();if(!text2)return!1;return copy(text2).then(()=>toast?.push("Copied to clipboard","info")).catch(()=>toast?.push("Clipboard write failed","err")),renderer.clearSelection(),!0}function key2(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 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(key3,configured=DEFAULT_VOICE_KEY){if(key3.name.toLowerCase()!==configured.ch)return!1;if(key3.shift)return!1;switch(configured.mod){case"ctrl":return key3.ctrl&&!key3.meta&&!key3.super;case"alt":return key3.meta&&!key3.ctrl&&!key3.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_react120.useRef(0),lastTab=import_react120.useRef(0),lastQuit=import_react120.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react120.useEffect(()=>{let found=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found.length===0)return;let first=found[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found.length>1?` (+${found.length-1} more)`:""))},[keys.table]),useKeyboard((key3)=>{let c=o.composer.current;if(exports_selection.key(renderer,key3)){key3.stopPropagation();return}if(keys.match("input.clear",key3)&&c&&!c.isEmpty()){let v2=c.value().trim();if(v2.length>=20)c.remember(v2);c.set(""),lastQuit.current=0,key3.stopPropagation();return}if(keys.match("input.stash",key3)){o.onStash(),key3.stopPropagation();return}if(keys.match("app.exit",key3)){let now2=Date.now();if(now2-lastQuit.current<QUIT_MS)return o.onQuit();lastQuit.current=now2,o.onQuitArm(keys.print("app.exit")),key3.stopPropagation();return}if(keys.match("app.suspend",key3)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key3)){redraw(renderer),key3.stopPropagation();return}if(keys.match("app.sidebar",key3)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(o.voiceRecordKey&&o.onVoiceRecord&&isVoiceToggleKey(key3,o.voiceRecordKey)){o.onVoiceRecord(),key3.stopPropagation();return}if(c?.mode()==="shell"){if(key3.name==="escape"){c.setMode("normal"),key3.stopPropagation();return}if(key3.name==="backspace"&&!key3.ctrl&&!key3.meta&&c.caret()===0){c.setMode("normal"),key3.stopPropagation();return}}if(keys.match("queue.flush",key3)&&o.streaming&&o.queued>0){o.onFlushQueue(),key3.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"){if(o.onPromptKey(key3)){key3.stopPropagation();return}}if(keys.match("editor.open",key3)&&!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",key3)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key3)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key3.shift&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"){if(key3.name==="left"){o.cycleSub(-1),key3.stopPropagation();return}if(key3.name==="right"){o.cycleSub(1),key3.stopPropagation();return}}if(keys.leader&&!key3.ctrl&&!key3.meta&&!key3.shift&&key3.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}[key3.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key3.stopPropagation();return}}if(key3.meta&&!key3.ctrl&&!key3.shift&&key3.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}[key3.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key3.stopPropagation();return}}if(c?.popOpen()){if(key3.name==="escape")return c.popCancel();if(key3.name==="up"){c.popNav(-1),key3.stopPropagation();return}if(key3.name==="down"){c.popNav(1),key3.stopPropagation();return}if(key3.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key3)&&!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,key3.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key3)){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",key3))return o.onCopyLast();if(keys.match("clipboard.attach",key3)){o.onAttachClipboard(),key3.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if((key3.name==="!"||key3.name==="1"&&key3.shift)&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"&&c&&c.mode()==="normal"&&!c.popOpen()&&c.caret()===0){c.setMode("shell"),key3.stopPropagation();return}if(key3.name==="up")return void c?.historyUp();if(key3.name==="down")return void c?.historyDown();if(key3.name==="backspace"&&!key3.ctrl&&!key3.meta&&c?.isEmpty()&&o.onDetachLast()){key3.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"){if(key3.name.length===1&&key3.name!==" "){let ch=key3.shift&&/[a-z]/.test(key3.name)?key3.name.toUpperCase():key3.name;o.setFocusRegion("input"),c?.insert(ch),key3.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY){let banner=sid?`
|
|
4153
|
+
`).filter(Boolean);return $jsxs("box",{flexDirection:"column",width:110,height:Math.min(34,Math.max(8,lines2.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:[lines2.length," lines \xB7 stderr + protocol \xB7 Esc to close"]})}),$jsx("box",{height:1}),lines2.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:lines2.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_react112=__toESM(require_react_production(),1);var ThemePickerDialog=({onConfirm})=>{let ctx=useTheme(),dialog=useDialog(),options=ctx.names.map((n)=>({title:n,value:n})),onMove=import_react112.useCallback((opt)=>{ctx.set(opt.value)},[ctx]),onSelect=import_react112.useCallback((opt)=>{ctx.set(opt.value),onConfirm(),dialog.clear()},[ctx,dialog,onConfirm]);return $jsx(DialogSelect,{title:"Switch Theme",options,current:ctx.name,onSelect,onMove,placeholder:"Search themes..."})},openThemePicker=(dialog,ctx)=>{let saved=ctx.name,confirmed=!1;dialog.replace($jsx(ThemePickerDialog,{onConfirm:()=>{confirmed=!0}}),()=>{if(!confirmed)ctx.set(saved)})};var import_react113=__toESM(require_react_production(),1);import{readFileSync as readFileSync13}from"fs";import{homedir as homedir8}from"os";import{join as join16}from"path";var trunc6=(s,n)=>s.length<=n?s:s.slice(0,n-1)+"\u2026",defaultDirs=()=>{let hermesHome2=process.env.HERMES_HOME||join16(homedir8(),".hermes");return[BUNDLED_EIKON_DIR,join16(hermesHome2,"eikons")]},EikonPickerDialog=(props)=>{let theme=useTheme().theme,dialog=useDialog(),dirs=props.dirs??defaultDirs(),found=import_react113.useMemo(()=>listEikons(dirs),[dirs]),[cursor,setCursor]=import_react113.useState(0),cur=found[cursor],parsed=import_react113.useMemo(()=>{if(!cur)return;try{return parseEikon(readFileSync13(cur.path,"utf8"))}catch{return}},[cur]);useListKeys({active:!0,count:found.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:`${found.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:found.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No .eikon files found."})},"empty"):found.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 \xB7 ${e.meta.width}\xD7${e.meta.height}`})})]},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_react114=__toESM(require_react_production(),1);var RollbackDialog=(props)=>{let theme=useTheme().theme,[data2,setData]=import_react114.useState(props.initial??null),[sel,setSel]=import_react114.useState(props.sel??0),[diff,setDiff]=import_react114.useState(null),[confirm,setConfirm]=import_react114.useState(!1);import_react114.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((key2)=>{if(diff){if(confirm){if(keys.match("dialog.confirm",key2))return restore(cur);if(keys.match("dialog.deny",key2)||keys.match("dialog.cancel",key2))return setConfirm(!1),back();return}if(keys.match("dialog.cancel",key2))return back();if(key2.name==="r")return setConfirm(!0);return}if(!data2?.enabled)return;handleListKey(keys,key2,{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_react116=__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_react116.useState(null),[err,setErr]=import_react116.useState("");import_react116.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_react117=__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})})}),$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,info2,sid){let toolsets=Object.keys(info2?.tools??{}),nTools=Object.values(info2?.tools??{}).reduce((n,v2)=>n+v2.length,0),mcp=info2?.mcp_servers??[],up=mcp.filter((s)=>s.connected).length;dialog.replace($jsx(InfoDialog,{title:"Status",rows:[["Version",info2?.version||"\u2014"],["Model",info2?.model||"\u2014"],["Profile",activeProfileName()],["Home",hermesPath("")],["CWD",info2?.cwd||process.cwd()],["Session",sid||"\u2014"],["Tools",`${nTools} in ${toolsets.length} toolset${toolsets.length===1?"":"s"}`],["Skills",String(Object.values(info2?.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_react117.useState(null),[err,setErr]=import_react117.useState("");if(import_react117.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",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?cost(u3.cost_usd):void 0,theme.accent]]})},openUsage=(dialog,gw)=>dialog.replace($jsx(UsageDialog,{gw})),ProfileDialog=()=>{let[p,setP]=import_react117.useState(void 0),active=activeProfileName();if(import_react117.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_react118=__toESM(require_react_production(),1);import{spawnSync as spawnSync3}from"child_process";import{existsSync as existsSync19}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(existsSync19(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(!existsSync19(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_react118.useState(80),[h2]=import_react118.useState(28),result=import_react118.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((row2,i)=>$jsx("text",{children:row2.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_react120=__toESM(require_react_production(),1);import{tmpdir as tmpdir3}from"os";import{join as join17}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=join17(tmpdir3(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text2=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text2.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text2.trim()||void 0}var exports_selection={};__export(exports_selection,{yank:()=>yank,key:()=>key2,Selection:()=>exports_selection});function yank(renderer,toast){let text2=renderer.getSelection()?.getSelectedText();if(!text2)return!1;return copy(text2).then(()=>toast?.push("Copied to clipboard","info")).catch(()=>toast?.push("Clipboard write failed","err")),renderer.clearSelection(),!0}function key2(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 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(key3,configured=DEFAULT_VOICE_KEY){if(key3.name.toLowerCase()!==configured.ch)return!1;if(key3.shift)return!1;switch(configured.mod){case"ctrl":return key3.ctrl&&!key3.meta&&!key3.super;case"alt":return key3.meta&&!key3.ctrl&&!key3.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_react120.useRef(0),lastTab=import_react120.useRef(0),lastQuit=import_react120.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react120.useEffect(()=>{let found=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found.length===0)return;let first=found[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found.length>1?` (+${found.length-1} more)`:""))},[keys.table]),useKeyboard((key3)=>{let c=o.composer.current;if(exports_selection.key(renderer,key3)){key3.stopPropagation();return}if(keys.match("input.clear",key3)&&c&&!c.isEmpty()){let v2=c.value().trim();if(v2.length>=20)c.remember(v2);c.set(""),lastQuit.current=0,key3.stopPropagation();return}if(keys.match("input.stash",key3)){o.onStash(),key3.stopPropagation();return}if(keys.match("app.exit",key3)){let now2=Date.now();if(now2-lastQuit.current<QUIT_MS)return o.onQuit();lastQuit.current=now2,o.onQuitArm(keys.print("app.exit")),key3.stopPropagation();return}if(keys.match("app.suspend",key3)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key3)){redraw(renderer),key3.stopPropagation();return}if(keys.match("app.sidebar",key3)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(o.voiceRecordKey&&o.onVoiceRecord&&isVoiceToggleKey(key3,o.voiceRecordKey)){o.onVoiceRecord(),key3.stopPropagation();return}if(c?.mode()==="shell"){if(key3.name==="escape"){c.setMode("normal"),key3.stopPropagation();return}if(key3.name==="backspace"&&!key3.ctrl&&!key3.meta&&c.caret()===0){c.setMode("normal"),key3.stopPropagation();return}}if(keys.match("session.steer",key3)){o.onSteer(),key3.stopPropagation();return}if(keys.match("queue.flush",key3)&&o.streaming&&o.queued>0){o.onFlushQueue(),key3.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"){if(o.onPromptKey(key3)){key3.stopPropagation();return}}if(keys.match("editor.open",key3)&&!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",key3)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key3)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key3.shift&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"){if(key3.name==="left"){o.cycleSub(-1),key3.stopPropagation();return}if(key3.name==="right"){o.cycleSub(1),key3.stopPropagation();return}}if(keys.leader&&!key3.ctrl&&!key3.meta&&!key3.shift&&key3.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}[key3.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key3.stopPropagation();return}}if(key3.meta&&!key3.ctrl&&!key3.shift&&key3.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}[key3.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key3.stopPropagation();return}}if(c?.popOpen()){if(key3.name==="escape")return c.popCancel();if(key3.name==="up"){c.popNav(-1),key3.stopPropagation();return}if(key3.name==="down"){c.popNav(1),key3.stopPropagation();return}if(key3.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key3)&&!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,key3.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key3)){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",key3))return o.onCopyLast();if(keys.match("clipboard.attach",key3)){o.onAttachClipboard(),key3.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if((key3.name==="!"||key3.name==="1"&&key3.shift)&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"&&c&&c.mode()==="normal"&&!c.popOpen()&&c.caret()===0){c.setMode("shell"),key3.stopPropagation();return}if(key3.name==="up")return void c?.historyUp();if(key3.name==="down")return void c?.historyDown();if(key3.name==="backspace"&&!key3.ctrl&&!key3.meta&&c?.isEmpty()&&o.onDetachLast()){key3.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key3.ctrl&&!key3.meta&&key3.eventType!=="release"){if(key3.name.length===1&&key3.name!==" "){let ch=key3.shift&&/[a-z]/.test(key3.name)?key3.name.toUpperCase():key3.name;o.setFocusRegion("input"),c?.insert(ch),key3.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY){let banner=sid?`
|
|
4154
4154
|
continue herm --resume ${sid}${title?` \u2014 ${title.slice(0,60)}`:""}
|
|
4155
4155
|
|
|
4156
4156
|
`:`
|
|
@@ -4193,8 +4193,8 @@ ${lines2.join(`
|
|
|
4193
4193
|
`)&&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(`
|
|
4194
4194
|
`,t2.cursorOffset)>=0)return!1;if(buf2.includes(`
|
|
4195
4195
|
`)&&t2.cursorOffset!==buf2.length)return t2.cursorOffset=buf2.length,!0;return hist.down(),!0}}),[hist.up,hist.down,pop3.setCursor,write]);let sidsRef=import_react139.useRef(sids);sidsRef.current=sids;let taRef=import_react139.useCallback((r)=>{if(ta.current=r,r&&!buf.current)buf.current=new PartsBuffer(r,sidsRef.current);if(!r)buf.current=null},[]),label=!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(`
|
|
4196
|
-
`).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})}):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:["~",fmt4(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:submit,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":label}),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_react140=__toESM(require_react_production(),1);init_sessions_db();var spec2=(row2)=>{if(!row2?.model)return null;if(!row2.billing_provider)return row2.model;return`${row2.model} --provider ${row2.billing_provider}`},normalize2=(sid)=>sid.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user)messages.push(...transcriptToMessages([{role:"user",text:user}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react140.useCallback(async(sid)=>{let target=normalize2(sid),row2=byId(target),res=await gw.request("session.resume",{session_id:target}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target);let model=spec2(row2);if(model)await gw.request("config.set",{key:"model",value:model}).catch(()=>{});let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react140.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_react140.useCallback(async(sid)=>{let target=normalize2(sid),res=await gw.request("session.activate",{session_id:target}),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]),close=import_react140.useCallback(async(sid)=>{if(!sid)return;try{await gw.request("session.close",{session_id:sid})}catch{}},[gw]),boot2=import_react140.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target=launch.sid??exports_sessions_db.lastReal()?.id;if(!target)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row2=last3?exports_sessions_db.byId(last3):null;if(row2?.message_count===0&&row2.parent_session_id==null)try{return await resume(row2.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react140.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react140.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react140.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react140.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react140.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_react141=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react141.useState(p.seconds);import_react141.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:(sid)=>{if(!sid)return;io.goalState(sid).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid)===s.goal)return;fired.set(sid,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react143=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react143.useState(!1),[recording,setRecording]=import_react143.useState(!1),[processing,setProcessing]=import_react143.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react143.useState(),[tts,setTts]=import_react143.useState(!1),[onTranscript,setTranscript]=import_react143.useState(null),setOnTranscript=import_react143.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react143.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react143.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react143.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react143.useCallback(async(action,sid)=>{try{let r=await gw("voice.toggle",{action,session_id:sid});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 label=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react143.useCallback(async(sid)=>{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:sid});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 text2,fg2=theme.text;if(voice.recording)text2="\u25CF recording",fg2=theme.error;else if(voice.processing)text2="\u25CC transcribing",fg2=theme.warning;else text2=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text2," "]})})}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react145.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react145.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react145.useState(!1),[sid,setSid]=import_react145.useState(""),sidRef=import_react145.useRef(sid);sidRef.current=sid;let[tab,setTab]=import_react145.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react145.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react145.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react145.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react145.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react145.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react145.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react145.useState(!1),[usage,setUsage]=import_react145.useState(void 0),[info2,setInfo]=import_react145.useState(null),[title,setTitle]=import_react145.useState(""),titleRef=import_react145.useRef(title);titleRef.current=title,import_react145.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react145.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_react145.useState("input"),goToTab=import_react145.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react145.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react145.useState(""),[escHint,setEscHint]=import_react145.useState(!1),[eikon,setEikon]=import_react145.useState(void 0),[queue,setQueue]=import_react145.useState([]),[busy,setBusy]=import_react145.useState("queue"),turnRef=import_react145.useRef(turn);turnRef.current=turn;let queueRef=import_react145.useRef(queue);queueRef.current=queue;let launchRef=import_react145.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react145.useState(launch.splash!==!1),[switching,setSwitching]=import_react145.useState(!1),summoned=import_react145.useRef(!1),[composing,setComposing]=import_react145.useState(!1),splashLast=import_react145.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react145.useMemo(()=>info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,[info2?.version,info2?.update_behind,info2?.model]),splashLastProp=import_react145.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react145.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react145.useState([]),[cloudH,setCloudH]=import_react145.useState(CLOUD_MIN),[pick2,setPick]=import_react145.useState(void 0),[skin,setSkin]=import_react145.useState(()=>deriveSkin(void 0)),inflight=import_react145.useRef(!1),undone=import_react145.useRef([]),sessionStart=import_react145.useRef(Date.now()),composer2=import_react145.useRef(null),promptRef=import_react145.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react145.useRef(cmds);cmdsRef.current=cmds;let sys=import_react145.useCallback((text2)=>dispatch({kind:"system",text:text2}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react145.useEffect(()=>{voice.setOnTranscript((text2)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text2),0)})},[]);let[errorPulse,setErrorPulse]=import_react145.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react145.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react145.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react145.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react145.useRef(turn.streaming);import_react145.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react145.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react145.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react145.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react145.useRef(()=>{}),onEnqueue=import_react145.useCallback((t2)=>{if(busy==="steer"){gw.request("session.steer",{text:t2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"steered \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q5)=>[t2,...q5]);setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react145.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse});intr.current=stream.doInterrupt;let reset3=import_react145.useCallback(()=>{stream.interrupted.current=!1,undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[]),newSession=import_react145.useCallback(async()=>{let prev=sidRef.current;if(reset3(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev);try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset3,session,gw]),switchSession=import_react145.useCallback(async(target)=>{let prev=sidRef.current;reset3(),summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target);if(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);setSplash(!1),summoned.current=!1}catch(err){dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,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_react145.useCallback(async(target)=>{let prev=sidRef.current;reset3(),summoned.current=!0,setSplash(!0),setSwitching(!0),goToTab(CHAT_TAB);try{let res=await session.activate(target);if(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){dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,session,goToTab,toast]),switchProfile=import_react145.useCallback((newHome,name)=>{rehome(newHome),reset3(),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()},[reset3,goToTab,gwRestart,toast,gw]),loadEikon=import_react145.useCallback((path7)=>{Bun.file(path7).text().then((t2)=>setEikon(parseEikon(t2))).catch(()=>{})},[]),eikonName=usePref("eikon"),eikonRev=import_react145.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react145.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_react145.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text2),setFocusRegion("input")},[gw]),fork2=import_react145.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await switchSession(res.session_id),composer2.current?.set(text2),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,switchSession]),msgMenu=import_react145.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react145.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_react145.useRef(()=>{}),slash=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,ready,info:info2,sid,title,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react145.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sid,title,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve8(cmdsRef.current,name);if("hit"in r)return slash(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text2=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text2=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text2].filter(Boolean).join(`
|
|
4196
|
+
`).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})}):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:["~",fmt4(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:submit,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":label}),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,$jsx("box",{height:1,flexDirection:"row",onMouseDown:()=>props.onSteer?.(),children:$jsxs("text",{children:[$jsx("span",{fg:theme.borderSubtle,children:"\u25C7 "}),$jsx("span",{fg:theme.textMuted,children:"steer "}),$jsx("span",{fg:theme.accent,children:keys.print("session.steer")})]})}),$jsx("text",{fg:theme.textMuted,children:" "}),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_react140=__toESM(require_react_production(),1);init_sessions_db();var spec2=(row2)=>{if(!row2?.model)return null;if(!row2.billing_provider)return row2.model;return`${row2.model} --provider ${row2.billing_provider}`},normalize2=(sid)=>sid.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user)messages.push(...transcriptToMessages([{role:"user",text:user}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react140.useCallback(async(sid)=>{let target=normalize2(sid),row2=byId(target),res=await gw.request("session.resume",{session_id:target}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target);let model=spec2(row2);if(model)await gw.request("config.set",{key:"model",value:model}).catch(()=>{});let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react140.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_react140.useCallback(async(sid)=>{let target=normalize2(sid),res=await gw.request("session.activate",{session_id:target}),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]),close=import_react140.useCallback(async(sid)=>{if(!sid)return;try{await gw.request("session.close",{session_id:sid})}catch{}},[gw]),boot2=import_react140.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target=launch.sid??exports_sessions_db.lastReal()?.id;if(!target)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row2=last3?exports_sessions_db.byId(last3):null;if(row2?.message_count===0&&row2.parent_session_id==null)try{return await resume(row2.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react140.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react140.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react140.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react140.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react140.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_react141=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react141.useState(p.seconds);import_react141.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:(sid)=>{if(!sid)return;io.goalState(sid).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid)===s.goal)return;fired.set(sid,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react143=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react143.useState(!1),[recording,setRecording]=import_react143.useState(!1),[processing,setProcessing]=import_react143.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react143.useState(),[tts,setTts]=import_react143.useState(!1),[onTranscript,setTranscript]=import_react143.useState(null),setOnTranscript=import_react143.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react143.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react143.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react143.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react143.useCallback(async(action,sid)=>{try{let r=await gw("voice.toggle",{action,session_id:sid});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 label=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react143.useCallback(async(sid)=>{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:sid});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 text2,fg2=theme.text;if(voice.recording)text2="\u25CF recording",fg2=theme.error;else if(voice.processing)text2="\u25CC transcribing",fg2=theme.warning;else text2=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text2," "]})})}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react145.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react145.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react145.useState(!1),[sid,setSid]=import_react145.useState(""),sidRef=import_react145.useRef(sid);sidRef.current=sid;let[tab,setTab]=import_react145.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react145.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react145.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react145.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react145.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react145.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react145.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react145.useState(!1),[usage,setUsage]=import_react145.useState(void 0),[info2,setInfo]=import_react145.useState(null),[title,setTitle]=import_react145.useState(""),titleRef=import_react145.useRef(title);titleRef.current=title,import_react145.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react145.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_react145.useState("input"),goToTab=import_react145.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react145.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react145.useState(""),[escHint,setEscHint]=import_react145.useState(!1),[eikon,setEikon]=import_react145.useState(void 0),[queue,setQueue]=import_react145.useState([]),[busy,setBusy]=import_react145.useState("queue"),turnRef=import_react145.useRef(turn);turnRef.current=turn;let queueRef=import_react145.useRef(queue);queueRef.current=queue;let launchRef=import_react145.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react145.useState(launch.splash!==!1),[switching,setSwitching]=import_react145.useState(!1),summoned=import_react145.useRef(!1),[composing,setComposing]=import_react145.useState(!1),splashLast=import_react145.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react145.useMemo(()=>info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,[info2?.version,info2?.update_behind,info2?.model]),splashLastProp=import_react145.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react145.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react145.useState([]),[cloudH,setCloudH]=import_react145.useState(CLOUD_MIN),[pick2,setPick]=import_react145.useState(void 0),[skin,setSkin]=import_react145.useState(()=>deriveSkin(void 0)),inflight=import_react145.useRef(!1),undone=import_react145.useRef([]),sessionStart=import_react145.useRef(Date.now()),composer2=import_react145.useRef(null),promptRef=import_react145.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react145.useRef(cmds);cmdsRef.current=cmds;let sys=import_react145.useCallback((text2)=>dispatch({kind:"system",text:text2}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react145.useEffect(()=>{voice.setOnTranscript((text2)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text2),0)})},[]);let[errorPulse,setErrorPulse]=import_react145.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react145.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react145.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react145.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react145.useRef(turn.streaming);import_react145.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react145.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react145.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react145.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react145.useRef(()=>{}),steer=import_react145.useCallback((text2)=>{let v2=text2.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_react145.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react145.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q5)=>[t2,...q5]);setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react145.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse});intr.current=stream.doInterrupt;let reset3=import_react145.useCallback(()=>{stream.interrupted.current=!1,undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[]),newSession=import_react145.useCallback(async()=>{let prev=sidRef.current;if(reset3(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev);try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset3,session,gw]),switchSession=import_react145.useCallback(async(target)=>{let prev=sidRef.current;reset3(),summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target);if(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);setSplash(!1),summoned.current=!1}catch(err){dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,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_react145.useCallback(async(target)=>{let prev=sidRef.current;reset3(),summoned.current=!0,setSplash(!0),setSwitching(!0),goToTab(CHAT_TAB);try{let res=await session.activate(target);if(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){dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,session,goToTab,toast]),switchProfile=import_react145.useCallback((newHome,name)=>{rehome(newHome),reset3(),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()},[reset3,goToTab,gwRestart,toast,gw]),loadEikon=import_react145.useCallback((path7)=>{Bun.file(path7).text().then((t2)=>setEikon(parseEikon(t2))).catch(()=>{})},[]),eikonName=usePref("eikon"),eikonRev=import_react145.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react145.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_react145.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text2),setFocusRegion("input")},[gw]),fork2=import_react145.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await switchSession(res.session_id),composer2.current?.set(text2),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,switchSession]),msgMenu=import_react145.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react145.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_react145.useRef(()=>{}),slash=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,ready,info:info2,sid,title,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react145.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sid,title,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve8(cmdsRef.current,name);if("hit"in r)return slash(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text2=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text2=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text2].filter(Boolean).join(`
|
|
4197
4197
|
`):text2;dispatch({kind:"user",text:withMedia}),setAttachments([]),undone.current=[],gw.request("prompt.submit",{text:text2}).catch(()=>{inflight.current=!1}),setTab(CHAT_TAB)},[gw,slash,attachments]);sendRef.current=send;let onShell=import_react145.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:
|
|
4198
4198
|
${err}`].filter(Boolean).join(`
|
|
4199
|
-
`);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_react145.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react145.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react145.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react145.useEffect(()=>{if(turn.streaming||inflight.current||!ready||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[turn.streaming,ready,queue,send]);let dequeue=import_react145.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_react145.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react145.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react145.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;return next2===cur?prev:{...prev,[tab]:next2}})},[tab]);useAppKeys({tab,tabMax,chatTab:CHAT_TAB,setTab,subCount,cycleSub,focusRegion,setFocusRegion,streaming:turn.streaming,dialogOpen:dialog.open,composer:composer2,onPromptKey:(k2)=>promptRef.current?.feed(k2)??!1,onEscape:()=>{if(!splash||!summoned.current)return!1;return setSplash(!1),summoned.current=!1,!0},onInterrupt:stream.doInterrupt,queued:queue.length,onFlushQueue:stream.doInterrupt,onQuit:()=>quit(renderer,sid,title,gw),onQuitArm:(label)=>toast.show({variant:"info",message:`${label} 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)copy(text(m2))},onAttachClipboard:attachClipboard,onDetachLast:()=>{if(attachments.length===0)return!1;return setAttachments((a)=>a.slice(0,-1)),!0},onNotice:(text2)=>dispatch({kind:"system",text:text2}),onToggleSidebar:()=>setHideSidebar((v2)=>!v2),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,focusRegion,setTab,setFocusRegion,dispatch,composer:composer2});let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react145.useCallback((id,label,ok)=>dispatch({kind:"prompt.answered",id,label,ok}),[]),promptWire=import_react145.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react145.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:sid,messages:turn.messages,sessionStart:sessionStart.current,info:info2??void 0});case AUTOMATION_TAB:return $jsx(Automation,{focused:contentFocused,sub:subTabs[AUTOMATION_TAB]??0,setSub:autoSub,sessionId:sid,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_react145.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react145.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt;return $jsx(import_react145.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||!info2}):null]}),$jsxs("box",{flexShrink:0,zIndex:1,children:[$jsx(VoiceIndicator,{voice:voice.state,keyLabel:voice.keyLabel}),$jsx(Composer,{ref:composer2,focused:inputFocused,connected:!!sid,ready,streaming:turn.streaming,status,model:info2?.model,escHint,queue,attachments,cmds,onSend,onSlash:slash,onShell,onAttach,onAttachClipboard:attachClipboard,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})]})]}),dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar?$jsx(import_react145.Profiler,{id:"sidebar",onRender,children:$jsx(Sidebar,{agentState,info:info2,usage,eikon,profile:activeProfileName(),title,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,tab,streaming:turn.streaming})}):null]})})})};init_perf();var exports_bundled_skills={};__export(exports_bundled_skills,{sync:()=>sync,skills:()=>exports_bundled_skills});import{existsSync as existsSync23,mkdirSync as mkdirSync8,readdirSync as readdirSync8,cpSync}from"fs";import{dirname as dirname9,join as join22}from"path";var locate4=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join22(d2,"assets/skills");if(existsSync23(p))return p;let up=dirname9(d2);if(up===d2)break;d2=up}return};function has(root2,n){if(existsSync23(join22(root2,n,"SKILL.md")))return!0;if(!existsSync23(root2))return!1;return readdirSync8(root2,{withFileTypes:!0}).some((e)=>e.isDirectory()&&existsSync23(join22(root2,e.name,n,"SKILL.md")))}function sync(){let src2=locate4();if(!src2)return[];let root2=hermesPath("skills"),dst=join22(root2,"creative"),out=[];for(let e of readdirSync8(src2,{withFileTypes:!0})){if(!e.isDirectory())continue;if(has(root2,e.name))continue;mkdirSync8(dst,{recursive:!0}),cpSync(join22(src2,e.name),join22(dst,e.name),{recursive:!0}),out.push(e.name)}return out}import{writeSync as writeSync2}from"fs";var TERMINAL_MODE_RESET="\x1B[0'z\x1B[0'{\x1B[?2029l\x1B[?1016l\x1B[?1015l\x1B[?1006l\x1B[?1005l\x1B[?1003l\x1B[?1002l\x1B[?1001l\x1B[?1000l\x1B[?9l\x1B[?1004l\x1B[?2004l\x1B[?1049l\x1B[<u\x1B[>4;0m\x1B[0m\x1B[?25h";function resetTerminalModes(stream=process.stdout){if(!stream.isTTY)return!1;let fd=typeof stream.fd==="number"?stream.fd:stream===process.stdout?1:void 0;if(fd!==void 0)try{return writeSync2(fd,TERMINAL_MODE_RESET),!0}catch{}try{return stream.write(TERMINAL_MODE_RESET),!0}catch{return!1}}var wired=!1;function installExitResetHooks(){if(wired)return;wired=!0,process.on("exit",()=>{resetTerminalModes()});let codes={SIGHUP:129,SIGINT:130,SIGTERM:143};for(let sig of["SIGINT","SIGTERM","SIGHUP"])process.on(sig,()=>{resetTerminalModes(),process.exit(codes[sig])});process.on("uncaughtException",(err)=>{resetTerminalModes(),console.error(err),process.exit(1)}),process.on("unhandledRejection",(reason)=>{resetTerminalModes(),console.error(reason),process.exit(1)})}boot("import-graph",Bun.nanoseconds()/1e6);var argv=Bun.argv.slice(2);if(argv.includes("--help")||argv.includes("-h"))process.stdout.write(HELP2),process.exit(0);if(argv.includes("--version")||argv.includes("-v"))process.stdout.write(VERSION+`
|
|
4199
|
+
`);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_react145.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react145.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react145.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react145.useEffect(()=>{if(turn.streaming||inflight.current||!ready||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[turn.streaming,ready,queue,send]);let dequeue=import_react145.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_react145.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react145.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react145.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;return next2===cur?prev:{...prev,[tab]:next2}})},[tab]);useAppKeys({tab,tabMax,chatTab:CHAT_TAB,setTab,subCount,cycleSub,focusRegion,setFocusRegion,streaming:turn.streaming,dialogOpen:dialog.open,composer:composer2,onPromptKey:(k2)=>promptRef.current?.feed(k2)??!1,onEscape:()=>{if(!splash||!summoned.current)return!1;return setSplash(!1),summoned.current=!1,!0},onInterrupt:stream.doInterrupt,queued:queue.length,onFlushQueue:stream.doInterrupt,onQuit:()=>quit(renderer,sid,title,gw),onQuitArm:(label)=>toast.show({variant:"info",message:`${label} 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)copy(text(m2))},onAttachClipboard:attachClipboard,onDetachLast:()=>{if(attachments.length===0)return!1;return setAttachments((a)=>a.slice(0,-1)),!0},onNotice:(text2)=>dispatch({kind:"system",text:text2}),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,focusRegion,setTab,setFocusRegion,dispatch,composer:composer2});let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react145.useCallback((id,label,ok)=>dispatch({kind:"prompt.answered",id,label,ok}),[]),promptWire=import_react145.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react145.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:sid,messages:turn.messages,sessionStart:sessionStart.current,info:info2??void 0});case AUTOMATION_TAB:return $jsx(Automation,{focused:contentFocused,sub:subTabs[AUTOMATION_TAB]??0,setSub:autoSub,sessionId:sid,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_react145.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react145.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt;return $jsx(import_react145.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||!info2}):null]}),$jsxs("box",{flexShrink:0,zIndex:1,children:[$jsx(VoiceIndicator,{voice:voice.state,keyLabel:voice.keyLabel}),$jsx(Composer,{ref:composer2,focused:inputFocused,connected:!!sid,ready,streaming:turn.streaming,status,model:info2?.model,escHint,queue,attachments,cmds,onSend,onSlash:slash,onShell,onAttach,onAttachClipboard:attachClipboard,onEnqueue,onDequeue:dequeue,onSteer:openSteer,onDirty:setComposing,onEmptyEnter})]})]}),dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar?$jsx(import_react145.Profiler,{id:"sidebar",onRender,children:$jsx(Sidebar,{agentState,info:info2,usage,eikon,profile:activeProfileName(),title,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,tab,streaming:turn.streaming})}):null]})})})};init_perf();var exports_bundled_skills={};__export(exports_bundled_skills,{sync:()=>sync,skills:()=>exports_bundled_skills});import{existsSync as existsSync23,mkdirSync as mkdirSync8,readdirSync as readdirSync8,cpSync}from"fs";import{dirname as dirname9,join as join22}from"path";var locate4=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join22(d2,"assets/skills");if(existsSync23(p))return p;let up=dirname9(d2);if(up===d2)break;d2=up}return};function has(root2,n){if(existsSync23(join22(root2,n,"SKILL.md")))return!0;if(!existsSync23(root2))return!1;return readdirSync8(root2,{withFileTypes:!0}).some((e)=>e.isDirectory()&&existsSync23(join22(root2,e.name,n,"SKILL.md")))}function sync(){let src2=locate4();if(!src2)return[];let root2=hermesPath("skills"),dst=join22(root2,"creative"),out=[];for(let e of readdirSync8(src2,{withFileTypes:!0})){if(!e.isDirectory())continue;if(has(root2,e.name))continue;mkdirSync8(dst,{recursive:!0}),cpSync(join22(src2,e.name),join22(dst,e.name),{recursive:!0}),out.push(e.name)}return out}import{writeSync as writeSync2}from"fs";var TERMINAL_MODE_RESET="\x1B[0'z\x1B[0'{\x1B[?2029l\x1B[?1016l\x1B[?1015l\x1B[?1006l\x1B[?1005l\x1B[?1003l\x1B[?1002l\x1B[?1001l\x1B[?1000l\x1B[?9l\x1B[?1004l\x1B[?2004l\x1B[?1049l\x1B[<u\x1B[>4;0m\x1B[0m\x1B[?25h";function resetTerminalModes(stream=process.stdout){if(!stream.isTTY)return!1;let fd=typeof stream.fd==="number"?stream.fd:stream===process.stdout?1:void 0;if(fd!==void 0)try{return writeSync2(fd,TERMINAL_MODE_RESET),!0}catch{}try{return stream.write(TERMINAL_MODE_RESET),!0}catch{return!1}}var wired=!1;function installExitResetHooks(){if(wired)return;wired=!0,process.on("exit",()=>{resetTerminalModes()});let codes={SIGHUP:129,SIGINT:130,SIGTERM:143};for(let sig of["SIGINT","SIGTERM","SIGHUP"])process.on(sig,()=>{resetTerminalModes(),process.exit(codes[sig])});process.on("uncaughtException",(err)=>{resetTerminalModes(),console.error(err),process.exit(1)}),process.on("unhandledRejection",(reason)=>{resetTerminalModes(),console.error(reason),process.exit(1)})}boot("import-graph",Bun.nanoseconds()/1e6);var argv=Bun.argv.slice(2);if(argv.includes("--help")||argv.includes("-h"))process.stdout.write(HELP2),process.exit(0);if(argv.includes("--version")||argv.includes("-v"))process.stdout.write(VERSION+`
|
|
4200
4200
|
`),process.exit(0);var launch=parseLaunch(argv),main2=async()=>{resetTerminalModes(),installExitResetHooks(),mem("pre-renderer");let prefs=load2(),end=mark("renderer-init"),renderer=await createCliRenderer({exitOnCtrlC:!1,useMouse:prefs.mouse??!0,targetFps:prefs.targetFps??30,gatherStats:!1});end();let bump3=()=>renderer.capabilities?.kitty_keyboard||process.stdout.isTTY&&process.stdout.write("\x1B[>4;2m");bump3(),renderer.on("focus",bump3),mem("post-renderer"),await prime(prefs.theme??DEFAULT_THEME);let root2=createRoot(renderer),endRender=mark("first-render");root2.render($jsx(App,{initialTheme:prefs.theme,launch})),endRender(),boot("first-render",Bun.nanoseconds()/1e6),warmup(),warm(),exports_bundled_skills.sync(),mem("post-first-render"),monitor(15000),start()};main2().catch(console.error);
|