herm-tui 1.11.0-dev.1 → 1.11.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +1 -1
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -4062,7 +4062,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
4062
4062
  `),n++}return n}var DEFAULT_SUBMIT_REPO=process.env.EIKON_REPO??"liftaris/eikon",DEFAULT_MAX_BUNDLE_BYTES=33554432,SECRET=/(\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|id_rsa$|id_ed25519$|token|secret|credential|password)/i;var hidden=(rel)=>rel.split(/[\\/]/).some((p)=>p.startsWith(".")),secret=(rel)=>SECRET.test(rel);var posix=(s)=>s.split(sep).join("/");function contain(root2,rel){if(rel.startsWith("/")||/^[A-Za-z]:[\\/]/.test(rel)||rel.split(/[\\/]/).some((p)=>p===".."))throw Error(`submission bundle path escape: ${rel}`);let abs=resolve6(root2,rel),back=relative2(root2,abs);if(back.startsWith("..")||back===""||resolve6(root2,back)!==abs)throw Error(`submission bundle path escape: ${rel}`);return{abs,rel:posix(back)}}function copy(root2,rel,out,opts){let path4=contain(root2,rel);if(!existsSync10(path4.abs))throw Error(`submission bundle missing source: ${path4.rel}`);if(!opts.allowHidden&&hidden(path4.rel))return;if(!opts.allowSecrets&&secret(path4.rel))return;let parts2=path4.rel.split("/"),cur=root2;for(let part of parts2){cur=join7(cur,part);let st=lstatSync2(cur);if(st.isSymbolicLink())throw Error(`submission bundle symlink unsupported: ${path4.rel}`);if(part!==parts2.at(-1)&&!st.isDirectory())return;if(part===parts2.at(-1)&&!st.isFile())return}mkdirSync5(dirname5(join7(out,path4.rel)),{recursive:!0}),copyFileSync3(path4.abs,join7(out,path4.rel))}function refs(raw){let man=JSON.parse(raw);if(man.kind==="eikon.package"){let source=man.source&&typeof man.source==="object"&&!Array.isArray(man.source)?man.source:{},states2=source.states&&typeof source.states==="object"&&!Array.isArray(source.states)?source.states:{};return[...typeof source.base==="string"?[source.base]:[],...Object.values(states2).flatMap((v2)=>typeof v2.file==="string"?[v2.file]:[])]}let states=man.states&&typeof man.states==="object"&&!Array.isArray(man.states)?man.states:{};return[...typeof man.source==="string"?[man.source]:[],...Object.values(states).flatMap((v2)=>typeof v2.file==="string"?[v2.file]:[])]}function walk(dir,base=dir){if(!existsSync10(dir))return[];return readdirSync4(dir,{withFileTypes:!0}).flatMap((item)=>{let abs=join7(dir,item.name);if(item.isDirectory())return walk(abs,base);if(!item.isFile())return[];return[posix(relative2(base,abs))]}).sort()}function artifactFiles(site,name){let keep=[`eikons/${name}/`,`packages/liftaris/${name}/`];return walk(site).filter((path4)=>path4==="eikons/index.json"||keep.some((prefix)=>path4.startsWith(prefix))).map((path4)=>({path:path4,dest:path4,abs:join7(site,path4),bytes:statSync4(join7(site,path4)).size}))}function bundleBytes(files,opts){let bytes=files.reduce((n,f)=>n+f.bytes,0),max=opts.maxBytes??DEFAULT_MAX_BUNDLE_BYTES;if(bytes>max)throw Error(`submission bundle too large: ${bytes} > ${max} bytes`)}function catalog2(site,name){let entry=JSON.parse(readFileSync6(join7(site,"eikons/index.json"),"utf8")).find((e)=>e.name===name);if(entry)return{...normalizeCatalogEntry(entry),w:0,h:0,width:0,height:0,identityKey:entry.sourceKey||entry.id,raw:entry,trust:entry.trust??{},poster:entry.poster??""};return catalogEntry({name},"https://eikon.liftaris.dev/eikons/",{allowPrivate:!0})}function mergeIndex(site,name){let file=join7(site,"eikons/index.json"),next=JSON.parse(readFileSync6(file,"utf8")),base=join7(import.meta.dir,"..","eikons","index.json"),merged=[...(existsSync10(base)?JSON.parse(readFileSync6(base,"utf8")):[]).filter((e)=>e.name!==name),...next].sort((a,b2)=>a.name.localeCompare(b2.name));writeFileSync6(file,JSON.stringify(merged,null,2)+`
4063
4063
  `)}function display(value){let out=Object.fromEntries(Object.entries(value??{}).filter(([,v2])=>typeof v2==="string"&&v2.trim()).map(([k2,v2])=>[k2,v2.trim()]));return Object.keys(out).length?out:void 0}function applyDisplay(site,name,next){let clean3=display(next);if(!clean3)return;for(let path4 of[join7(site,"eikons",name,"manifest.json"),join7(site,"packages","liftaris",name,"1.0.0.json")]){let man=JSON.parse(readFileSync6(path4,"utf8"));writeFileSync6(path4,JSON.stringify({...man,display:{...man.display,...clean3}},null,2)+`
4064
4064
  `)}}async function previewSubmitBundle(opts){let input=resolve6(opts.path),source=dirname5(input),eikon,text3;try{text3=decodeRuntimeFile(input),eikon=lint(text3)}catch(err){throw Error(`invalid eikon: ${err instanceof Error?err.message:String(err)}`)}let name=eikon.meta.name,site=mkdtempSync3(join7(tmpdir2(),"eikon-submit-")),root2=join7(site,"eikons",name);mkdirSync5(root2,{recursive:!0});let runtime=text3.trimStart().startsWith('{"type":"header"')||text3.trimStart().startsWith('{"type":"header",')?text3:(await Promise.resolve().then(() => (init_legacy(),exports_legacy))).migrateLegacyEikon(text3,{id:`liftaris/${name}`,entrypoint:`${name}.eikon`,version:"1.0.0"}).stream;await Bun.write(join7(root2,`${name}.eikon`),encodeRuntimeText(runtime,{encoding:"gzip"}));let mf=join7(source,"manifest.json");if(existsSync10(mf)){copyFileSync3(mf,join7(root2,"manifest.json"));for(let rel of refs(readFileSync6(mf,"utf8")))copy(source,rel,root2,opts)}for(let rel of opts.extraFiles??[])copy(source,rel,root2,opts);manifest2({root:join7(site,"eikons"),encoding:"gzip"}),applyDisplay(site,name,opts.display),await index({root:join7(site,"eikons")}),mergeIndex(site,name);let manifest3=lintManifest(join7(root2,"manifest.json"),readFileSync6(join7(root2,"manifest.json"),"utf8")),files=artifactFiles(site,name);return bundleBytes(files,opts),{root:site,packed:join7(root2,`${name}.eikon`),files,meta:lint(decodeRuntimeFile(join7(root2,`${name}.eikon`))).meta,manifest:manifest3,catalog:catalog2(site,name),lint:[`\u2713 runtime ${name}.eikon`,`\u2713 package manifest ${manifest3.entrypoints.default}`,"\u2713 registry index eikons/index.json"]}}async function gh(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?new TextEncoder().encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code!==0)throw Error(`gh ${args[0]} failed: ${err.trim()||out.trim()}`);return out.trim()}async function existingSha(run,fork,branch,path4){try{let out=await run(["api","-X","GET",`repos/${fork}/contents/${path4}`,"-f",`ref=${branch}`]),json=JSON.parse(out);return typeof json.sha==="string"?json.sha:void 0}catch{return}}function githubSubmitBackend(repo=DEFAULT_SUBMIT_REPO,run=gh){return{async check(){try{return await run(["api","user","-q",".login"]),{ok:!0}}catch(err){return{ok:!1,reason:err instanceof Error?err.message:String(err)}}},async create(req){let name=req.bundle.meta.name,branch=`submit/${name}`;await run(["repo","fork",repo,"--clone=false"]).catch(()=>"");let user=await run(["api","user","-q",".login"]),fork=`${user}/${repo.split("/")[1]}`,main=await run(["api",`repos/${repo}/git/ref/heads/main`,"-q",".object.sha"]);await run(["api","-X","POST",`repos/${fork}/git/refs`,"-f",`ref=refs/heads/${branch}`,"-f",`sha=${main}`]).catch(()=>"");for(let file of req.bundle.files){let content=Buffer.from(await Bun.file(file.abs).arrayBuffer()).toString("base64"),sha2=await existingSha(run,fork,branch,file.dest);await run(["api","-X","PUT",`repos/${fork}/contents/${file.dest}`,"--input","-"],JSON.stringify({message:`eikons: submit ${name}`,branch,content,...sha2?{sha:sha2}:{}}))}return{kind:"submitted",url:await run(["pr","create","-R",repo,"-H",`${user}:${branch}`,"-B","main","-t",req.title,"-b",req.body]),request:req}}}}var STREAM_EXT=/\.eikon$/;function readManifestEntrypoint(path4){try{let entrypoints=JSON.parse(readFileSync7(path4,"utf8")).entrypoints;if(!entrypoints||typeof entrypoints!=="object"||Array.isArray(entrypoints))return;let value=entrypoints.default;return typeof value==="string"&&STREAM_EXT.test(value)?value:void 0}catch{return}}function parseEikon(text3){let first=text3.split(`
4065
- `,1)[0];if((first?JSON.parse(first):{}).type==="header"){let e2=parseLaunchStream(text3);return{meta:e2.meta,states:e2.clips,resolve:(signal)=>{try{return e2.clips.get(resolveSignal(e2,signal).clip)}catch{return}}}}let e=parse3(text3);return{meta:e.meta,states:e.clips,resolve:(signal)=>e.clips.get(signal.replace(/^state\./,""))}}function parseEikonFile(path4){return parseEikon(decodeRuntimeFile(path4))}function listEikons(dirs){return dirs.flatMap((dir)=>{let ents;try{ents=readdirSync5(dir,{recursive:!0})}catch{return[]}let paths=ents.map((e)=>join8(dir,e)),streamFiles=paths.filter((path4)=>STREAM_EXT.test(path4)),packageEntrypoints=new Map;for(let manifest3 of paths.filter((path4)=>path4.endsWith("manifest.json"))){let entrypoint=readManifestEntrypoint(manifest3);if(entrypoint){let root2=dirname6(manifest3);packageEntrypoints.set(root2,join8(root2,entrypoint))}}let packageRootFor=(path4)=>{for(let root2 of packageEntrypoints.keys()){let rel=relative3(root2,path4);if(rel&&!rel.startsWith("..")&&!isAbsolute3(rel))return root2}return};return streamFiles.sort((a,b2)=>a.localeCompare(b2)).filter((path4)=>{let packageRoot=packageRootFor(path4);return packageRoot?path4===packageEntrypoints.get(packageRoot):!0}).map((path4)=>({path:path4,meta:peek2(resolve7(path4))})).filter((x2)=>x2.meta!==null)})}var BLANK2={fps:1,loopFrom:1,frames:[[""]]},DEFAULT_EIKON=(()=>{try{return parseEikon(default_default)}catch{return}})(),STATE_FRAMES={idle:DEFAULT_EIKON?.states.get("idle")??BLANK2,listening:DEFAULT_EIKON?.states.get("listening")??BLANK2,thinking:DEFAULT_EIKON?.states.get("thinking")??BLANK2,speaking:DEFAULT_EIKON?.states.get("speaking")??BLANK2,working:DEFAULT_EIKON?.states.get("working")??BLANK2,error:DEFAULT_EIKON?.states.get("error")??BLANK2};init_perf();var AnimatedAvatar=import_react33.memo(({state="idle",eikon,onHold})=>{let theme=useTheme().theme,[frame,setFrame]=import_react33.useState(0),timer2=import_react33.useRef(null),holdRef=import_react33.useRef(onHold);holdRef.current=onHold;let signal=`state.${state}`,clip=eikon?.resolve(signal)??eikon?.states.get(state)??STATE_FRAMES[state],{frames,fps,loopFrom}=clip,count2=frames.length,animate=usePref("animations")!==!1,targetFps=usePref("targetFps")??30,dt=1000/Math.max(1,Math.min(fps,targetFps));import_react33.useEffect(()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null;if(setFrame(0),!animate||count2<2)return;if(count("avatar:timer:start"),process.env.HERM_TEST_PERF==="1")globalThis.__hermAvatarTimerStarts=(globalThis.__hermAvatarTimerStarts??0)+1;let idx=0,tick2=()=>{if(count("avatar:tick"),idx++,idx>=count2){if(loopFrom>=count2){setFrame(count2-1),holdRef.current?.(state);return}idx=loopFrom}setFrame(idx),timer2.current=setTimeout(tick2,dt)};return timer2.current=setTimeout(tick2,dt),()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null,count("avatar:timer:stop")}},[state,count2,loopFrom,animate,dt]);let end=mark("avatar:render"),lines3=frames[Math.min(frame,count2-1)]??[],result=$jsx("box",{flexDirection:"column",children:lines3.map((line,i)=>$jsx("text",{children:$jsx("span",{fg:theme.hermAvatar,children:line})},i))});return end(),result});var import_react34=__toESM(require_react_production(),1);import{watch}from"fs";var TIMEOUT=500;async function git(cwd,...args){let p=Bun.spawn(["git","-C",cwd,...args],{stdout:"pipe",stderr:"ignore"}),t2=setTimeout(()=>p.kill(),TIMEOUT),out=await new Response(p.stdout).text();return clearTimeout(t2),await p.exited===0?out.trim():null}async function branch(cwd){let b2=await git(cwd,"rev-parse","--abbrev-ref","HEAD");return!b2||b2==="HEAD"?null:b2}async function gitdir(cwd){return git(cwd,"rev-parse","--absolute-git-dir")}function useGitBranch(cwd){let[val,set2]=import_react34.useState(null);return import_react34.useEffect(()=>{if(!cwd){set2(null);return}let dead=!1,w2,read=()=>branch(cwd).then((b2)=>{if(!dead)set2(b2)});return read(),gitdir(cwd).then((dir)=>{if(dead||!dir)return;try{w2=watch(dir,{persistent:!1},(_ev,f)=>{if(f==="HEAD")read()})}catch{}}),()=>{dead=!0,w2?.close()}},[cwd]),val}var rtrunc=(s,max)=>s.length<=max?s:"\u2026"+s.slice(-(max-1));var import_react35=__toESM(require_react_production(),1);var enc,load3=()=>{if(enc!==void 0)return enc;try{enc=require_main()}catch{enc=null}return enc},warmup=()=>{queueMicrotask(load3)},hash=(s)=>{let h2=5381;for(let i=0;i<s.length;i++)h2=(h2<<5)+h2+s.charCodeAt(i)|0;return String(h2)},cache2=new Map;var roughCount=(s)=>Math.ceil(s.length/4);function count2(s){if(!s)return 0;let k2=hash(s),hit=cache2.get(k2);if(hit!==void 0)return hit;let n;try{n=load3()?.countTokens(s)??roughCount(s)}catch{n=roughCount(s)}if(cache2.size>=1024){let first=cache2.keys().next().value;if(first!==void 0)cache2.delete(first)}return cache2.set(k2,n),n}function formatTokens(n){if(!Number.isFinite(n)||n<0)return"0";if(n>=1e6){let m2=n/1e6;return m2===Math.floor(m2)?`${m2}M`:`${m2.toFixed(1)}M`}if(n>=1e4)return`${Math.round(n/1000)}K`;if(n>=1000)return`${(n/1000).toFixed(1)}K`;return String(Math.round(n))}var FILL="\u2588",EMPTY="\u2591",ramp=(ratio)=>{if(ratio>=0.9)return"error";if(ratio>=0.75)return"warning";if(ratio>=0.5)return"primary";return"muted"},centered=(s,width)=>{let pad=Math.max(0,width-s.length),left=Math.ceil(pad/2),right=pad-left;return" ".repeat(left)+s+" ".repeat(right)},formatPct=(ratio)=>{let pct=ratio*100;if(pct<10)return`${pct.toFixed(1)}%`;return`${Math.round(pct)}%`},ContextGauge=import_react35.memo((props)=>{let theme=useTheme().theme,info=props.info,used=props.usage?.context_used??info?.usage?.context_used??info?.context_used,max=props.usage?.context_max??info?.usage?.context_max??info?.context_max;if(typeof max!=="number"||max<=0)return null;if(typeof used!=="number")return null;let ratio=Math.max(0,Math.min(1,used/max)),cells=Math.max(8,props.width-2),filled=Math.round(ratio*cells),bar=FILL.repeat(filled)+EMPTY.repeat(cells-filled),color=(()=>{switch(ramp(ratio)){case"error":return theme.error;case"warning":return theme.warning;case"primary":return theme.primary;default:return theme.textMuted}})(),top=`${formatTokens(used)} / ${formatTokens(max)}`,pct=formatPct(ratio);return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(top,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:color,children:centered(`[${bar}]`,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(pct,props.width)})})})]})});var WIDTH=48,PAD_L=12,INNER=WIDTH-4,trunc=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function hidden2(props){let cwd=props.info?.cwd?.split(/[/\\]/).filter(Boolean).pop();return{profile:props.profile,model:props.info?.model,title:props.title,place:props.branch??cwd,context:typeof props.usage?.context_percent==="number"?`${props.usage.context_percent}%`:void 0}}var Section=import_react36.memo((props)=>{let theme=useTheme().theme,[hover,setHover]=import_react36.useState(!1);return $jsxs("box",{flexDirection:"column",marginBottom:props.open?1:0,children:[$jsx("box",{height:1,onMouseDown:props.onToggle,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:$jsxs("text",{children:[$jsx("span",{fg:hover?theme.text:theme.textMuted,children:props.open?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:props.title})}),props.hint?$jsx("span",{fg:theme.textMuted,children:` ${props.hint}`}):null]})}),props.open?$jsx("box",{flexDirection:"column",children:props.children}):null]})}),Avatar=(props)=>$jsx(AnimatedAvatar,{state:props.state,eikon:props.eikon,onHold:props.onHold},props.id),Row=(props)=>{let theme=useTheme().theme;if(props.block)return $jsxs("box",{flexDirection:"column",minHeight:2,marginBottom:1,children:[$jsx("text",{fg:theme.textMuted,children:` ${props.label}`}),$jsx("text",{fg:theme.text,wrapMode:"word",children:props.value})]});return $jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:` ${props.label.padEnd(PAD_L)}`}),props.strong?$jsx("span",{fg:theme.text,children:$jsx("strong",{children:trunc(props.value,INNER-PAD_L-2)})}):$jsx("span",{fg:theme.text,children:trunc(props.value,INNER-PAD_L-2)})]})})},Sidebar=import_react36.memo((props)=>{let theme=useTheme().theme,state=props.agentState??"idle",info=props.info,[mcpOpen,setMcpOpen]=import_react36.useState(!1),cwd=info?.cwd??process.cwd(),branch2=useGitBranch(cwd);return $jsxs("box",{width:WIDTH,flexDirection:"column",children:[$jsxs("box",{position:"relative",flexDirection:"column",height:24,overflow:"hidden",onMouseDown:props.onAvatar,children:[$jsx(Avatar,{state,eikon:props.eikon,onHold:props.onAvatarHold}),props.cloud?$jsx("box",{position:"absolute",left:0,top:0,children:$jsx(Tail,{run:!!props.pulse})}):null]}),$jsxs("box",{padding:1,flexDirection:"column",flexGrow:1,overflow:"hidden",border:["top","left","right"],borderStyle:"double",borderColor:theme.hermAvatar,children:[$jsx(Row,{label:"Title",value:props.title||"\u2014",strong:!!props.title}),$jsx(Row,{label:"Profile",value:props.profile??"default",strong:!!props.profile&&props.profile!=="default"}),$jsx(Row,{label:"Model",value:info?.model??"\u2014"}),info?.cwd?$jsx(Row,{label:"cwd",value:info.cwd}):null,branch2?$jsx(Row,{label:"Branch",value:rtrunc(branch2,INNER-PAD_L-2)}):null,(info?.mcp_servers?.length??0)>0?(()=>{let srv=info.mcp_servers,ok=srv.filter((s)=>s.connected).length;return $jsx(Section,{title:"MCP",hint:`${ok}/${srv.length} up`,open:mcpOpen,onToggle:()=>setMcpOpen((o)=>!o),children:srv.map((s)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:s.connected?theme.text:theme.textMuted,children:(s.connected?"\u25CF ":"\u25CB ")+trunc(s.name,16).padEnd(16)}),$jsx("span",{fg:theme.textMuted,children:s.connected?` ${s.transport} \xB7 ${s.tools}t`:" failed"})]})},s.name))})})():null,$jsx("box",{flexGrow:1}),$jsx(ContextGauge,{info,usage:props.usage,width:INNER})]})]})});var import_react47=__toESM(require_react_production(),1);var import_react46=__toESM(require_react_production(),1);var import_react45=__toESM(require_react_production(),1);var import_react37=__toESM(require_react_production(),1);var LEFT_BAR={topLeft:"",bottomLeft:"",topRight:"",bottomRight:"",horizontal:"",vertical:"\u2503",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},SIDE_PIPE={topLeft:"\u2502",bottomLeft:"\u2502",vertical:"\u2502",topRight:"\u2502",bottomRight:"\u2502",horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},CORNERS={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:" ",vertical:" ",topT:" ",bottomT:" ",leftT:" ",rightT:" ",cross:" "};import{platform}from"os";var OSC52_CAPABLE=["ghostty","kitty","WezTerm","windows-terminal","vscode"];function detect(){let env2=process.env;if(env2.CURSOR_TRACE_ID)return"cursor";if(env2.TERM==="xterm-ghostty")return"ghostty";if(env2.TERM?.includes("kitty"))return"kitty";if(env2.TERM_PROGRAM)return env2.TERM_PROGRAM;if(env2.TMUX)return"tmux";if(env2.STY)return"screen";if(env2.KITTY_WINDOW_ID)return"kitty";if(env2.WT_SESSION)return"windows-terminal";return env2.TERM??null}var terminal=detect();function supportsOsc52Clipboard(t2=terminal){return OSC52_CAPABLE.includes(t2??"")}function shouldUseNativeClipboard(env2=process.env,t2=terminal){if(env2.SSH_CONNECTION)return!1;if(env2.TMUX||env2.STY)return!0;if(!process.stdout.isTTY)return!0;return!supportsOsc52Clipboard(t2)}function writeOsc52(text3){if(!process.stdout.isTTY)return;let osc52=`\x1B]52;c;${Buffer.from(text3).toString("base64")}\x07`,seq=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${osc52}\x1B\\`:osc52;process.stdout.write(seq)}async function nativeCopy(text3){let os2=platform();if(os2==="darwin"){let proc=Bun.spawn(["pbcopy"],{stdin:"pipe"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}if(os2==="linux"){if(process.env.WAYLAND_DISPLAY)try{let proc=Bun.spawn(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}}}async function copy2(text3){if(writeOsc52(text3),shouldUseNativeClipboard())await nativeCopy(text3).catch(()=>{})}function copied(toast,message="Copied to clipboard"){toast.show({key:"clipboard.copy",variant:"success",message})}function copyText(text3,toast,message="Copied to clipboard"){let p=copy2(text3);if(toast)copied(toast,message);return p}function copySelection(renderer,toast){let text3=renderer.getSelection()?.getSelectedText();if(!text3)return!1;return copyText(text3,toast).catch(()=>{}),renderer.clearSelection(),!0}var CAP2=6,ErrorBlock=import_react37.memo(({text:text3})=>{let theme=useTheme().theme,[open,setOpen]=import_react37.useState(!1),[copied2,setCopied]=import_react37.useState(!1),lines3=text3.trimEnd().split(`
4065
+ `,1)[0];if((first?JSON.parse(first):{}).type==="header"){let e2=parseLaunchStream(text3);return{meta:e2.meta,states:e2.clips,resolve:(signal)=>{try{return e2.clips.get(resolveSignal(e2,signal).clip)}catch{return}}}}let e=parse3(text3);return{meta:e.meta,states:e.clips,resolve:(signal)=>e.clips.get(signal.replace(/^state\./,""))}}function parseEikonFile(path4){return parseEikon(decodeRuntimeFile(path4))}function listEikons(dirs){return dirs.flatMap((dir)=>{let ents;try{ents=readdirSync5(dir,{recursive:!0})}catch{return[]}let paths=ents.map((e)=>join8(dir,e)),streamFiles=paths.filter((path4)=>STREAM_EXT.test(path4)),packageEntrypoints=new Map;for(let manifest3 of paths.filter((path4)=>path4.endsWith("manifest.json"))){let entrypoint=readManifestEntrypoint(manifest3);if(entrypoint){let root2=dirname6(manifest3);packageEntrypoints.set(root2,join8(root2,entrypoint))}}let packageRootFor=(path4)=>{for(let root2 of packageEntrypoints.keys()){let rel=relative3(root2,path4);if(rel&&!rel.startsWith("..")&&!isAbsolute3(rel))return root2}return};return streamFiles.sort((a,b2)=>a.localeCompare(b2)).filter((path4)=>{let packageRoot=packageRootFor(path4);return packageRoot?path4===packageEntrypoints.get(packageRoot):!0}).map((path4)=>({path:path4,meta:peek2(resolve7(path4))})).filter((x2)=>x2.meta!==null)})}var BLANK2={fps:1,loopFrom:1,frames:[[""]]},DEFAULT_EIKON=(()=>{try{return parseEikon(default_default)}catch{return}})(),STATE_FRAMES={idle:DEFAULT_EIKON?.states.get("idle")??BLANK2,listening:DEFAULT_EIKON?.states.get("listening")??BLANK2,thinking:DEFAULT_EIKON?.states.get("thinking")??BLANK2,speaking:DEFAULT_EIKON?.states.get("speaking")??BLANK2,working:DEFAULT_EIKON?.states.get("working")??BLANK2,error:DEFAULT_EIKON?.states.get("error")??BLANK2};init_perf();var maxLines=(frames)=>frames.reduce((n,f)=>Math.max(n,f.length),0),AnimatedAvatar=import_react33.memo(({state="idle",eikon,onHold})=>{let g=globalThis;if(process.env.HERM_TEST_PERF==="1")g.__hermAvatarRenders=(g.__hermAvatarRenders??0)+1;let theme=useTheme().theme,refs2=import_react33.useRef([]),timer2=import_react33.useRef(null),holdRef=import_react33.useRef(onHold);holdRef.current=onHold;let signal=`state.${state}`,clip=eikon?.resolve(signal)??eikon?.states.get(state)??STATE_FRAMES[state],{frames,fps,loopFrom}=clip,count2=frames.length,lines3=maxLines(frames),first=frames[0]??[],animate=usePref("animations")!==!1,targetFps=usePref("targetFps")??30,dt=1000/Math.max(1,Math.min(fps,targetFps));import_react33.useEffect(()=>{let paint=(idx2)=>{let frame=frames[Math.min(idx2,count2-1)]??[];for(let i=0;i<lines3;i++){let node=refs2.current[i];if(node)node.children=[frame[i]??""]}};if(timer2.current)clearTimeout(timer2.current),timer2.current=null;if(paint(0),!animate||count2<2)return;if(count("avatar:timer:start"),process.env.HERM_TEST_PERF==="1")g.__hermAvatarTimerStarts=(g.__hermAvatarTimerStarts??0)+1;let idx=0,tick2=()=>{if(count("avatar:tick"),idx++,idx>=count2){if(loopFrom>=count2){timer2.current=null,paint(count2-1),holdRef.current?.(state);return}idx=loopFrom}paint(idx),timer2.current=setTimeout(tick2,dt)};return timer2.current=setTimeout(tick2,dt),()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null,count("avatar:timer:stop")}},[state,frames,count2,loopFrom,animate,dt,lines3,g]);let end=mark("avatar:render"),result=$jsx("box",{flexDirection:"column",children:Array.from({length:lines3},(_2,i)=>$jsx("text",{children:$jsx("span",{ref:(el)=>{refs2.current[i]=el},fg:theme.hermAvatar,children:first[i]??""})},i))});return end(),result});var import_react34=__toESM(require_react_production(),1);import{watch}from"fs";var TIMEOUT=500;async function git(cwd,...args){let p=Bun.spawn(["git","-C",cwd,...args],{stdout:"pipe",stderr:"ignore"}),t2=setTimeout(()=>p.kill(),TIMEOUT),out=await new Response(p.stdout).text();return clearTimeout(t2),await p.exited===0?out.trim():null}async function branch(cwd){let b2=await git(cwd,"rev-parse","--abbrev-ref","HEAD");return!b2||b2==="HEAD"?null:b2}async function gitdir(cwd){return git(cwd,"rev-parse","--absolute-git-dir")}function useGitBranch(cwd){let[val,set2]=import_react34.useState(null);return import_react34.useEffect(()=>{if(!cwd){set2(null);return}let dead=!1,w2,read=()=>branch(cwd).then((b2)=>{if(!dead)set2(b2)});return read(),gitdir(cwd).then((dir)=>{if(dead||!dir)return;try{w2=watch(dir,{persistent:!1},(_ev,f)=>{if(f==="HEAD")read()})}catch{}}),()=>{dead=!0,w2?.close()}},[cwd]),val}var rtrunc=(s,max)=>s.length<=max?s:"\u2026"+s.slice(-(max-1));var import_react35=__toESM(require_react_production(),1);var enc,load3=()=>{if(enc!==void 0)return enc;try{enc=require_main()}catch{enc=null}return enc},warmup=()=>{queueMicrotask(load3)},hash=(s)=>{let h2=5381;for(let i=0;i<s.length;i++)h2=(h2<<5)+h2+s.charCodeAt(i)|0;return String(h2)},cache2=new Map;var roughCount=(s)=>Math.ceil(s.length/4);function count2(s){if(!s)return 0;let k2=hash(s),hit=cache2.get(k2);if(hit!==void 0)return hit;let n;try{n=load3()?.countTokens(s)??roughCount(s)}catch{n=roughCount(s)}if(cache2.size>=1024){let first=cache2.keys().next().value;if(first!==void 0)cache2.delete(first)}return cache2.set(k2,n),n}function formatTokens(n){if(!Number.isFinite(n)||n<0)return"0";if(n>=1e6){let m2=n/1e6;return m2===Math.floor(m2)?`${m2}M`:`${m2.toFixed(1)}M`}if(n>=1e4)return`${Math.round(n/1000)}K`;if(n>=1000)return`${(n/1000).toFixed(1)}K`;return String(Math.round(n))}var FILL="\u2588",EMPTY="\u2591",ramp=(ratio)=>{if(ratio>=0.9)return"error";if(ratio>=0.75)return"warning";if(ratio>=0.5)return"primary";return"muted"},centered=(s,width)=>{let pad=Math.max(0,width-s.length),left=Math.ceil(pad/2),right=pad-left;return" ".repeat(left)+s+" ".repeat(right)},formatPct=(ratio)=>{let pct=ratio*100;if(pct<10)return`${pct.toFixed(1)}%`;return`${Math.round(pct)}%`},ContextGauge=import_react35.memo((props)=>{let theme=useTheme().theme,info=props.info,used=props.usage?.context_used??info?.usage?.context_used??info?.context_used,max=props.usage?.context_max??info?.usage?.context_max??info?.context_max;if(typeof max!=="number"||max<=0)return null;if(typeof used!=="number")return null;let ratio=Math.max(0,Math.min(1,used/max)),cells=Math.max(8,props.width-2),filled=Math.round(ratio*cells),bar=FILL.repeat(filled)+EMPTY.repeat(cells-filled),color=(()=>{switch(ramp(ratio)){case"error":return theme.error;case"warning":return theme.warning;case"primary":return theme.primary;default:return theme.textMuted}})(),top=`${formatTokens(used)} / ${formatTokens(max)}`,pct=formatPct(ratio);return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(top,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:color,children:centered(`[${bar}]`,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(pct,props.width)})})})]})});var WIDTH=48,PAD_L=12,INNER=WIDTH-4,trunc=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function hidden2(props){let cwd=props.info?.cwd?.split(/[/\\]/).filter(Boolean).pop();return{profile:props.profile,model:props.info?.model,title:props.title,place:props.branch??cwd,context:typeof props.usage?.context_percent==="number"?`${props.usage.context_percent}%`:void 0}}var Section=import_react36.memo((props)=>{let theme=useTheme().theme,[hover,setHover]=import_react36.useState(!1);return $jsxs("box",{flexDirection:"column",marginBottom:props.open?1:0,children:[$jsx("box",{height:1,onMouseDown:props.onToggle,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:$jsxs("text",{children:[$jsx("span",{fg:hover?theme.text:theme.textMuted,children:props.open?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:props.title})}),props.hint?$jsx("span",{fg:theme.textMuted,children:` ${props.hint}`}):null]})}),props.open?$jsx("box",{flexDirection:"column",children:props.children}):null]})}),Avatar=(props)=>$jsx(AnimatedAvatar,{state:props.state,eikon:props.eikon,onHold:props.onHold},props.id),Row=(props)=>{let theme=useTheme().theme;if(props.block)return $jsxs("box",{flexDirection:"column",minHeight:2,marginBottom:1,children:[$jsx("text",{fg:theme.textMuted,children:` ${props.label}`}),$jsx("text",{fg:theme.text,wrapMode:"word",children:props.value})]});return $jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:` ${props.label.padEnd(PAD_L)}`}),props.strong?$jsx("span",{fg:theme.text,children:$jsx("strong",{children:trunc(props.value,INNER-PAD_L-2)})}):$jsx("span",{fg:theme.text,children:trunc(props.value,INNER-PAD_L-2)})]})})},Sidebar=import_react36.memo((props)=>{let theme=useTheme().theme,state=props.agentState??"idle",info=props.info,[mcpOpen,setMcpOpen]=import_react36.useState(!1),cwd=info?.cwd??process.cwd(),branch2=useGitBranch(cwd);return $jsxs("box",{width:WIDTH,flexDirection:"column",children:[$jsxs("box",{position:"relative",flexDirection:"column",height:24,overflow:"hidden",onMouseDown:props.onAvatar,children:[$jsx(Avatar,{state,eikon:props.eikon,onHold:props.onAvatarHold}),props.cloud?$jsx("box",{position:"absolute",left:0,top:0,children:$jsx(Tail,{run:!!props.pulse})}):null]}),$jsxs("box",{padding:1,flexDirection:"column",flexGrow:1,overflow:"hidden",border:["top","left","right"],borderStyle:"double",borderColor:theme.hermAvatar,children:[$jsx(Row,{label:"Title",value:props.title||"\u2014",strong:!!props.title}),$jsx(Row,{label:"Profile",value:props.profile??"default",strong:!!props.profile&&props.profile!=="default"}),$jsx(Row,{label:"Model",value:info?.model??"\u2014"}),info?.cwd?$jsx(Row,{label:"cwd",value:info.cwd}):null,branch2?$jsx(Row,{label:"Branch",value:rtrunc(branch2,INNER-PAD_L-2)}):null,(info?.mcp_servers?.length??0)>0?(()=>{let srv=info.mcp_servers,ok=srv.filter((s)=>s.connected).length;return $jsx(Section,{title:"MCP",hint:`${ok}/${srv.length} up`,open:mcpOpen,onToggle:()=>setMcpOpen((o)=>!o),children:srv.map((s)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:s.connected?theme.text:theme.textMuted,children:(s.connected?"\u25CF ":"\u25CB ")+trunc(s.name,16).padEnd(16)}),$jsx("span",{fg:theme.textMuted,children:s.connected?` ${s.transport} \xB7 ${s.tools}t`:" failed"})]})},s.name))})})():null,$jsx("box",{flexGrow:1}),$jsx(ContextGauge,{info,usage:props.usage,width:INNER})]})]})});var import_react47=__toESM(require_react_production(),1);var import_react46=__toESM(require_react_production(),1);var import_react45=__toESM(require_react_production(),1);var import_react37=__toESM(require_react_production(),1);var LEFT_BAR={topLeft:"",bottomLeft:"",topRight:"",bottomRight:"",horizontal:"",vertical:"\u2503",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},SIDE_PIPE={topLeft:"\u2502",bottomLeft:"\u2502",vertical:"\u2502",topRight:"\u2502",bottomRight:"\u2502",horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},CORNERS={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:" ",vertical:" ",topT:" ",bottomT:" ",leftT:" ",rightT:" ",cross:" "};import{platform}from"os";var OSC52_CAPABLE=["ghostty","kitty","WezTerm","windows-terminal","vscode"];function detect(){let env2=process.env;if(env2.CURSOR_TRACE_ID)return"cursor";if(env2.TERM==="xterm-ghostty")return"ghostty";if(env2.TERM?.includes("kitty"))return"kitty";if(env2.TERM_PROGRAM)return env2.TERM_PROGRAM;if(env2.TMUX)return"tmux";if(env2.STY)return"screen";if(env2.KITTY_WINDOW_ID)return"kitty";if(env2.WT_SESSION)return"windows-terminal";return env2.TERM??null}var terminal=detect();function supportsOsc52Clipboard(t2=terminal){return OSC52_CAPABLE.includes(t2??"")}function shouldUseNativeClipboard(env2=process.env,t2=terminal){if(env2.SSH_CONNECTION)return!1;if(env2.TMUX||env2.STY)return!0;if(!process.stdout.isTTY)return!0;return!supportsOsc52Clipboard(t2)}function writeOsc52(text3){if(!process.stdout.isTTY)return;let osc52=`\x1B]52;c;${Buffer.from(text3).toString("base64")}\x07`,seq=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${osc52}\x1B\\`:osc52;process.stdout.write(seq)}async function nativeCopy(text3){let os2=platform();if(os2==="darwin"){let proc=Bun.spawn(["pbcopy"],{stdin:"pipe"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}if(os2==="linux"){if(process.env.WAYLAND_DISPLAY)try{let proc=Bun.spawn(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}}}async function copy2(text3){if(writeOsc52(text3),shouldUseNativeClipboard())await nativeCopy(text3).catch(()=>{})}function copied(toast,message="Copied to clipboard"){toast.show({key:"clipboard.copy",variant:"success",message})}function copyText(text3,toast,message="Copied to clipboard"){let p=copy2(text3);if(toast)copied(toast,message);return p}function copySelection(renderer,toast){let text3=renderer.getSelection()?.getSelectedText();if(!text3)return!1;return copyText(text3,toast).catch(()=>{}),renderer.clearSelection(),!0}var CAP2=6,ErrorBlock=import_react37.memo(({text:text3})=>{let theme=useTheme().theme,[open,setOpen]=import_react37.useState(!1),[copied2,setCopied]=import_react37.useState(!1),lines3=text3.trimEnd().split(`
4066
4066
  `),head=lines3[0]||"Error",body=lines3.slice(1),over=body.length>CAP2,shown=open||!over?body:body.slice(0,CAP2);import_react37.useEffect(()=>{if(!copied2)return;let t2=setTimeout(()=>setCopied(!1),1500);return()=>clearTimeout(t2)},[copied2]);let doCopy=()=>{copy2(text3),setCopied(!0)};return $jsxs("box",{border:["left"],borderColor:theme.error,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingTop:1,paddingBottom:1,marginTop:1,flexDirection:"column",gap:1,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("box",{flexGrow:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:"\u2717 "}),$jsx("span",{fg:theme.text,children:head})]})}),$jsx("box",{onMouseDown:doCopy,paddingX:1,children:$jsx("text",{fg:copied2?theme.success:theme.textMuted,children:copied2?"copied":"copy"})})]}),shown.length?$jsxs("box",{flexDirection:"column",onMouseDown:over?()=>setOpen((o)=>!o):void 0,children:[shown.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:l||" "})},i)),over?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:open?"Click to collapse":`\u2026 ${body.length-CAP2} more \u2014 click to expand`})}):null]}):null]})});var import_react38=__toESM(require_react_production(),1);import{spawn}from"child_process";import{platform as platform3}from"os";import process8 from"process";import path5 from"path";import{fileURLToPath as fileURLToPath3}from"url";import childProcess3 from"child_process";import fs6,{constants as fsConstants2}from"fs/promises";import{promisify as promisify2}from"util";import childProcess2 from"child_process";import fs5,{constants as fsConstants}from"fs/promises";import process2 from"process";import os2 from"os";import fs4 from"fs";import fs3 from"fs";import fs2 from"fs";var isDockerCached;function hasDockerEnv(){try{return fs2.statSync("/.dockerenv"),!0}catch{return!1}}function hasDockerCGroup(){try{return fs2.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function isDocker(){if(isDockerCached===void 0)isDockerCached=hasDockerEnv()||hasDockerCGroup();return isDockerCached}var cachedResult,hasContainerEnv=()=>{try{return fs3.statSync("/run/.containerenv"),!0}catch{return!1}};function isInsideContainer(){if(cachedResult===void 0)cachedResult=hasContainerEnv()||isDocker();return cachedResult}var isWsl=()=>{if(process2.platform!=="linux")return!1;if(os2.release().toLowerCase().includes("microsoft")){if(isInsideContainer())return!1;return!0}try{if(fs4.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!isInsideContainer()}catch{}if(fs4.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||fs4.existsSync("/run/WSL"))return!isInsideContainer();return!1},is_wsl_default=process2.env.__IS_WSL_TEST__?isWsl:isWsl();import process3 from"process";import{Buffer as Buffer4}from"buffer";import{promisify}from"util";import childProcess from"child_process";var execFile=promisify(childProcess.execFile),powerShellPath=()=>`${process3.env.SYSTEMROOT||process3.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var executePowerShell=async(command,options={})=>{let{powerShellPath:psPath,...execFileOptions}=options,encodedCommand=executePowerShell.encodeCommand(command);return execFile(psPath??powerShellPath(),[...executePowerShell.argumentsPrefix,encodedCommand],{encoding:"utf8",...execFileOptions})};executePowerShell.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];executePowerShell.encodeCommand=(command)=>Buffer4.from(command,"utf16le").toString("base64");executePowerShell.escapeArgument=(value)=>`'${String(value).replaceAll("'","''")}'`;function parseMountPointFromConfig(content){for(let line of content.split(`
4067
4067
  `)){if(/^\s*#/.test(line))continue;let match2=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);if(!match2)continue;return match2.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var execFile2=promisify2(childProcess2.execFile),wslDrivesMountPoint=(()=>{let mountPoint;return async function(){if(mountPoint)return mountPoint;let configFilePath="/etc/wsl.conf",isConfigFileExists=!1;try{await fs5.access(configFilePath,fsConstants.F_OK),isConfigFileExists=!0}catch{}if(!isConfigFileExists)return"/mnt/";let configContent=await fs5.readFile(configFilePath,{encoding:"utf8"}),parsedMountPoint=parseMountPointFromConfig(configContent);if(parsedMountPoint===void 0)return"/mnt/";return mountPoint=parsedMountPoint,mountPoint=mountPoint.endsWith("/")?mountPoint:`${mountPoint}/`,mountPoint}})(),powerShellPathFromWsl=async()=>{return`${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},powerShellPath2=is_wsl_default?powerShellPathFromWsl:powerShellPath,canAccessPowerShellPromise,canAccessPowerShell=async()=>{return canAccessPowerShellPromise??=(async()=>{try{let psPath=await powerShellPath2();return await fs5.access(psPath,fsConstants.X_OK),!0}catch{return!1}})(),canAccessPowerShellPromise},wslDefaultBrowser=async()=>{let psPath=await powerShellPath2(),command=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout}=await executePowerShell(command,{powerShellPath:psPath});return stdout.trim()},convertWslPathToWindows=async(path4)=>{if(/^[a-z]+:\/\//i.test(path4))return path4;try{let{stdout}=await execFile2("wslpath",["-aw",path4],{encoding:"utf8"});return stdout.trim()}catch{return path4}};function defineLazyProperty(object,propertyName,valueGetter){let define=(value)=>Object.defineProperty(object,propertyName,{value,enumerable:!0,writable:!0});return Object.defineProperty(object,propertyName,{configurable:!0,enumerable:!0,get(){let result=valueGetter();return define(result),result},set(value){define(value)}}),object}import{promisify as promisify6}from"util";import process6 from"process";import{execFile as execFile6}from"child_process";import{promisify as promisify3}from"util";import process4 from"process";import{execFile as execFile3}from"child_process";var execFileAsync=promisify3(execFile3);async function defaultBrowserId(){if(process4.platform!=="darwin")throw Error("macOS only");let{stdout}=await execFileAsync("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),browserId=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id??"com.apple.Safari";if(browserId==="com.apple.safari")return"com.apple.Safari";return browserId}import process5 from"process";import{promisify as promisify4}from"util";import{execFile as execFile4,execFileSync}from"child_process";var execFileAsync2=promisify4(execFile4);async function runAppleScript(script,{humanReadableOutput=!0,signal}={}){if(process5.platform!=="darwin")throw Error("macOS only");let outputArguments=humanReadableOutput?[]:["-ss"],execOptions={};if(signal)execOptions.signal=signal;let{stdout}=await execFileAsync2("osascript",["-e",script,outputArguments],execOptions);return stdout.trim()}async function bundleName(bundleId){return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
4068
4068
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as promisify5}from"util";import{execFile as execFile5}from"child_process";var execFileAsync3=promisify5(execFile5),windowsBrowserProgIds={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},_windowsBrowserProgIdMap=new Map(Object.entries(windowsBrowserProgIds));class UnknownBrowserError extends Error{}async function defaultBrowser(_execFileAsync=execFileAsync3){let{stdout}=await _execFileAsync("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),match2=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);if(!match2)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);let{id}=match2.groups,dotIndex=id.lastIndexOf("."),hyphenIndex=id.lastIndexOf("-"),baseIdByDot=dotIndex===-1?void 0:id.slice(0,dotIndex),baseIdByHyphen=hyphenIndex===-1?void 0:id.slice(0,hyphenIndex);return windowsBrowserProgIds[id]??windowsBrowserProgIds[baseIdByDot]??windowsBrowserProgIds[baseIdByHyphen]??{name:id,id}}var execFileAsync4=promisify6(execFile6),titleize=(string)=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(x2)=>x2.toUpperCase());async function defaultBrowser2(){if(process6.platform==="darwin"){let id=await defaultBrowserId();return{name:await bundleName(id),id}}if(process6.platform==="linux"){let{stdout}=await execFileAsync4("xdg-mime",["query","default","x-scheme-handler/http"]),id=stdout.trim();return{name:titleize(id.replace(/.desktop$/,"").replace("-"," ")),id}}if(process6.platform==="win32")return defaultBrowser();throw Error("Only macOS, Linux, and Windows are supported")}import process7 from"process";var isInSsh=Boolean(process7.env.SSH_CONNECTION||process7.env.SSH_CLIENT||process7.env.SSH_TTY),is_in_ssh_default=isInSsh;var fallbackAttemptSymbol=Symbol("fallbackAttempt"),__dirname2=import.meta.url?path5.dirname(fileURLToPath3(import.meta.url)):"",localXdgOpenPath=path5.join(__dirname2,"xdg-open"),{platform:platform2,arch}=process8,tryEachApp=async(apps,opener)=>{if(apps.length===0)return;let errors=[];for(let app of apps)try{return await opener(app)}catch(error){errors.push(error)}throw AggregateError(errors,"Failed to open in all supported apps")},baseOpen=async(options)=>{options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options};let isFallbackAttempt=options[fallbackAttemptSymbol]===!0;if(delete options[fallbackAttemptSymbol],Array.isArray(options.app))return tryEachApp(options.app,(singleApp)=>baseOpen({...options,app:singleApp,[fallbackAttemptSymbol]:!0}));let{name:app,arguments:appArguments=[]}=options.app??{};if(appArguments=[...appArguments],Array.isArray(app))return tryEachApp(app,(appName)=>baseOpen({...options,app:{name:appName,arguments:appArguments},[fallbackAttemptSymbol]:!0}));if(app==="browser"||app==="browserPrivate"){let ids={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},flags={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},browser;if(is_wsl_default){let progId=await wslDefaultBrowser();browser=_windowsBrowserProgIdMap.get(progId)??{}}else browser=await defaultBrowser2();if(browser.id in ids){let browserName=ids[browser.id.toLowerCase()];if(app==="browserPrivate"){if(browserName==="safari")throw Error("Safari doesn't support opening in private mode via command line");appArguments.push(flags[browserName])}return baseOpen({...options,app:{name:apps[browserName],arguments:appArguments}})}throw Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={},shouldUseWindowsInWsl=!1;if(is_wsl_default&&!isInsideContainer()&&!is_in_ssh_default&&!app)shouldUseWindowsInWsl=await canAccessPowerShell();if(platform2==="darwin"){if(command="open",options.wait)cliArguments.push("--wait-apps");if(options.background)cliArguments.push("--background");if(options.newInstance)cliArguments.push("--new");if(app)cliArguments.push("-a",app)}else if(platform2==="win32"||shouldUseWindowsInWsl){if(command=await powerShellPath2(),cliArguments.push(...executePowerShell.argumentsPrefix),!is_wsl_default)childProcessOptions.windowsVerbatimArguments=!0;if(is_wsl_default&&options.target)options.target=await convertWslPathToWindows(options.target);let encodedArguments=["$ProgressPreference = 'SilentlyContinue';","Start"];if(options.wait)encodedArguments.push("-Wait");if(app){if(encodedArguments.push(executePowerShell.escapeArgument(app)),options.target)appArguments.push(options.target)}else if(options.target)encodedArguments.push(executePowerShell.escapeArgument(options.target));if(appArguments.length>0)appArguments=appArguments.map((argument)=>executePowerShell.escapeArgument(argument)),encodedArguments.push("-ArgumentList",appArguments.join(","));if(options.target=executePowerShell.encodeCommand(encodedArguments.join(" ")),!options.wait)childProcessOptions.stdio="ignore"}else{if(app)command=app;else{let isBundled=!__dirname2||__dirname2==="/",exeLocalXdgOpen=!1;try{await fs6.access(localXdgOpenPath,fsConstants2.X_OK),exeLocalXdgOpen=!0}catch{}command=process8.versions.electron??(platform2==="android"||isBundled||!exeLocalXdgOpen)?"xdg-open":localXdgOpenPath}if(appArguments.length>0)cliArguments.push(...appArguments);if(!options.wait)childProcessOptions.stdio="ignore",childProcessOptions.detached=!0}if(platform2==="darwin"&&appArguments.length>0)cliArguments.push("--args",...appArguments);if(options.target)cliArguments.push(options.target);let subprocess=childProcess3.spawn(command,cliArguments,childProcessOptions);if(options.wait)return new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("close",(exitCode)=>{if(!options.allowNonzeroExitCode&&exitCode!==0){reject(Error(`Exited with code ${exitCode}`));return}resolve4(subprocess)})});if(isFallbackAttempt)return new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("spawn",()=>{subprocess.once("close",(exitCode)=>{if(subprocess.off("error",reject),exitCode!==0){reject(Error(`Exited with code ${exitCode}`));return}subprocess.unref(),resolve4(subprocess)})})});return subprocess.unref(),new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("spawn",()=>{subprocess.off("error",reject),resolve4(subprocess)})})},open=(target,options)=>{if(typeof target!=="string")throw TypeError("Expected a `target`");return baseOpen({...options,target})};function detectArchBinary(binary){if(typeof binary==="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw Error(`${arch} is not supported`);return archBinary}function detectPlatformBinary({[platform2]:platformBinary},{wsl}={}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw Error(`${platform2} is not supported`);return detectArchBinary(platformBinary)}var apps={browser:"browser",browserPrivate:"browserPrivate"};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"brave",()=>detectPlatformBinary({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));defineLazyProperty(apps,"safari",()=>detectPlatformBinary({darwin:"Safari"}));var open_default=open;function openFile(path4){open_default(path4).catch(()=>{})}function openUrl(raw,deps={}){let url2=parseSafeUrl(raw);if(!url2)return!1;let spawnFn=deps.spawn??spawn,id=deps.platform?.()??platform3(),cmd=openCommand(id);if(!cmd)return!1;let child;try{child=spawnFn(cmd.command,[...cmd.args,url2.toString()],{detached:!0,stdio:"ignore"})}catch{return!1}return child.once("error",()=>{}),child.unref(),!0}function parseSafeUrl(value){if(!value||typeof value!=="string")return null;let url2;try{url2=new URL(value)}catch{return null}if(url2.protocol!=="http:"&&url2.protocol!=="https:")return null;if(!url2.hostname.trim())return null;return url2}function openCommand(id){if(id==="darwin")return{command:"open",args:[]};if(id==="win32")return{command:"explorer.exe",args:[]};if(new Set(["linux","freebsd","openbsd","netbsd","dragonfly"]).has(id))return{command:"xdg-open",args:[]};return null}import{existsSync as existsSync11}from"fs";var IMAGE_EXT=new Set(["png","jpg","jpeg","gif","webp","svg","bmp"]),URL_RE=/^[a-z][a-z0-9+.-]*:\/\//i;function image(path4){return IMAGE_EXT.has((path4.split(/[?#]/)[0].split(".").pop()??"").toLowerCase())}function remote(path4){return URL_RE.test(path4)}function previewStrategy(opts){if(remote(opts.path))return{kind:"chip",reason:"remote"};if(!image(opts.path))return{kind:"chip",reason:"unsupported"};if(!opts.exists)return{kind:"chip",reason:"missing"};if(opts.chafa)return{kind:"chafa",reason:"chafa-supported"};return{kind:"chip",reason:"no-renderer"}}function strategy(path4,chafa){return previewStrategy({path:path4,chafa,exists:remote(path4)?!1:existsSync11(path4.startsWith("~")?(process.env.HOME??"")+path4.slice(1):path4)})}var MEDIA_LINE_RE=/^\s*[`"']?MEDIA:\s*(\S+?)[`"']?\s*$/,AUDIO_EXT=new Set(["mp3","wav","ogg","m4a","flac","opus"]),VIDEO_EXT=new Set(["mp4","webm","mov","mkv"]),IMG_RE=/!\[[^\]\n]*\]\(([^)\s]+)(?:\s+[^)]*)?\)/g;function classify(path4){if(/^https?:\/\//i.test(path4))return"url";if(image(path4))return"img";let ext=path4.split(".").pop()?.toLowerCase()??"";if(AUDIO_EXT.has(ext))return"audio";if(VIDEO_EXT.has(ext))return"video";return"file"}var basename5=(p)=>p.split(/[/\\]/).pop()||p;function splitContent(text3){if(!text3.includes("MEDIA:")&&!text3.includes("```")&&!text3.includes("~~~")&&!text3.includes("!["))return[{md:text3}];let out=[],buf=[],fence=null,flush=()=>{if(buf.length)out.push({md:buf.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herm-tui",
3
- "version": "1.11.0-dev.1",
3
+ "version": "1.11.0-dev.2",
4
4
  "description": "A modern TUI for Hermes Agent",
5
5
  "license": "MIT",
6
6
  "repository": {