herm-tui 1.3.0-dev.4 → 1.3.0-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/db.worker.js +10 -2
- package/index.js +15 -7
- package/package.json +1 -1
package/db.worker.js
CHANGED
|
@@ -3,7 +3,9 @@ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defP
|
|
|
3
3
|
\x1B[1m\u2550\u2550\u2550 PERF REPORT \u2550\u2550\u2550\x1B[0m
|
|
4
4
|
`];if(snapshots.length>0){lines.push("\x1B[1mMemory Snapshots:\x1B[0m");for(let s of snapshots)lines.push(` ${s.label}: RSS=${mb(s.rss)}MB heap=${mb(s.heap)}MB ext=${mb(s.external)}MB`);let first=snapshots[0],last=snapshots[snapshots.length-1],drift=last.rss-first.rss;lines.push(` \u0394 RSS: ${drift>0?"+":""}${mb(drift)}MB (${first.label} \u2192 ${last.label})`),lines.push("")}if(timings.size>0){lines.push("\x1B[1mTimings:\x1B[0m");let sorted=[...timings.entries()].sort((a,b)=>b[1].total-a[1].total);for(let[label,t]of sorted){let avg=t.total/t.count;lines.push(` ${label}: ${t.count}\xD7 avg=${avg.toFixed(2)}ms min=${t.min.toFixed(2)}ms max=${t.max.toFixed(2)}ms total=${t.total.toFixed(0)}ms`)}lines.push("")}if(renders.size>0){lines.push("\x1B[1mReact Renders:\x1B[0m");let sorted=[...renders.entries()].sort((a,b)=>b[1].count-a[1].count);for(let[id,r]of sorted){let avg=r.total/r.count;lines.push(` <${id}>: ${r.count}\xD7 avg=${avg.toFixed(2)}ms max=${r.max.toFixed(2)}ms total=${r.total.toFixed(0)}ms`)}lines.push("")}if(counters.size>0){lines.push("\x1B[1mCounters:\x1B[0m");let sorted=[...counters.entries()].sort((a,b)=>b[1]-a[1]);for(let[label,n]of sorted)lines.push(` ${label}: ${n}`);lines.push("")}log(lines.join(`
|
|
5
5
|
`))},data=()=>{if(!enabled)return null;let m=process.memoryUsage();return{boot:Object.fromEntries(stages.map(([l,ms])=>[l,+ms.toFixed(1)])),memory:{rss:Math.round(m.rss/1024/1024),heap:Math.round(m.heapUsed/1024/1024),heapTotal:Math.round(m.heapTotal/1024/1024),external:Math.round(m.external/1024/1024)},snapshots:snapshots.map((s)=>({label:s.label,rss:Math.round(s.rss/1024/1024),heap:Math.round(s.heap/1024/1024),external:Math.round(s.external/1024/1024)})),timings:Object.fromEntries([...timings.entries()].sort((a,b)=>b[1].total-a[1].total).map(([k,v])=>[k,{count:v.count,avg:+(v.total/v.count).toFixed(2),min:+v.min.toFixed(2),max:+v.max.toFixed(2),total:Math.round(v.total)}])),renders:Object.fromEntries([...renders.entries()].sort((a,b)=>b[1].count-a[1].count).map(([k,v])=>[k,{count:v.count,avg:+(v.total/v.count).toFixed(2),max:+v.max.toFixed(2),total:Math.round(v.total)}])),counters:Object.fromEntries([...counters.entries()].sort((a,b)=>b[1]-a[1]))}},log=(msg)=>process.stderr.write(msg+`
|
|
6
|
-
`);var init_perf=__esm(()=>{level=process.env.PERF??"",enabled=level==="1"||level==="verbose",verbose=level==="verbose",timings=new Map,mark=enabled?(label)=>{let start=Bun.nanoseconds();return()=>{let ms=(Bun.nanoseconds()-start)/1e6,t=timings.get(label);if(t){if(t.count++,t.total+=ms,ms<t.min)t.min=ms;if(ms>t.max)t.max=ms;t.last=ms}else timings.set(label,{count:1,total:ms,min:ms,max:ms,last:ms});if(verbose)log(`\u23F1 ${label}: ${ms.toFixed(2)}ms`);return ms}}:(_)=>noop,stages=[],counters=new Map,count=enabled?(label,n=1)=>{counters.set(label,(counters.get(label)??0)+n)}:(_label,_n)=>{},snapshots=[],mem=enabled?(label)=>{let m=process.memoryUsage();snapshots.push({label,rss:m.rss,heap:m.heapUsed,external:m.external,ts:Date.now()}),log(`\uD83D\uDCCA [${label}] RSS=${mb(m.rss)}MB heap=${mb(m.heapUsed)}MB ext=${mb(m.external)}MB`)}:(_)=>{},monitor=enabled?(ms=1e4)=>{let id=setInterval(()=>{let m=process.memoryUsage(),gc=Bun.gc(!1);log(`\x1B[90m[mem] RSS=${mb(m.rss)}MB heap=${mb(m.heapUsed)}/${mb(m.heapTotal)}MB ext=${mb(m.external)}MB gcRuns=${gc?.eden_collections??"?"}/${gc?.full_collections??"?"}\x1B[0m`)},ms);return()=>clearInterval(id)}:(_ms)=>noop,renders=new Map,onRender=enabled?(id,phase,actual)=>{let r=renders.get(id);if(r){if(r.count++,r.total+=actual,actual>r.max)r.max=actual;r.last=actual}else renders.set(id,{count:1,total:actual,max:actual,last:actual});if(verbose&&actual>1)log(`\uD83D\uDD04 [${id}] ${phase}: ${actual.toFixed(2)}ms`)}:(_id,_phase,_actual)=>{};if(enabled)process.on("exit",report),process.on("SIGINT",()=>{report(),process.exit(0)})});import{Database}from"bun:sqlite";import{homedir}from"os";function
|
|
6
|
+
`);var init_perf=__esm(()=>{level=process.env.PERF??"",enabled=level==="1"||level==="verbose",verbose=level==="verbose",timings=new Map,mark=enabled?(label)=>{let start=Bun.nanoseconds();return()=>{let ms=(Bun.nanoseconds()-start)/1e6,t=timings.get(label);if(t){if(t.count++,t.total+=ms,ms<t.min)t.min=ms;if(ms>t.max)t.max=ms;t.last=ms}else timings.set(label,{count:1,total:ms,min:ms,max:ms,last:ms});if(verbose)log(`\u23F1 ${label}: ${ms.toFixed(2)}ms`);return ms}}:(_)=>noop,stages=[],counters=new Map,count=enabled?(label,n=1)=>{counters.set(label,(counters.get(label)??0)+n)}:(_label,_n)=>{},snapshots=[],mem=enabled?(label)=>{let m=process.memoryUsage();snapshots.push({label,rss:m.rss,heap:m.heapUsed,external:m.external,ts:Date.now()}),log(`\uD83D\uDCCA [${label}] RSS=${mb(m.rss)}MB heap=${mb(m.heapUsed)}MB ext=${mb(m.external)}MB`)}:(_)=>{},monitor=enabled?(ms=1e4)=>{let id=setInterval(()=>{let m=process.memoryUsage(),gc=Bun.gc(!1);log(`\x1B[90m[mem] RSS=${mb(m.rss)}MB heap=${mb(m.heapUsed)}/${mb(m.heapTotal)}MB ext=${mb(m.external)}MB gcRuns=${gc?.eden_collections??"?"}/${gc?.full_collections??"?"}\x1B[0m`)},ms);return()=>clearInterval(id)}:(_ms)=>noop,renders=new Map,onRender=enabled?(id,phase,actual)=>{let r=renders.get(id);if(r){if(r.count++,r.total+=actual,actual>r.max)r.max=actual;r.last=actual}else renders.set(id,{count:1,total:actual,max:actual,last:actual});if(verbose&&actual>1)log(`\uD83D\uDD04 [${id}] ${phase}: ${actual.toFixed(2)}ms`)}:(_id,_phase,_actual)=>{};if(enabled)process.on("exit",report),process.on("SIGINT",()=>{report(),process.exit(0)})});import{Database}from"bun:sqlite";import{homedir}from"os";function walkUp(sid){let step=q(`SELECT p.id FROM sessions c
|
|
7
|
+
JOIN sessions p ON p.id = c.parent_session_id
|
|
8
|
+
WHERE c.id = ? AND ${CONT("c")}`),cur=sid;for(let i=0;i<100;i++){let prev=step?.get(cur);if(!prev)return cur;cur=prev.id}return cur}function roots(limit=30){let end=mark("io:sessions.roots");try{return(q(`SELECT ${COLS} FROM sessions s
|
|
7
9
|
WHERE s.parent_session_id IS NULL
|
|
8
10
|
OR EXISTS (SELECT 1 FROM sessions p
|
|
9
11
|
WHERE p.id = s.parent_session_id
|
|
@@ -46,7 +48,13 @@ var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defP
|
|
|
46
48
|
(SELECT MAX(timestamp) FROM messages WHERE session_id = s.id) AS last_active,
|
|
47
49
|
(SELECT COUNT(*) FROM sessions c
|
|
48
50
|
WHERE c.parent_session_id = s.id
|
|
49
|
-
AND (s.ended_at IS NULL OR c.started_at < s.ended_at)) AS subagent_count`,toRow=(r,lineage=null)=>({source:SRC,id:r.id,sessionSource:r.source,model:r.model,started_at:r.started_at,ended_at:r.ended_at,end_reason:r.end_reason,message_count:r.message_count,tool_call_count:r.tool_call_count,input_tokens:r.input_tokens,output_tokens:r.output_tokens,cache_read_tokens:r.cache_read_tokens,cache_write_tokens:r.cache_write_tokens,reasoning_tokens:r.reasoning_tokens,estimated_cost_usd:r.estimated_cost_usd,title:r.title,lastMessage:r.lastMessage,last_active:r.last_active,parent_session_id:r.parent_session_id,subagent_count:r.subagent_count,lineage_root_id:lineage}),one=(id)=>q(`SELECT ${COLS} FROM sessions s WHERE s.id = ?`)?.get(id)??null,byId=(id)=>{let r=one(id);return r?toRow(r):null},lastReal=()=>
|
|
51
|
+
AND (s.ended_at IS NULL OR c.started_at < s.ended_at)) AS subagent_count`,toRow=(r,lineage=null)=>({source:SRC,id:r.id,sessionSource:r.source,model:r.model,started_at:r.started_at,ended_at:r.ended_at,end_reason:r.end_reason,message_count:r.message_count,tool_call_count:r.tool_call_count,input_tokens:r.input_tokens,output_tokens:r.output_tokens,cache_read_tokens:r.cache_read_tokens,cache_write_tokens:r.cache_write_tokens,reasoning_tokens:r.reasoning_tokens,estimated_cost_usd:r.estimated_cost_usd,title:r.title,lastMessage:r.lastMessage,last_active:r.last_active,parent_session_id:r.parent_session_id,subagent_count:r.subagent_count,lineage_root_id:lineage}),one=(id)=>q(`SELECT ${COLS} FROM sessions s WHERE s.id = ?`)?.get(id)??null,byId=(id)=>{let r=one(id);return r?toRow(r):null},lastReal=()=>{let hit=q(`
|
|
52
|
+
SELECT s.id FROM sessions s
|
|
53
|
+
LEFT JOIN sessions p ON p.id = s.parent_session_id
|
|
54
|
+
WHERE s.source IN ('tui', 'cli') AND s.message_count > 0
|
|
55
|
+
AND (s.parent_session_id IS NULL OR ${CONT("s")})
|
|
56
|
+
ORDER BY s.started_at DESC LIMIT 1
|
|
57
|
+
`)?.get();if(!hit)return;let row=byId(chainTip(hit.id));return row&&row.message_count>0?row:void 0},chainTip=(sid)=>tip(walkUp(sid)),systemPrompt=()=>q(`SELECT id, system_prompt AS text FROM sessions
|
|
50
58
|
WHERE system_prompt IS NOT NULL AND length(system_prompt) > 1000
|
|
51
59
|
ORDER BY started_at DESC LIMIT 1`)?.get()??null,fts=(s)=>s.trim().split(/\s+/).filter(Boolean).map((w)=>/^\w+$/.test(w)?`${w}*`:`"${w.replace(/"/g,'""')}"`).join(" ");var init_sessions_db=__esm(()=>{init_perf();HERMES=process.env.HERMES_HOME||`${process.env.HOME||homedir()}/.hermes`,SRC={file:`${HERMES}/state.db`,relative:"state.db",label:"state.db"},conn={path:SRC.file,ro:null},stmts=new Map});function analytics(days,opts){let since=Math.floor(Date.now()/1000)-days*86400,db=stateDb();if(!db)return ZERO;let q2=db.query.bind(db),tot=q2(`SELECT COUNT(*) n,
|
|
52
60
|
COALESCE(SUM(message_count),0) msgs,
|
package/index.js
CHANGED
|
@@ -3411,7 +3411,9 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
3411
3411
|
`)+1;while(nl!==0)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
|
|
3412
3412
|
`,nl)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(map){let it=map.items[map.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,it.value){let end="end"in it.value?it.value.end:void 0;if((Array.isArray(end)?end[end.length-1]:void 0)?.type==="comment")end?.push(this.sourceToken);else map.items.push({start:[this.sourceToken]})}else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"space":case"comment":if(it.value)map.items.push({start:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else{if(this.atIndentedComment(it.start,map.indent)){let end=map.items[map.items.length-2]?.value?.end;if(Array.isArray(end)){Array.prototype.push.apply(end,it.start),end.push(this.sourceToken),map.items.pop();return}}it.start.push(this.sourceToken)}return}if(this.indent>=map.indent){let atMapIndent=!this.onKeyLine&&this.indent===map.indent,atNextItem=atMapIndent&&(it.sep||it.explicitKey)&&this.type!=="seq-item-ind",start2=[];if(atNextItem&&it.sep&&!it.value){let nl=[];for(let i=0;i<it.sep.length;++i){let st=it.sep[i];switch(st.type){case"newline":nl.push(i);break;case"space":break;case"comment":if(st.indent>map.indent)nl.length=0;break;default:nl.length=0}}if(nl.length>=2)start2=it.sep.splice(nl[1])}switch(this.type){case"anchor":case"tag":if(atNextItem||it.value)start2.push(this.sourceToken),map.items.push({start:start2}),this.onKeyLine=!0;else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"explicit-key-ind":if(!it.sep&&!it.explicitKey)it.start.push(this.sourceToken),it.explicitKey=!0;else if(atNextItem||it.value)start2.push(this.sourceToken),map.items.push({start:start2,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(it.explicitKey)if(!it.sep)if(includesToken(it.start,"newline"))Object.assign(it,{key:null,sep:[this.sourceToken]});else{let start3=getFirstKeyStartProps(it.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start3,key:null,sep:[this.sourceToken]}]})}else if(it.value)map.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(it.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(it.key)&&!includesToken(it.sep,"newline")){let start3=getFirstKeyStartProps(it.start),key2=it.key,sep=it.sep;sep.push(this.sourceToken),delete it.key,delete it.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start3,key:key2,sep}]})}else if(start2.length>0)it.sep=it.sep.concat(start2,this.sourceToken);else it.sep.push(this.sourceToken);else if(!it.sep)Object.assign(it,{key:null,sep:[this.sourceToken]});else if(it.value||atNextItem)map.items.push({start:start2,key:null,sep:[this.sourceToken]});else if(includesToken(it.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else it.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs7=this.flowScalar(this.type);if(atNextItem||it.value)map.items.push({start:start2,key:fs7,sep:[]}),this.onKeyLine=!0;else if(it.sep)this.stack.push(fs7);else Object.assign(it,{key:fs7,sep:[]}),this.onKeyLine=!0;return}default:{let bv=this.startBlockValue(map);if(bv){if(bv.type==="block-seq"){if(!it.explicitKey&&it.sep&&!includesToken(it.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(atMapIndent)map.items.push({start:start2});this.stack.push(bv);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(seq){let it=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it.value){let end="end"in it.value?it.value.end:void 0;if((Array.isArray(end)?end[end.length-1]:void 0)?.type==="comment")end?.push(this.sourceToken);else seq.items.push({start:[this.sourceToken]})}else it.start.push(this.sourceToken);return;case"space":case"comment":if(it.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it.start,seq.indent)){let end=seq.items[seq.items.length-2]?.value?.end;if(Array.isArray(end)){Array.prototype.push.apply(end,it.start),end.push(this.sourceToken),seq.items.pop();return}}it.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it.value||this.indent<=seq.indent)break;it.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;if(it.value||includesToken(it.start,"seq-item-ind"))seq.items.push({start:[this.sourceToken]});else it.start.push(this.sourceToken);return}if(this.indent>seq.indent){let bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop(),yield*this.step()}*flowCollection(fc){let it=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do yield*this.pop(),top=this.peek(1);while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!it||it.sep)fc.items.push({start:[this.sourceToken]});else it.start.push(this.sourceToken);return;case"map-value-ind":if(!it||it.value)fc.items.push({start:[],key:null,sep:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else Object.assign(it,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!it||it.value)fc.items.push({start:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs7=this.flowScalar(this.type);if(!it||it.value)fc.items.push({start:[],key:fs7,sep:[]});else if(it.sep)this.stack.push(fs7);else Object.assign(it,{key:fs7,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}let bv=this.startBlockValue(fc);if(bv)this.stack.push(bv);else yield*this.pop(),yield*this.step()}else{let parent=this.peek(2);if(parent.type==="block-map"&&(this.type==="map-value-ind"&&parent.indent===fc.indent||this.type==="newline"&&!parent.items[parent.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&parent.type!=="flow-collection"){let prev=getPrevProps(parent),start2=getFirstKeyStartProps(prev);fixFlowSeqItems(fc);let sep=fc.end.splice(1,fc.end.length);sep.push(this.sourceToken);let map={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start:start2,key:fc,sep}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=map}else yield*this.lineEnd(fc)}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf(`
|
|
3413
3413
|
`)+1;while(nl!==0)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
|
|
3414
|
-
`,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start2=getFirstKeyStartProps(prev);return start2.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start2=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start2,indent){if(this.type!=="comment")return!1;if(this.indent<=indent)return!1;return start2.every((st)=>st.type==="newline"||st.type==="space")}*documentEnd(docEnd){if(this.type!=="doc-mode"){if(docEnd.end)docEnd.end.push(this.sourceToken);else docEnd.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(token.end)token.end.push(this.sourceToken);else token.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}exports.Parser=Parser});var require_public_api=__commonJS((exports)=>{var composer=require_composer(),Document=require_Document(),errors=require_errors(),log2=require_log(),identity=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));if(docs.length>0)return docs;return Object.assign([],{empty:!0},composer$1.streamInfo())}function parseDocument(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(prettyErrors&&lineCounter2)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return doc}function parse4(src,reviver,options){let _reviver=void 0;if(typeof reviver==="function")_reviver=reviver;else if(options===void 0&&reviver&&typeof reviver==="object")options=reviver;let doc=parseDocument(src,options);if(!doc)return null;if(doc.warnings.forEach((warning)=>log2.warn(doc.options.logLevel,warning)),doc.errors.length>0)if(doc.options.logLevel!=="silent")throw doc.errors[0];else doc.errors=[];return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value,replacer,options){let _replacer=null;if(typeof replacer==="function"||Array.isArray(replacer))_replacer=replacer;else if(options===void 0&&replacer)options=replacer;if(typeof options==="string")options=options.length;if(typeof options==="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}if(identity.isDocument(value)&&!_replacer)return value.toString(options);return new Document.Document(value,_replacer,options).toString(options)}exports.parse=parse4;exports.parseAllDocuments=parseAllDocuments;exports.parseDocument=parseDocument;exports.stringify=stringify});import{Database}from"bun:sqlite";import{homedir as homedir3}from"os";function
|
|
3414
|
+
`,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start2=getFirstKeyStartProps(prev);return start2.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start2=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start2,indent){if(this.type!=="comment")return!1;if(this.indent<=indent)return!1;return start2.every((st)=>st.type==="newline"||st.type==="space")}*documentEnd(docEnd){if(this.type!=="doc-mode"){if(docEnd.end)docEnd.end.push(this.sourceToken);else docEnd.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(token.end)token.end.push(this.sourceToken);else token.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}exports.Parser=Parser});var require_public_api=__commonJS((exports)=>{var composer=require_composer(),Document=require_Document(),errors=require_errors(),log2=require_log(),identity=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));if(docs.length>0)return docs;return Object.assign([],{empty:!0},composer$1.streamInfo())}function parseDocument(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(prettyErrors&&lineCounter2)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return doc}function parse4(src,reviver,options){let _reviver=void 0;if(typeof reviver==="function")_reviver=reviver;else if(options===void 0&&reviver&&typeof reviver==="object")options=reviver;let doc=parseDocument(src,options);if(!doc)return null;if(doc.warnings.forEach((warning)=>log2.warn(doc.options.logLevel,warning)),doc.errors.length>0)if(doc.options.logLevel!=="silent")throw doc.errors[0];else doc.errors=[];return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value,replacer,options){let _replacer=null;if(typeof replacer==="function"||Array.isArray(replacer))_replacer=replacer;else if(options===void 0&&replacer)options=replacer;if(typeof options==="string")options=options.length;if(typeof options==="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}if(identity.isDocument(value)&&!_replacer)return value.toString(options);return new Document.Document(value,_replacer,options).toString(options)}exports.parse=parse4;exports.parseAllDocuments=parseAllDocuments;exports.parseDocument=parseDocument;exports.stringify=stringify});import{Database}from"bun:sqlite";import{homedir as homedir3}from"os";function walkUp(sid){let step=q2(`SELECT p.id FROM sessions c
|
|
3415
|
+
JOIN sessions p ON p.id = c.parent_session_id
|
|
3416
|
+
WHERE c.id = ? AND ${CONT("c")}`),cur=sid;for(let i=0;i<100;i++){let prev=step?.get(cur);if(!prev)return cur;cur=prev.id}return cur}function roots(limit=30){let end=mark("io:sessions.roots");try{return(q2(`SELECT ${COLS} FROM sessions s
|
|
3415
3417
|
WHERE s.parent_session_id IS NULL
|
|
3416
3418
|
OR EXISTS (SELECT 1 FROM sessions p
|
|
3417
3419
|
WHERE p.id = s.parent_session_id
|
|
@@ -3454,7 +3456,13 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
3454
3456
|
(SELECT MAX(timestamp) FROM messages WHERE session_id = s.id) AS last_active,
|
|
3455
3457
|
(SELECT COUNT(*) FROM sessions c
|
|
3456
3458
|
WHERE c.parent_session_id = s.id
|
|
3457
|
-
AND (s.ended_at IS NULL OR c.started_at < s.ended_at)) AS subagent_count`,toRow=(r,lineage=null)=>({source:SRC,id:r.id,sessionSource:r.source,model:r.model,started_at:r.started_at,ended_at:r.ended_at,end_reason:r.end_reason,message_count:r.message_count,tool_call_count:r.tool_call_count,input_tokens:r.input_tokens,output_tokens:r.output_tokens,cache_read_tokens:r.cache_read_tokens,cache_write_tokens:r.cache_write_tokens,reasoning_tokens:r.reasoning_tokens,estimated_cost_usd:r.estimated_cost_usd,title:r.title,lastMessage:r.lastMessage,last_active:r.last_active,parent_session_id:r.parent_session_id,subagent_count:r.subagent_count,lineage_root_id:lineage}),one2=(id)=>q2(`SELECT ${COLS} FROM sessions s WHERE s.id = ?`)?.get(id)??null,byId=(id)=>{let r=one2(id);return r?toRow(r):null},lastReal=()=>
|
|
3459
|
+
AND (s.ended_at IS NULL OR c.started_at < s.ended_at)) AS subagent_count`,toRow=(r,lineage=null)=>({source:SRC,id:r.id,sessionSource:r.source,model:r.model,started_at:r.started_at,ended_at:r.ended_at,end_reason:r.end_reason,message_count:r.message_count,tool_call_count:r.tool_call_count,input_tokens:r.input_tokens,output_tokens:r.output_tokens,cache_read_tokens:r.cache_read_tokens,cache_write_tokens:r.cache_write_tokens,reasoning_tokens:r.reasoning_tokens,estimated_cost_usd:r.estimated_cost_usd,title:r.title,lastMessage:r.lastMessage,last_active:r.last_active,parent_session_id:r.parent_session_id,subagent_count:r.subagent_count,lineage_root_id:lineage}),one2=(id)=>q2(`SELECT ${COLS} FROM sessions s WHERE s.id = ?`)?.get(id)??null,byId=(id)=>{let r=one2(id);return r?toRow(r):null},lastReal=()=>{let hit=q2(`
|
|
3460
|
+
SELECT s.id FROM sessions s
|
|
3461
|
+
LEFT JOIN sessions p ON p.id = s.parent_session_id
|
|
3462
|
+
WHERE s.source IN ('tui', 'cli') AND s.message_count > 0
|
|
3463
|
+
AND (s.parent_session_id IS NULL OR ${CONT("s")})
|
|
3464
|
+
ORDER BY s.started_at DESC LIMIT 1
|
|
3465
|
+
`)?.get();if(!hit)return;let row=byId(chainTip(hit.id));return row&&row.message_count>0?row:void 0},chainTip=(sid)=>tip(walkUp(sid)),systemPrompt=()=>q2(`SELECT id, system_prompt AS text FROM sessions
|
|
3458
3466
|
WHERE system_prompt IS NOT NULL AND length(system_prompt) > 1000
|
|
3459
3467
|
ORDER BY started_at DESC LIMIT 1`)?.get()??null,fts=(s)=>s.trim().split(/\s+/).filter(Boolean).map((w2)=>/^\w+$/.test(w2)?`${w2}*`:`"${w2.replace(/"/g,'""')}"`).join(" ");var init_sessions_db=__esm(()=>{init_perf();HERMES=process.env.HERMES_HOME||`${process.env.HOME||homedir3()}/.hermes`,SRC={file:`${HERMES}/state.db`,relative:"state.db",label:"state.db"},conn={path:SRC.file,ro:null},stmts=new Map});function analytics(days,opts){let since=Math.floor(Date.now()/1000)-days*86400,db=stateDb();if(!db)return ZERO;let q3=db.query.bind(db),tot=q3(`SELECT COUNT(*) n,
|
|
3460
3468
|
COALESCE(SUM(message_count),0) msgs,
|
|
@@ -4093,7 +4101,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
4093
4101
|
`,skE);while(end<text2.length&&end>=0){let nl=text2.indexOf(`
|
|
4094
4102
|
`,end+1);if(nl<0){end=text2.length;break}let line=text2.slice(end+1,nl).trim();if(line.startsWith("#"))break;if(line===""){if(text2.slice(nl+1,text2.indexOf(`
|
|
4095
4103
|
`,nl+1)).trim().startsWith("#")){end=nl;break}}end=nl}mark2(skH,end+1,"skills","Skills Catalog",makeSource("skills","skills/"))}let proj=text2.indexOf("# Project Context");if(proj>=0){let conv2=text2.indexOf("Conversation started:");mark2(proj,conv2>proj?conv2:text2.length,"project","Project Context",makeSource("AGENTS.md"))}let conv=text2.indexOf("Conversation started:");if(conv>=0)mark2(conv,text2.length,"meta","Session Metadata");let start2=-1;for(let i=0;i<=text2.length;i++)if(i<text2.length&&!used[i]){if(start2<0)start2=i}else if(start2>=0){let slice=text2.slice(start2,i);if(slice.trim().length>0)sections.push({id:"other",label:"Other",chars:slice.length,tokens:count2(slice),text:slice});start2=-1}return sections.sort((a,b2)=>text2.indexOf(a.text)-text2.indexOf(b2.text))}function classifyTools(tools){let system=[],mcp=[];for(let t2 of tools)if(t2.name.startsWith("mcp_"))mcp.push(t2);else system.push(t2);return{system,mcp}}function toolTokens(tool){return Math.ceil((tool.descriptionLength+tool.paramsLength)/CPT)}function build(opts){let pct=(t2)=>opts.contextLength>0?t2/opts.contextLength*100:0,result=[],byId2=new Map;for(let s of opts.sections)byId2.set(s.id,s);let promptChildren=opts.sections.filter((sec)=>SYSTEM_PROMPT_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),promptTok=promptChildren.reduce((s,c)=>s+c.tokens,0);if(promptTok>0)result.push({id:"system_prompt",label:"System Prompt",tokens:promptTok,percent:pct(promptTok),children:promptChildren});let{system:sysTools,mcp:mcpTools}=classifyTools(opts.tools),sysToolsTok=sysTools.reduce((s,t2)=>s+toolTokens(t2),0);if(sysToolsTok>0)result.push({id:"system_tools",label:"System Tools",tokens:sysToolsTok,percent:pct(sysToolsTok)});let mcpToolsTok=mcpTools.reduce((s,t2)=>s+toolTokens(t2),0);if(mcpToolsTok>0)result.push({id:"mcp_tools",label:"MCP Tools",tokens:mcpToolsTok,percent:pct(mcpToolsTok)});let memChildren=opts.sections.filter((sec)=>MEMORY_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),memTok=memChildren.reduce((s,c)=>s+c.tokens,0);if(memTok>0)result.push({id:"memory",label:"Memory",tokens:memTok,percent:pct(memTok),children:memChildren});let skillsSec=byId2.get("skills"),skillsTok=skillsSec?.tokens??opts.skillsTokens??0;if(skillsTok>0)result.push({id:"skills",label:"Skills",tokens:skillsTok,percent:pct(skillsTok),section:skillsSec});if(opts.conversationTokens>0){let ct=Math.min(opts.conversationTokens,opts.inputTokens||opts.conversationTokens);result.push({id:"conversation",label:"Conversation",tokens:ct,percent:pct(ct)})}let taken=result.reduce((s,g)=>s+g.tokens,0),free=Math.max(0,opts.contextLength-taken);return result.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),result}function drill(group){if(!group.children||group.children.length===0)return[];let total=group.tokens;return group.children.map((c)=>({...c,percent:total>0?c.tokens/total*100:0}))}function cells(segments,fallback="free"){let filled=segments.flatMap((seg)=>Array.from({length:Math.round(seg.percent/100*GRID)},()=>({id:seg.id}))),pad=Array.from({length:Math.max(0,GRID-filled.length)},()=>({id:fallback}));return[...filled,...pad].slice(0,GRID)}var import_react47=__toESM(require_react_production(),1);var FileLink=import_react47.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react47.useState(!1);return $jsx("box",{height:1,onMouseDown:()=>openFile(source.file),onMouseOver:()=>setHovered(!0),onMouseOut:()=>setHovered(!1),children:$jsx("text",{fg:theme.info,attributes:hovered?TextAttributes.UNDERLINE:TextAttributes.NONE,children:children2??source.label})})}),KVLink=(props)=>{let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx(FileLink,{source:props.source,children:props.text??props.source.label})})]})};var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:` ${props.hint}`})})]}),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,children:props.children})]})};var GOLDEN_ANGLE=137.50776405003785;function luminance(c){return 0.299*c.r+0.587*c.g+0.114*c.b}function rgbaToHsl(c){let{r,g,b:b2}=c,max=Math.max(r,g,b2),min=Math.min(r,g,b2),l=(max+min)/2,d2=max-min;if(d2===0)return[0,0,l];let s=l>0.5?d2/(2-max-min):d2/(max+min),h2;switch(max){case r:h2=(g-b2)/d2+(g<b2?6:0);break;case g:h2=(b2-r)/d2+2;break;default:h2=(r-g)/d2+4}return[h2*60,s,l]}function hslToRgba(h2,s,l){if(h2=(h2%360+360)%360/360,s===0)return RGBA.fromValues(l,l,l,1);let q3=l<0.5?l*(1+s):l+s-l*s,p=2*l-q3,ch=(t2)=>{if(t2<0)t2+=1;if(t2>1)t2-=1;if(t2<0.16666666666666666)return p+(q3-p)*6*t2;if(t2<0.5)return q3;if(t2<0.6666666666666666)return p+(q3-p)*(0.6666666666666666-t2)*6;return p};return RGBA.fromValues(ch(h2+0.3333333333333333),ch(h2),ch(h2-0.3333333333333333),1)}function categorical(seed,bg2,n){let[h0]=rgbaToHsl(seed),dark=luminance(bg2)<0.5,s=dark?0.6:0.7,l=dark?0.62:0.42,out=[];for(let i=0;i<n;i++)out.push(hslToRgba(h0+i*GOLDEN_ANGLE,s,l));return out}var DEFAULT_CTX=128000,COLS2=16,SLOTS2=["system_prompt","system_tools","mcp_tools","memory","skills","conversation","soul","mem0","user","project","meta","other"],SLOT=Object.fromEntries(SLOTS2.map((id,i)=>[id,i])),rampCache=new WeakMap;function ramp2(theme){let r=rampCache.get(theme);if(!r)rampCache.set(theme,r=categorical(theme.primary,theme.background,SLOTS2.length));return r}function clr(id,theme){if(id==="free")return theme.borderSubtle;return ramp2(theme)[SLOT[id]??SLOT.other]}var fmt=(n)=>{if(n>=1e6)return`${(n/1e6).toFixed(1)}M`;if(n>=1e4)return`${Math.round(n/1000)}k`;if(n>=1000)return`${(n/1000).toFixed(1)}k`;return String(n)},est=(s)=>s?count2(s):0,bar=(pct,w2=20)=>{let f=Math.round(Math.max(0,Math.min(100,pct))/100*w2);return`[${"\u2588".repeat(f)}${"\u2591".repeat(Math.max(0,w2-f))}]`},SectionPanel=import_react48.memo(({seg,theme})=>{let{syntaxStyle}=useTheme(),sec=seg.section;if(!sec)return null;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsxs("text",{children:[sec.chars.toLocaleString()," chars \xB7 ~",fmt(sec.tokens)," tokens"]}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsx("markdown",{content:sec.text,fg:theme.markdownText,syntaxStyle})]})}),MemoryPanel=import_react48.memo(({seg,theme,label,chars,limit,pct,entries,source})=>$jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:$jsx("strong",{children:label})}),source?$jsxs($Fragment2,{children:[$jsx("text",{children:" ("}),$jsx(FileLink,{source}),$jsx("text",{children:")"})]}):null]}),$jsxs("text",{children:[chars.toLocaleString()," / ",limit.toLocaleString()," chars (",pct,"%)"]}),$jsxs("text",{children:[bar(pct,25),pct>=95?" \u26A0 near limit":""]}),$jsx("text",{children:" "}),$jsxs("text",{children:[entries.length," entries:"]}),entries.map((e,i)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",e]},i))]})),SkillsPanel=import_react48.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line of sec.text.split(`
|
|
4096
|
-
`)){if(line.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line.match(/^\s{4}- \S+:/)){let last=Object.keys(cats).pop();if(last)cats[last]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react48.memo(({seg,theme,tools,kind})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label=kind==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind,theme),children:"\u25FC"})," ",label," \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react48.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment2,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react48.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment2,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),Context=import_react48.memo(({messages=NO_MESSAGES,info,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),recentSessions=useHome("recentSessions"),liveSessions=useHome("liveSessions"),[wire,setWire]=import_react48.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react48.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react48.useState(null),[selected,setSelected]=import_react48.useState(null),[drilled,setDrilled]=import_react48.useState(null);import_react48.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let session=recentSessions?.[0],ctxLen=info?.context_max??DEFAULT_CTX,lastPrompt=(session?Object.values(liveSessions??{}).find((ls)=>ls.session_id===session.id):void 0)?.last_prompt_tokens??0,fill=wire.calls>0?wire.input:lastPrompt>0?lastPrompt:session?.input_tokens??0,cumulative=wire.calls===0&&lastPrompt===0&&(session?.input_tokens??0)>0,output=wire.calls>0?wire.output:session?.output_tokens??0,pct=ctxLen>0?Math.round(fill/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react48.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react48.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),top=import_react48.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:toolsInfo?.tools??[]}),[ctxLen,fill,sections,convTok,toolsInfo?.tools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react48.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":"free"),[view,drilledGroup]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react48.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react48.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react48.useRef(0),segs=view.filter((s)=>s.tokens>0),idx3=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx3):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&&toolsInfo){let{system}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&toolsInfo){let{mcp}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt(drilledGroup.tokens)," tok)"]}):$jsx("span",{fg:theme.info,children:" (click group to expand)"})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt(output)," tokens"]}):null,$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})})]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:wire.calls===0&&fill===0?"[no data]":cumulative?"[cumulative \u2014 not current fill]":wire.calls===0&&fill>0?"[live session]":"\u2191\u2193 nav \xB7 click a group to drill in",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs(TabShell,{title:`Context \xB7 ${fmt(fill)} / ${fmt(ctxLen)} (${pct}%)`,hint:crumb+escHint,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=row*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]})});var import_react53=__toESM(require_react_production(),1);init_sessions_db();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_react50=__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",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_react50.useRef(null),node=import_react50.useRef(null),animate=get("animations")!==!1&&p.active;return import_react50.useEffect(()=>{let tn=node.current;if(!tn)return;if(!animate){tn.scrollX=0;return}let id,period=text2.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let w2=box.current?.width??0;if(text2.length<=w2){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]),$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:text2+GAP+text2})}):$jsx("span",{fg:fg2,children:text2+GAP+text2})})})},GAP=" ";var import_react51=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react51.useRef(null),animate=get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react51.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)||keys.match("dialog.cancel",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)=>{dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}))})}var h12=()=>get("timeFormat")==="12h",abs=()=>get("timeStyle")==="absolute",trunc4=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt2=(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=(start2,end)=>{let s=Math.round(end-start2);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 badge=(src)=>({cli:"CLI",tui:"TUI",api_server:"API",discord:"Discord",telegram:"Telegram",slack:"Slack",whatsapp:"WhatsApp",signal:"Signal"})[src]??src,line=(s)=>(s??"").replace(/\s+/g," ").trim(),fold=(msgs)=>{let turns=[],tools=0;for(let m2 of msgs){if(m2.role==="tool"){tools++;continue}if(m2.role!=="user"&&m2.role!=="assistant")continue;let text2=line(m2.content);if(!text2)continue;turns.push({role:m2.role,text:text2})}return{turns,tools}},PeekRow=import_react53.memo((props)=>{let theme=useTheme().theme,[hot,setHot]=import_react53.useState(!1),left=props.row.role==="user",color=left?theme.primary:theme.accent,fg2=left?theme.text:theme.markdownText,bar2=(side)=>$jsx("box",{width:2,flexShrink:0,height:1,border:[side],borderColor:color,customBorderChars:SIDE_PIPE});return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:hot?theme.backgroundElement:void 0,onMouseOver:()=>setHot(!0),onMouseOut:()=>setHot(!1),children:[left?bar2("left"):null,$jsx(Ticker,{active:hot,speed:35,hold:150,fg:fg2,children:inline(props.row.text).map((s,i)=>s.c?$jsx("span",{fg:theme.warning,children:s.t},i):s.b?$jsx("span",{fg:fg2,children:$jsx("strong",{children:s.t})},i):s.i?$jsx("span",{fg:fg2,children:$jsx("u",{children:s.t})},i):$jsx("span",{fg:fg2,children:s.t},i))}),left?null:bar2("right")]})}),Peek=import_react53.memo((props)=>{let theme=useTheme().theme,[data2,setData]=import_react53.useState(null),sb=import_react53.useRef(null);if(import_react53.useEffect(()=>{Promise.resolve(props.peek(props.sid,60)).then((m2)=>setData(fold(m2)))},[props.sid,props.peek]),import_react53.useEffect(()=>{if(data2&&sb.current)sb.current.scrollTop=sb.current.scrollHeight},[data2]),data2===null)return null;if(data2.turns.length===0&&data2.tools===0)return $jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local transcript)"})});let more=Math.max(0,props.total-60);return $jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:5,border:!0,borderStyle:"single",borderColor:theme.border,title:` Transcript${more>0?` \xB7 ${more} earlier`:""} `,titleAlignment:"left",children:[$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,minHeight:3,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.turns.map((r,i)=>$jsx(PeekRow,{row:r},i))})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${data2.turns.length} turn${data2.turns.length===1?"":"s"} \xB7 ${data2.tools} tool call${data2.tools===1?"":"s"}`})})]})}),Detail=import_react53.memo((props)=>{let theme=useTheme().theme,r=props.row,d2=r.detail,lastActive=d2?.last_active??d2?.ended_at??null,subs2=d2?.subagent_count??0,[info,setInfo]=import_react53.useState({});import_react53.useEffect(()=>{Promise.resolve(props.lineage(r.id)).then(setInfo)},[r.id,props.lineage]);let hasLineage=info.continuesFrom||info.compressedTo||subs2>0,go=(sid)=>()=>props.onSwitch?.(sid);return $jsx(TabShell,{title:"Session Detail",hint:"",grow:2,children:$jsxs("box",{flexDirection:"column",width:"100%",flexGrow:1,overflow:"hidden",children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:r.title||"Untitled"})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["ID",r.id],["Source",badge(r.source??"")],["Model",d2?.model??"\u2014"],["Started",when(r.started_at)],["Last active",lastActive?`${when(lastActive)} (${ago(lastActive)})`:"\u2014"],["Duration",lastActive?span(r.started_at,lastActive):"\u2014"],["Ended",d2?.ended_at?`${when(d2.ended_at)} \xB7 ${d2.end_reason??"\u2014"}`:void 0]]}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Messages",String(r.message_count)],["Tool calls",d2?String(d2.tool_call_count):void 0],["Input",d2?`${fmt2(d2.input_tokens)} tok`:void 0],["Output",d2?`${fmt2(d2.output_tokens)} tok`:void 0],["Cache",d2?`${fmt2(d2.cache_read_tokens)} r / ${fmt2(d2.cache_write_tokens)} w`:void 0],["Reasoning",d2?`${fmt2(d2.reasoning_tokens)} tok`:void 0],["Cost",d2?cost(d2.estimated_cost_usd):void 0,theme.success]]}),hasLineage?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,children:"Lineage"})}),info.continuesFrom?$jsx("box",{height:1,onMouseDown:go(info.continuesFrom.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2190 continues from "}),$jsx("span",{fg:theme.accent,children:info.continuesFrom.title||info.continuesFrom.id})]})}):null,info.compressedTo?$jsx("box",{height:1,onMouseDown:go(info.compressedTo.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2192 compressed to "}),$jsx("span",{fg:theme.accent,children:info.compressedTo.title||info.compressedTo.id})]})}):null,subs2>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2387 spawned "}),$jsx("span",{fg:theme.text,children:String(subs2)}),$jsx("span",{fg:theme.textMuted,children:` subagent${subs2===1?"":"s"}`})]})}):null]}):null,!d2?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local detail \u2014 state.db mismatch)"})})]}):null,$jsx("box",{height:1})]}),$jsx(Peek,{sid:r.id,total:r.message_count,peek:props.peek})]})})}),SearchDetail=import_react53.memo((props)=>{let theme=useTheme().theme,r=props.result,parts2=[],rest=r.snippet;while(rest.length){let start2=rest.indexOf(">>>");if(start2<0){parts2.push({text:rest,hi:!1});break}if(start2>0)parts2.push({text:rest.slice(0,start2),hi:!1});let end=rest.indexOf("<<<",start2+3);if(end<0){parts2.push({text:rest.slice(start2+3),hi:!0});break}parts2.push({text:rest.slice(start2+3,end),hi:!0}),rest=rest.slice(end+3)}return $jsx(TabShell,{title:"Search Match",hint:"",grow:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:r.title??"Untitled"})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Source",badge(r.source)],["Model",r.model??"\u2014"],["Time",when(r.started_at)]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Snippet"})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:parts2.map((p,i)=>p.hi?$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:p.text})},i):$jsx("span",{fg:theme.text,children:p.text},i))})})]})})})}),HeaderRow=import_react53.memo(()=>{let fg2=useTheme().theme.textMuted;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:8,fg:fg2,bold:!0,children:"Start"}),$jsx(Col,{w:10,fg:fg2,bold:!0,right:!0,children:"Active"}),$jsx(Col,{w:7,fg:fg2,bold:!0,right:!0,children:"Msgs"}),$jsx("box",{width:3})]})}),Item=import_react53.memo((props)=>{let theme=useTheme().theme,{row:r,idx:i}=props,[x2,setX]=import_react53.useState(!1),active=r.detail?.last_active??r.detail?.ended_at??null,leader=props.indent?"\u2514\u2500":props.selected?"\u25B8 ":" ",muted=props.indent&&!props.selected?theme.textMuted:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:muted??theme.text,children:leader}),$jsx(Marquee,{grow:!0,active:props.selected,fg:props.selected?theme.accent:muted??theme.text,bold:props.selected,children:r.title||"Untitled"}),$jsx(Col,{w:9,fg:muted??theme.info,children:badge(r.source??"")}),$jsx(Col,{w:8,fg:theme.textMuted,children:stamp(r.started_at)}),$jsx(Col,{w:10,fg:theme.textMuted,right:!0,children:active?ago(active):"\u2014"}),$jsx(Col,{w:7,fg:theme.textMuted,right:!0,children:String(r.message_count)}),props.indent?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{children:$jsx("span",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})})]})}),SearchHeaderRow=import_react53.memo(()=>{let fg2=useTheme().theme.textMuted;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:10,fg:fg2,bold:!0,children:"When"}),$jsx(Col,{w:20,fg:fg2,bold:!0,children:"Model"})]})}),SearchItem=import_react53.memo((props)=>{let theme=useTheme().theme,{result:r,idx:i}=props;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,bold:props.selected,children:r.title??"Untitled"}),$jsx(Col,{w:9,fg:theme.info,children:badge(r.source)}),$jsx(Col,{w:10,fg:theme.textMuted,children:ago(r.started_at)}),$jsx(Col,{w:20,fg:theme.textMuted,children:r.model??"\u2014"})]})}),last={rows:[],kids:new Map},Sessions=import_react53.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),cached2=props.io==null,io2={list:props.io?.list??io.roots,search:props.io?.search??io.search,subagents:props.io?.subagents??io.children,lineage:props.io?.lineage??io.lineage,peek:props.io?.peek??io.peek,remove:props.io?.remove??remove,rename:props.io?.rename??rename},[rows2,setRows]=import_react53.useState(cached2?last.rows:[]),[warn,setWarn]=import_react53.useState(""),[pending2,setPending]=import_react53.useState(rows2.length===0),[anchor,setAnchor]=import_react53.useState(null),[searching,setSearching]=import_react53.useState(!1),[query,setQuery]=import_react53.useState(""),[results,setResults]=import_react53.useState([]),[searchSel,setSearchSel]=import_react53.useState(0),[kids,setKids]=import_react53.useState(cached2?last.kids:new Map),debounce=import_react53.useRef(null),vscroll=import_react53.useRef(null),anchored=anchor&&rows2.find((r)=>r.id===anchor.id),owner=anchor?.indent?rows2.find((r)=>kids.get(r.id)?.some((c)=>c.id===anchor.id)):(anchored?.detail?.subagent_count??0)>0?anchored:void 0,visible=rows2.flatMap((r,i)=>r.id===owner?.id?[{row:r,indent:!1,parentIdx:i},...(kids.get(r.id)??[]).map((c)=>({row:c,indent:!0,parentIdx:i}))]:[{row:r,indent:!1,parentIdx:i}]),sel=anchor?Math.max(0,visible.findIndex((v2)=>v2.row.id===anchor.id&&v2.indent===anchor.indent)):0,live=import_react53.useRef({rows:rows2,visible,anchor,results,searching,onSwitch:props.onSwitch,currentId:props.currentId});live.current={rows:rows2,visible,anchor,results,searching,onSwitch:props.onSwitch,currentId:props.currentId};let setSel=import_react53.useCallback((arg)=>{let cur=live.current,prev=cur.visible.findIndex((v3)=>v3.row.id===cur.anchor?.id&&v3.indent===cur.anchor.indent),n=typeof arg==="function"?arg(Math.max(0,prev)):arg,v2=cur.visible[Math.max(0,Math.min(cur.visible.length-1,n))];if(v2)setAnchor({id:v2.row.id,indent:v2.indent})},[]),LIMIT=2000,toRow2=(d2)=>({id:d2.id,title:d2.title??"",preview:d2.lastMessage??"",message_count:d2.message_count,started_at:d2.started_at,source:d2.sessionSource,detail:d2}),load3=import_react53.useCallback(async()=>{setPending(!0);let rpc=gw.request("session.list",{limit:LIMIT}).then((r2)=>({ok:!0,v:r2})).catch((e)=>({ok:!1,e})),disk=await Promise.resolve(io2.list(LIMIT)).catch(()=>[]),local=new Map(disk.map((r2)=>[r2.id,r2])),diskRows=disk.filter((d2)=>d2.message_count>0).map(toRow2);if(setRows(diskRows),cached2)last.rows=diskRows;let fillKids=async(list)=>{let ps=list.filter((r2)=>(r2.detail?.subagent_count??0)>0),cs=await Promise.all(ps.map((r2)=>io2.subagents(r2.id))),m2=new Map(ps.map((r2,i)=>[r2.id,cs[i].map(toRow2)]));if(setKids(m2),cached2)last.kids=m2};fillKids(diskRows);let r=await rpc;if(r.ok&&r.v.sessions?.length){let merged=r.v.sessions.filter((s)=>(s.message_count??0)>0).map((s)=>({...s,detail:local.get(s.id)}));if(setRows(merged),cached2)last.rows=merged;fillKids(merged)}setPending(!1),setWarn(!r.ok?local.size?`gateway session.list failed (${r.e.message}) \u2014 listing state.db directly; rows may not resume`:r.e.message:"")},[gw]);import_react53.useEffect(()=>{load3()},[load3]),import_react53.useEffect(()=>{if(!anchor&&rows2.length)setAnchor({id:rows2[0].id,indent:!1})},[rows2,anchor]),import_react53.useEffect(()=>{if(!searching||!query.trim()){setResults([]);return}return debounce.current=setTimeout(()=>{Promise.resolve(io2.search(query,30)).then((r)=>{setResults(r),setSearchSel(0)})},150),()=>{if(debounce.current)clearTimeout(debounce.current)}},[query,searching]);let rowHover=import_react53.useCallback((i)=>{live.current.searching?setSearchSel(i):setSel(i)},[setSel]),rowActivate=import_react53.useCallback((i)=>{let l=live.current;l.searching?setSearchSel(i):setSel(i);let hit=l.searching?l.results[i]:l.visible[i]?.row,id=l.searching?hit?.session_id:hit?.id;if(!id||!l.onSwitch)return;if(id===l.currentId)return l.onSwitch(id);let title=hit?.title||"Untitled",n=l.searching?void 0:hit.message_count;openConfirm(dialog,{title:"Load session?",body:`${trunc4(title,60)}${n!=null?` \xB7 ${n} msg${n===1?"":"s"}`:""}
|
|
4104
|
+
`)){if(line.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line.match(/^\s{4}- \S+:/)){let last=Object.keys(cats).pop();if(last)cats[last]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react48.memo(({seg,theme,tools,kind})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label=kind==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind,theme),children:"\u25FC"})," ",label," \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react48.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment2,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react48.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment2,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),Context=import_react48.memo(({messages=NO_MESSAGES,info,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),recentSessions=useHome("recentSessions"),liveSessions=useHome("liveSessions"),[wire,setWire]=import_react48.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react48.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react48.useState(null),[selected,setSelected]=import_react48.useState(null),[drilled,setDrilled]=import_react48.useState(null);import_react48.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let session=recentSessions?.[0],ctxLen=info?.context_max??DEFAULT_CTX,lastPrompt=(session?Object.values(liveSessions??{}).find((ls)=>ls.session_id===session.id):void 0)?.last_prompt_tokens??0,fill=wire.calls>0?wire.input:lastPrompt>0?lastPrompt:session?.input_tokens??0,cumulative=wire.calls===0&&lastPrompt===0&&(session?.input_tokens??0)>0,output=wire.calls>0?wire.output:session?.output_tokens??0,pct=ctxLen>0?Math.round(fill/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react48.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react48.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),top=import_react48.useMemo(()=>build({contextLength:ctxLen,inputTokens:fill,sections,conversationTokens:convTok,tools:toolsInfo?.tools??[]}),[ctxLen,fill,sections,convTok,toolsInfo?.tools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react48.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":"free"),[view,drilledGroup]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react48.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react48.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react48.useRef(0),segs=view.filter((s)=>s.tokens>0),idx3=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx3):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key2)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key2,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key2.name==="right")return setSel((p)=>p+1);if(key2.name==="left")return setSel((p)=>p-1);if(key2.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&&toolsInfo){let{system}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&&toolsInfo){let{mcp}=classifyTools(toolsInfo.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt(drilledGroup.tokens)," tok)"]}):$jsx("span",{fg:theme.info,children:" (click group to expand)"})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt(output)," tokens"]}):null,$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})})]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:wire.calls===0&&fill===0?"[no data]":cumulative?"[cumulative \u2014 not current fill]":wire.calls===0&&fill>0?"[live session]":"\u2191\u2193 nav \xB7 click a group to drill in",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs(TabShell,{title:`Context \xB7 ${fmt(fill)} / ${fmt(ctxLen)} (${pct}%)`,hint:crumb+escHint,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=row*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]})});var import_react53=__toESM(require_react_production(),1);init_sessions_db();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_react50=__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",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_react50.useRef(null),node=import_react50.useRef(null),animate=get("animations")!==!1&&p.active;return import_react50.useEffect(()=>{let tn=node.current;if(!tn)return;if(!animate){tn.scrollX=0;return}let id,period=text2.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let w2=box.current?.width??0;if(text2.length<=w2){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]),$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:text2+GAP+text2})}):$jsx("span",{fg:fg2,children:text2+GAP+text2})})})},GAP=" ";var import_react51=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react51.useRef(null),animate=get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react51.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)||keys.match("dialog.cancel",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)=>{dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}))})}var h12=()=>get("timeFormat")==="12h",abs=()=>get("timeStyle")==="absolute",trunc4=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt2=(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=(start2,end)=>{let s=Math.round(end-start2);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 badge=(src)=>({cli:"CLI",tui:"TUI",api_server:"API",discord:"Discord",telegram:"Telegram",slack:"Slack",whatsapp:"WhatsApp",signal:"Signal"})[src]??src,line=(s)=>(s??"").replace(/\s+/g," ").trim(),fold=(msgs)=>{let turns=[],tools=0;for(let m2 of msgs){if(m2.role==="tool"){tools++;continue}if(m2.role!=="user"&&m2.role!=="assistant")continue;let text2=line(m2.content);if(!text2)continue;turns.push({role:m2.role,text:text2})}return{turns,tools}},PeekRow=import_react53.memo((props)=>{let theme=useTheme().theme,[hot,setHot]=import_react53.useState(!1),left=props.row.role==="user",color=left?theme.primary:theme.accent,fg2=left?theme.text:theme.markdownText,bar2=(side)=>$jsx("box",{width:2,flexShrink:0,height:1,border:[side],borderColor:color,customBorderChars:SIDE_PIPE});return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:hot?theme.backgroundElement:void 0,onMouseOver:()=>setHot(!0),onMouseOut:()=>setHot(!1),children:[left?bar2("left"):null,$jsx(Ticker,{active:hot,speed:35,hold:150,fg:fg2,children:inline(props.row.text).map((s,i)=>s.c?$jsx("span",{fg:theme.warning,children:s.t},i):s.b?$jsx("span",{fg:fg2,children:$jsx("strong",{children:s.t})},i):s.i?$jsx("span",{fg:fg2,children:$jsx("u",{children:s.t})},i):$jsx("span",{fg:fg2,children:s.t},i))}),left?null:bar2("right")]})}),Peek=import_react53.memo((props)=>{let theme=useTheme().theme,[data2,setData]=import_react53.useState(null),sb=import_react53.useRef(null);if(import_react53.useEffect(()=>{Promise.resolve(props.peek(props.sid,60)).then((m2)=>setData(fold(m2)))},[props.sid,props.peek]),import_react53.useEffect(()=>{if(data2&&sb.current)sb.current.scrollTop=sb.current.scrollHeight},[data2]),data2===null)return null;if(data2.turns.length===0&&data2.tools===0)return $jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local transcript)"})});let more=Math.max(0,props.total-60);return $jsxs("box",{flexDirection:"column",flexGrow:1,minHeight:5,border:!0,borderStyle:"single",borderColor:theme.border,title:` Transcript${more>0?` \xB7 ${more} earlier`:""} `,titleAlignment:"left",children:[$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,minHeight:3,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.turns.map((r,i)=>$jsx(PeekRow,{row:r},i))})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${data2.turns.length} turn${data2.turns.length===1?"":"s"} \xB7 ${data2.tools} tool call${data2.tools===1?"":"s"}`})})]})}),Detail=import_react53.memo((props)=>{let theme=useTheme().theme,r=props.row,d2=r.detail,lastActive=d2?.last_active??d2?.ended_at??null,subs2=d2?.subagent_count??0,[info,setInfo]=import_react53.useState({});import_react53.useEffect(()=>{Promise.resolve(props.lineage(r.id)).then(setInfo)},[r.id,props.lineage]);let hasLineage=info.continuesFrom||info.compressedTo||subs2>0,go=(sid)=>()=>props.onSwitch?.(sid);return $jsx(TabShell,{title:"Session Detail",hint:"",grow:2,children:$jsxs("box",{flexDirection:"column",width:"100%",flexGrow:1,overflow:"hidden",children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:r.title||"Untitled"})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["ID",r.id],["Source",badge(r.source??"")],["Model",d2?.model??"\u2014"],["Started",when(r.started_at)],["Last active",lastActive?`${when(lastActive)} (${ago(lastActive)})`:"\u2014"],["Duration",lastActive?span(r.started_at,lastActive):"\u2014"],["Ended",d2?.ended_at?`${when(d2.ended_at)} \xB7 ${d2.end_reason??"\u2014"}`:void 0]]}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Messages",String(r.message_count)],["Tool calls",d2?String(d2.tool_call_count):void 0],["Input",d2?`${fmt2(d2.input_tokens)} tok`:void 0],["Output",d2?`${fmt2(d2.output_tokens)} tok`:void 0],["Cache",d2?`${fmt2(d2.cache_read_tokens)} r / ${fmt2(d2.cache_write_tokens)} w`:void 0],["Reasoning",d2?`${fmt2(d2.reasoning_tokens)} tok`:void 0],["Cost",d2?cost(d2.estimated_cost_usd):void 0,theme.success]]}),hasLineage?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,children:"Lineage"})}),info.continuesFrom?$jsx("box",{height:1,onMouseDown:go(info.continuesFrom.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2190 continues from "}),$jsx("span",{fg:theme.accent,children:info.continuesFrom.title||info.continuesFrom.id})]})}):null,info.compressedTo?$jsx("box",{height:1,onMouseDown:go(info.compressedTo.id),children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2192 compressed to "}),$jsx("span",{fg:theme.accent,children:info.compressedTo.title||info.compressedTo.id})]})}):null,subs2>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" \u2387 spawned "}),$jsx("span",{fg:theme.text,children:String(subs2)}),$jsx("span",{fg:theme.textMuted,children:` subagent${subs2===1?"":"s"}`})]})}):null]}):null,!d2?$jsxs($Fragment2,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"(no local detail \u2014 state.db mismatch)"})})]}):null,$jsx("box",{height:1})]}),$jsx(Peek,{sid:r.id,total:r.message_count,peek:props.peek})]})})}),SearchDetail=import_react53.memo((props)=>{let theme=useTheme().theme,r=props.result,parts2=[],rest=r.snippet;while(rest.length){let start2=rest.indexOf(">>>");if(start2<0){parts2.push({text:rest,hi:!1});break}if(start2>0)parts2.push({text:rest.slice(0,start2),hi:!1});let end=rest.indexOf("<<<",start2+3);if(end<0){parts2.push({text:rest.slice(start2+3),hi:!0});break}parts2.push({text:rest.slice(start2+3,end),hi:!0}),rest=rest.slice(end+3)}return $jsx(TabShell,{title:"Search Match",hint:"",grow:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:r.title??"Untitled"})})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Source",badge(r.source)],["Model",r.model??"\u2014"],["Time",when(r.started_at)]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Snippet"})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:parts2.map((p,i)=>p.hi?$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:p.text})},i):$jsx("span",{fg:theme.text,children:p.text},i))})})]})})})}),HeaderRow=import_react53.memo(()=>{let fg2=useTheme().theme.textMuted;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:8,fg:fg2,bold:!0,children:"Start"}),$jsx(Col,{w:10,fg:fg2,bold:!0,right:!0,children:"Active"}),$jsx(Col,{w:7,fg:fg2,bold:!0,right:!0,children:"Msgs"}),$jsx("box",{width:3})]})}),Item=import_react53.memo((props)=>{let theme=useTheme().theme,{row:r,idx:i}=props,[x2,setX]=import_react53.useState(!1),active=r.detail?.last_active??r.detail?.ended_at??null,leader=props.indent?"\u2514\u2500":props.selected?"\u25B8 ":" ",muted=props.indent&&!props.selected?theme.textMuted:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:muted??theme.text,children:leader}),$jsx(Marquee,{grow:!0,active:props.selected,fg:props.selected?theme.accent:muted??theme.text,bold:props.selected,children:r.title||"Untitled"}),$jsx(Col,{w:9,fg:muted??theme.info,children:badge(r.source??"")}),$jsx(Col,{w:8,fg:theme.textMuted,children:stamp(r.started_at)}),$jsx(Col,{w:10,fg:theme.textMuted,right:!0,children:active?ago(active):"\u2014"}),$jsx(Col,{w:7,fg:theme.textMuted,right:!0,children:String(r.message_count)}),props.indent?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{children:$jsx("span",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})})]})}),SearchHeaderRow=import_react53.memo(()=>{let fg2=useTheme().theme.textMuted;return $jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:fg2,children:" "}),$jsx(Col,{grow:!0,fg:fg2,bold:!0,children:"Title"}),$jsx(Col,{w:9,fg:fg2,bold:!0,children:"Source"}),$jsx(Col,{w:10,fg:fg2,bold:!0,children:"When"}),$jsx(Col,{w:20,fg:fg2,bold:!0,children:"Model"})]})}),SearchItem=import_react53.memo((props)=>{let theme=useTheme().theme,{result:r,idx:i}=props;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseDown:()=>props.onActivate(i),onMouseMove:()=>props.onHover(i),children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,bold:props.selected,children:r.title??"Untitled"}),$jsx(Col,{w:9,fg:theme.info,children:badge(r.source)}),$jsx(Col,{w:10,fg:theme.textMuted,children:ago(r.started_at)}),$jsx(Col,{w:20,fg:theme.textMuted,children:r.model??"\u2014"})]})}),last={rows:[],kids:new Map},Sessions=import_react53.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),dims=useTerminalDimensions(),cached2=props.io==null,io2={list:props.io?.list??io.roots,search:props.io?.search??io.search,subagents:props.io?.subagents??io.children,lineage:props.io?.lineage??io.lineage,peek:props.io?.peek??io.peek,remove:props.io?.remove??remove,rename:props.io?.rename??rename},[rows2,setRows]=import_react53.useState(cached2?last.rows:[]),[warn,setWarn]=import_react53.useState(""),[pending2,setPending]=import_react53.useState(rows2.length===0),[anchor,setAnchor]=import_react53.useState(null),[searching,setSearching]=import_react53.useState(!1),[query,setQuery]=import_react53.useState(""),[results,setResults]=import_react53.useState([]),[searchSel,setSearchSel]=import_react53.useState(0),[kids,setKids]=import_react53.useState(cached2?last.kids:new Map),debounce=import_react53.useRef(null),vscroll=import_react53.useRef(null),anchored=anchor&&rows2.find((r)=>r.id===anchor.id),owner=anchor?.indent?rows2.find((r)=>kids.get(r.id)?.some((c)=>c.id===anchor.id)):(anchored?.detail?.subagent_count??0)>0?anchored:void 0,visible=rows2.flatMap((r,i)=>r.id===owner?.id?[{row:r,indent:!1,parentIdx:i},...(kids.get(r.id)??[]).map((c)=>({row:c,indent:!0,parentIdx:i}))]:[{row:r,indent:!1,parentIdx:i}]),sel=anchor?Math.max(0,visible.findIndex((v2)=>v2.row.id===anchor.id&&v2.indent===anchor.indent)):0,live=import_react53.useRef({rows:rows2,visible,anchor,results,searching,onSwitch:props.onSwitch,currentId:props.currentId});live.current={rows:rows2,visible,anchor,results,searching,onSwitch:props.onSwitch,currentId:props.currentId};let setSel=import_react53.useCallback((arg)=>{let cur=live.current,prev=cur.visible.findIndex((v3)=>v3.row.id===cur.anchor?.id&&v3.indent===cur.anchor.indent),n=typeof arg==="function"?arg(Math.max(0,prev)):arg,v2=cur.visible[Math.max(0,Math.min(cur.visible.length-1,n))];if(v2)setAnchor({id:v2.row.id,indent:v2.indent})},[]),LIMIT=2000,toRow2=(d2)=>({id:d2.id,title:d2.title??"",preview:d2.lastMessage??"",message_count:d2.message_count,started_at:d2.started_at,source:d2.sessionSource,detail:d2}),load3=import_react53.useCallback(async()=>{setPending(!0);let rpc=gw.request("session.list",{limit:LIMIT}).then((r2)=>({ok:!0,v:r2})).catch((e)=>({ok:!1,e})),disk=await Promise.resolve(io2.list(LIMIT)).catch(()=>[]),local=new Map(disk.map((r2)=>[r2.id,r2])),diskRows=disk.filter((d2)=>d2.message_count>0).map(toRow2);if(setRows(diskRows),cached2)last.rows=diskRows;let fillKids=async(list)=>{let ps=list.filter((r2)=>(r2.detail?.subagent_count??0)>0),cs=await Promise.all(ps.map((r2)=>io2.subagents(r2.id))),m2=new Map(ps.map((r2,i)=>[r2.id,cs[i].map(toRow2)]));if(setKids(m2),cached2)last.kids=m2};fillKids(diskRows);let r=await rpc;if(r.ok&&r.v.sessions?.length){let seen=new Set(diskRows.map((s)=>s.id)),merged=[...diskRows,...r.v.sessions.filter((s)=>(s.message_count??0)>0&&!seen.has(s.id)).map((s)=>({...s,detail:local.get(s.id)}))].sort((a,b2)=>b2.started_at-a.started_at);if(setRows(merged),cached2)last.rows=merged;fillKids(merged)}setPending(!1),setWarn(!r.ok?local.size?`gateway session.list failed (${r.e.message}) \u2014 listing state.db directly; rows may not resume`:r.e.message:"")},[gw]);import_react53.useEffect(()=>{load3()},[load3]),import_react53.useEffect(()=>{if(!anchor&&rows2.length)setAnchor({id:rows2[0].id,indent:!1})},[rows2,anchor]),import_react53.useEffect(()=>{if(!searching||!query.trim()){setResults([]);return}return debounce.current=setTimeout(()=>{Promise.resolve(io2.search(query,30)).then((r)=>{setResults(r),setSearchSel(0)})},150),()=>{if(debounce.current)clearTimeout(debounce.current)}},[query,searching]);let rowHover=import_react53.useCallback((i)=>{live.current.searching?setSearchSel(i):setSel(i)},[setSel]),rowActivate=import_react53.useCallback((i)=>{let l=live.current;l.searching?setSearchSel(i):setSel(i);let hit=l.searching?l.results[i]:l.visible[i]?.row,id=l.searching?hit?.session_id:hit?.id;if(!id||!l.onSwitch)return;if(id===l.currentId)return l.onSwitch(id);let title=hit?.title||"Untitled",n=l.searching?void 0:hit.message_count;openConfirm(dialog,{title:"Load session?",body:`${trunc4(title,60)}${n!=null?` \xB7 ${n} msg${n===1?"":"s"}`:""}
|
|
4097
4105
|
|
|
4098
4106
|
Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(id)})},[dialog]),rowDelete=import_react53.useCallback((i)=>{let v2=live.current.visible[i];if(v2&&!v2.indent)confirmDeleteRef.current(v2.row)},[]),lineageSwitch=import_react53.useCallback((sid)=>{let l=live.current;if(!l.onSwitch)return;if(sid===l.currentId)return l.onSwitch(sid);openConfirm(dialog,{title:"Load session?",body:`Switch to ${trunc4(sid,24)}?
|
|
4099
4107
|
|
|
@@ -4144,13 +4152,13 @@ Usage:
|
|
|
4144
4152
|
`).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop2.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop2.popover,cursor:pop2.cursor,onCursor:pop2.setCursor,onSelect:select})}):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((q4,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,". ",trunc4(q4,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:["~",fmt3(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:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:ta,onContentChange:()=>setInput(ta.current?.plainText??""),onSubmit:submit,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder: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}),pop2.ghost&&props.focused&&rows3===1?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop2.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:label})]}),$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]})]})}));var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(a.text)]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":return{...state2,hasContent:!0,toolActive:!1,messages:appendText(state2.messages,a.chunk)};case"message.complete":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:finalize(state2.messages,a.text,a.usage)};case"tool.start":{let json2=a.preview&&/^\s*\{/.test(a.preview),part={type:"tool",id:a.id,name:a.name,args:json2?a.preview:"",status:"running",startedAt:Date.now(),preview:a.preview};return{...state2,toolActive:!0,hasContent:!1,messages:appendPart(state2.messages,part,!0)}}case"tool.progress":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:a.preview||p.preview}))};case"tool.generating":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:p.preview??"generating\u2026"}))};case"tool.complete":return{...state2,toolActive:!1,messages:updateToolById(state2.messages,a.id,(p)=>({...p,status:a.error?"error":"done",duration:p.startedAt?Date.now()-p.startedAt:void 0,preview:a.summary||a.inline_diff||p.preview,result:a.error||a.summary,diff:a.inline_diff}))};case"thinking":return{...state2,messages:upsertThinking(state2.messages,a.text,a.final)};case"subagent":return{...state2,messages:renderSubagent(state2.messages,a.event,a.payload)};case"prompt":{let part={type:"prompt",id:a.id,variant:a.req.variant,req:a.req};return{...state2,messages:appendPart(state2.messages,part,!0)}}case"prompt.answered":return{...state2,messages:updatePrompt(state2.messages,a.id,(p)=>({...p,answered:{label:a.label,ok:a.ok,at:Date.now()}}))};case"error":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:[...state2.messages,systemMessage(`Error: ${a.text}`)]};case"interrupt.notice":{let last3=state2.messages[state2.messages.length-1];if(last3?.role==="system"&&last3.parts[0]?.type==="text"&&last3.parts[0].content.includes(a.text))return state2;return{...state2,messages:[...state2.messages,systemMessage(a.text)]}}}}function userMessage(text2){return{id:mid(),role:"user",parts:[{type:"text",content:text2,streaming:!1}],timestamp:Date.now()/1000}}function systemMessage(text2){return{id:mid(),role:"system",parts:[{type:"text",content:text2,streaming:!1}],timestamp:Date.now()/1000}}function flatten3(text2){if(typeof text2==="string")return text2;if(!Array.isArray(text2))return"";let out=[];for(let p of text2)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")out.push(p.text);return out.join(`
|
|
4145
4153
|
`)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:flatten3(r.text)})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,chunk){return withLastAssistant(messages,(m2)=>{let last3=m2.parts[m2.parts.length-1];if(last3?.type==="text"&&last3.streaming){let part={...last3,content:last3.content+chunk};return{...m2,parts:[...m2.parts.slice(0,-1),part]}}return{...m2,parts:[...m2.parts,{type:"text",key:pid(),content:chunk,streaming:!0}]}},()=>assistant([{type:"text",key:pid(),content:chunk,streaming:!0}]))}function appendPart(messages,part,close){return withLastAssistant(messages,(m2)=>({...m2,parts:[...close?seal(m2.parts):m2.parts,part]}),()=>assistant([part]))}function finalize(messages,final,usage){let last3=messages[messages.length-1];if(last3?.role==="assistant"){let tail=last3.parts[last3.parts.length-1],parts2=tail?.type==="text"&&tail.streaming?[...last3.parts.slice(0,-1),{...tail,content:final||tail.content,streaming:!1}]:final&&final!==joinText(last3.parts)?[...last3.parts,{type:"text",content:final,streaming:!1}]:seal(last3.parts);return[...messages.slice(0,-1),{...last3,parts:parts2,usage}]}if(!final)return messages;return[...messages,{...assistant([{type:"text",content:final,streaming:!1}]),usage}]}function joinText(parts2){return parts2.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function updateRunningTool(messages,name,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;for(let i=last3.parts.length-1;i>=0;i--){let p=last3.parts[i];if(p.type!=="tool"||p.status!=="running")continue;if(name&&p.name!==name)continue;let parts2=[...last3.parts];return parts2[i]=fn(p),[...messages.slice(0,-1),{...last3,parts:parts2}]}return messages}function updateToolById(messages,id,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;let parts2=last3.parts.map((p)=>p.type==="tool"&&p.id===id?fn(p):p);return[...messages.slice(0,-1),{...last3,parts:parts2}]}function updatePrompt(messages,id,fn){return messages.map((m2)=>{if(m2.role!=="assistant")return m2;if(!m2.parts.some((p)=>p.type==="prompt"&&p.id===id))return m2;return{...m2,parts:m2.parts.map((p)=>p.type==="prompt"&&p.id===id?fn(p):p)}})}function upsertThinking(messages,text2,final){return withLastAssistant(messages,(m2)=>{let idx3=m2.parts.findIndex((p)=>p.type==="thinking");if(idx3>=0){let prev=m2.parts[idx3],content=final?prev.content.trim()||text2:prev.content+text2,parts2=[...m2.parts];return parts2[idx3]={...prev,content,streaming:!final},{...m2,parts:parts2}}return{...m2,parts:[{type:"thinking",key:pid(),content:text2,streaming:!final},...m2.parts]}},()=>assistant([{type:"thinking",key:pid(),content:text2,streaming:!final}]))}function renderSubagent(messages,event,p){let id=p.subagent_id?`sub-${p.subagent_id}`:`sub-${p.task_index}`;if(event==="start"){let part={type:"tool",id,name:"delegate_task",args:"",status:"running",startedAt:Date.now(),preview:p.goal,goal:p.goal,depth:p.depth??0,trail:[]};return appendPart(messages,part,!0)}if(event==="tool"&&p.tool_name)return updateToolById(messages,id,(t2)=>({...t2,trail:[...t2.trail??[],{name:p.tool_name,preview:p.tool_preview}],preview:p.tool_preview?`${p.tool_name}: ${p.tool_preview}`:p.tool_name}));if(event==="complete"){let tokens3=(p.input_tokens??0)+(p.output_tokens??0),extra=tokens3?` \xB7 ${(tokens3/1000).toFixed(1)}k tok`:"";return updateToolById(messages,id,(t2)=>({...t2,status:p.status==="failed"?"error":"done",duration:p.duration_seconds?p.duration_seconds*1000:t2.startedAt?Date.now()-t2.startedAt:void 0,result:p.summary?p.summary+extra:void 0,preview:t2.goal??t2.preview}))}return updateToolById(messages,id,(t2)=>({...t2,preview:p.text??t2.preview}))}init_perf();function count3(o){return o?Object.values(o).reduce((n,v2)=>n+v2.length,0):0}function mapEvent(ev,side){switch(ev.type){case"gateway.ready":if(side.onReady?.(),ev.payload?.skin)side.onSkin?.(ev.payload.skin);return null;case"session.info":{let si=ev.payload;side.onSessionInfo?.(si);let label=si.model?`Connected \u2014 ${si.model} \xB7 ${count3(si.tools)} tools \xB7 ${count3(si.skills)} skills`:"Connected to Hermes";if(si.credential_warning)side.onStatus?.(si.credential_warning);return{kind:"system",text:label}}case"message.start":return count("stream:start"),mem("stream-start"),{kind:"message.start"};case"message.delta":{let chunk=ev.payload?.text??"";if(!chunk)return null;return count("stream:chunk"),{kind:"message.delta",chunk}}case"message.complete":{count("stream:done"),mem("stream-done");let p=ev.payload;if(p?.usage)side.onUsage?.(p.usage);if(side.onTurnComplete?.(),p?.status==="error")return{kind:"error",text:p.text||"request failed \u2014 see messages above"};if(p?.status==="interrupted")return{kind:"message.complete",text:(p.text||"")+`
|
|
4146
4154
|
|
|
4147
|
-
*[interrupted]*`,usage:p?.usage};return{kind:"message.complete",text:p?.text??void 0,usage:p?.usage}}case"tool.start":return{kind:"tool.start",id:ev.payload.tool_id,name:ev.payload.name??"unknown",preview:ev.payload.context};case"tool.progress":return{kind:"tool.progress",name:ev.payload.name,preview:ev.payload.preview};case"tool.generating":return{kind:"tool.generating",name:ev.payload.name};case"tool.complete":return{kind:"tool.complete",id:ev.payload.tool_id,summary:ev.payload.summary,error:ev.payload.error,inline_diff:ev.payload.inline_diff};case"thinking.delta":return side.onStatus?.(ev.payload?.text??""),null;case"reasoning.delta":case"reasoning.available":{let text2=ev.payload?.text;if(!text2)return null;return{kind:"thinking",text:text2,final:ev.type==="reasoning.available"}}case"subagent.start":case"subagent.thinking":case"subagent.tool":case"subagent.progress":case"subagent.complete":{let sub2=ev.type.slice(9);return record(sub2,ev.payload),{kind:"subagent",event:sub2,payload:ev.payload}}case"error":return{kind:"error",text:ev.payload?.message??"Unknown error"};case"clarify.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"clarify",...ev.payload}};case"approval.request":return{kind:"prompt",id:`approval-${pid()}`,req:{variant:"approval",...ev.payload}};case"sudo.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"sudo",...ev.payload}};case"secret.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"secret",...ev.payload}};case"background.complete":return side.onBackground?.(ev.payload.task_id,ev.payload.text),null;case"review.summary":{let text2=String(ev.payload?.text??"").trim();if(!text2)return null;return{kind:"system",text:text2}}case"btw.complete":return side.onBtw?.(ev.payload.text),null;case"gateway.stderr":{let line3=ev.payload.line;if(/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i.test(line3))return{kind:"system",text:line3.slice(0,200)};return null}case"skin.changed":return side.onSkin?.(ev.payload),null;case"gateway.start_timeout":return{kind:"error",text:`gateway startup timed out (${ev.payload?.python??"python"} @ ${ev.payload?.cwd??"?"})`};case"gateway.protocol_error":return{kind:"system",text:`protocol error: ${ev.payload?.preview??"?"}`};case"browser.progress":{let text2=ev.payload?.message??"";if(!text2)return null;return ev.payload?.level==="error"?{kind:"error",text:text2}:{kind:"system",text:`\xB7 ${text2}`}}case"status.update":{let kind=ev.payload?.kind,text2=ev.payload?.text??"";if(side.onStatus?.(text2),!kind||kind==="status")return null;return{kind:"system",text:text2}}}return null}var import_react104=__toESM(require_react_production(),1);init_sessions_db();function useSession(){let gw=useGateway(),resume=import_react104.useCallback(async(sid)=>{let res=await gw.request("session.resume",{session_id:
|
|
4155
|
+
*[interrupted]*`,usage:p?.usage};return{kind:"message.complete",text:p?.text??void 0,usage:p?.usage}}case"tool.start":return{kind:"tool.start",id:ev.payload.tool_id,name:ev.payload.name??"unknown",preview:ev.payload.context};case"tool.progress":return{kind:"tool.progress",name:ev.payload.name,preview:ev.payload.preview};case"tool.generating":return{kind:"tool.generating",name:ev.payload.name};case"tool.complete":return{kind:"tool.complete",id:ev.payload.tool_id,summary:ev.payload.summary,error:ev.payload.error,inline_diff:ev.payload.inline_diff};case"thinking.delta":return side.onStatus?.(ev.payload?.text??""),null;case"reasoning.delta":case"reasoning.available":{let text2=ev.payload?.text;if(!text2)return null;return{kind:"thinking",text:text2,final:ev.type==="reasoning.available"}}case"subagent.start":case"subagent.thinking":case"subagent.tool":case"subagent.progress":case"subagent.complete":{let sub2=ev.type.slice(9);return record(sub2,ev.payload),{kind:"subagent",event:sub2,payload:ev.payload}}case"error":return{kind:"error",text:ev.payload?.message??"Unknown error"};case"clarify.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"clarify",...ev.payload}};case"approval.request":return{kind:"prompt",id:`approval-${pid()}`,req:{variant:"approval",...ev.payload}};case"sudo.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"sudo",...ev.payload}};case"secret.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"secret",...ev.payload}};case"background.complete":return side.onBackground?.(ev.payload.task_id,ev.payload.text),null;case"review.summary":{let text2=String(ev.payload?.text??"").trim();if(!text2)return null;return{kind:"system",text:text2}}case"btw.complete":return side.onBtw?.(ev.payload.text),null;case"gateway.stderr":{let line3=ev.payload.line;if(/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i.test(line3))return{kind:"system",text:line3.slice(0,200)};return null}case"skin.changed":return side.onSkin?.(ev.payload),null;case"gateway.start_timeout":return{kind:"error",text:`gateway startup timed out (${ev.payload?.python??"python"} @ ${ev.payload?.cwd??"?"})`};case"gateway.protocol_error":return{kind:"system",text:`protocol error: ${ev.payload?.preview??"?"}`};case"browser.progress":{let text2=ev.payload?.message??"";if(!text2)return null;return ev.payload?.level==="error"?{kind:"error",text:text2}:{kind:"system",text:`\xB7 ${text2}`}}case"status.update":{let kind=ev.payload?.kind,text2=ev.payload?.text??"";if(side.onStatus?.(text2),!kind||kind==="status")return null;return{kind:"system",text:text2}}}return null}var import_react104=__toESM(require_react_production(),1);init_sessions_db();var normalize2=(sid)=>sid.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),resume=import_react104.useCallback(async(sid)=>{let target=normalize2(sid),res=await gw.request("session.resume",{session_id:target}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages}},[gw]),create=import_react104.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),res.session_id},[gw]),close=import_react104.useCallback(async(sid)=>{if(!sid)return;try{await gw.request("session.close",{session_id:sid})}catch{}},[gw]),boot2=import_react104.useCallback(async(launch)=>{let fresh=async(note)=>({id:await create(),messages:[],note});if(launch.mode==="resume"){let target=launch.sid??lastReal()?.id;if(!target)return fresh("no prior session to resume \u2014 starting fresh");try{return await resume(target)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh(`resume ${target} failed: ${msg} \u2014 starting fresh`)}}let last3=get("lastSessionId"),tip2=last3?chainTip(last3):null;if(tip2&&byId(tip2)?.message_count===0)try{return await resume(tip2)}catch{}return fresh()},[create,resume]),interrupt=import_react104.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react104.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react104.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react104.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react104.useMemo(()=>({boot:boot2,create,resume,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,close,interrupt,branch2,compress,undo])}var import_react106=__toESM(require_react_production(),1);import{tmpdir}from"os";import{join as join15}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=join15(tmpdir(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text2=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text2.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text2.trim()||void 0}function redraw(renderer){resolveRenderLib().clearTerminal(renderer.rendererPtr),renderer.currentRenderBuffer.clear(RGBA.fromValues(0,0,0,0)),renderer.requestRender()}var INTERRUPT_MS=5000,DOUBLE_TAB_MS=400;function useAppKeys(o){let renderer=useRenderer(),keys=useKeys(),lastEsc=import_react106.useRef(0),lastTab=import_react106.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react106.useEffect(()=>{let found=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found.length===0)return;let first=found[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found.length>1?` (+${found.length-1} more)`:""))},[keys.table]),useKeyboard((key2)=>{let c=o.composer.current;if(keys.match("input.clear",key2)&&c&&!c.isEmpty()){c.set(""),key2.stopPropagation();return}if(keys.match("app.exit",key2))return o.onQuit();if(keys.match("app.suspend",key2)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key2)){redraw(renderer),key2.stopPropagation();return}if(keys.match("app.sidebar",key2)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(keys.match("queue.flush",key2)&&o.streaming&&o.queued>0){o.onFlushQueue(),key2.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key2.ctrl&&!key2.meta&&key2.eventType!=="release"){if(o.onPromptKey(key2)){key2.stopPropagation();return}}if(keys.match("editor.open",key2)&&!o.streaming){let seed=c?.value()??"";editInEditor(renderer,seed).then((out)=>{if(out===void 0){if(!process.env.VISUAL&&!process.env.EDITOR)o.onNotice("Set $EDITOR or $VISUAL to use the external editor");return}c?.set(out),o.setFocusRegion("input")});return}if(keys.match("tab.prev",key2)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key2)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.leader&&!key2.ctrl&&!key2.meta&&!key2.shift&&key2.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key2.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key2.stopPropagation();return}}if(key2.meta&&!key2.ctrl&&!key2.shift&&key2.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key2.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key2.stopPropagation();return}}if(c?.popOpen()){if(key2.name==="escape")return c.popCancel();if(key2.name==="up"){c.popNav(-1),key2.stopPropagation();return}if(key2.name==="down"){c.popNav(1),key2.stopPropagation();return}if(key2.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key2)&&!o.streaming){if(o.tab===o.chatTab){o.setFocusRegion((r)=>r==="input"?"content":"input");return}if(o.focusRegion==="input"){o.setFocusRegion("content");return}let now2=Date.now();if(now2-lastTab.current<DOUBLE_TAB_MS)o.setFocusRegion("input"),lastTab.current=0,key2.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key2)){if(!o.streaming&&o.onEscape?.())return;if(o.streaming){let now2=Date.now();if(now2-lastEsc.current<INTERRUPT_MS){o.onInterrupt(),lastEsc.current=0;return}lastEsc.current=now2,o.onInterruptNotice();return}if(o.tab===o.chatTab&&o.focusRegion==="content")o.setFocusRegion("input");return}if(keys.match("reply.copy",key2))return o.onCopyLast();if(keys.match("clipboard.attach",key2)){o.onAttachClipboard(),key2.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if(key2.name==="up")return void c?.historyUp();if(key2.name==="down")return void c?.historyDown();if(key2.name==="backspace"&&!key2.ctrl&&!key2.meta&&c?.isEmpty()&&o.onDetachLast()){key2.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key2.ctrl&&!key2.meta&&key2.eventType!=="release"){if(key2.name.length===1&&key2.name!==" "){let ch=key2.shift&&/[a-z]/.test(key2.name)?key2.name.toUpperCase():key2.name;o.setFocusRegion("input"),c?.insert(ch),key2.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY&&sid){let t2=title?` \u2014 ${title.slice(0,60)}`:"";writeSync(1,`
|
|
4148
4156
|
continue herm --resume ${sid}${t2}
|
|
4149
4157
|
|
|
4150
|
-
`)}process.exit(0)}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache2.clear(),resetKanban(),reload(),home2.reset()}var import_react107=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react107.useState(p.seconds);import_react107.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)=>{let pref=(get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal;if(toast.show({variant:"success",title:"Goal complete",message:head,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),act(s.goal)}).catch(()=>{})}}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),cmd=useCommand(),toast=useToast(),renderer=useRenderer(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react110.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react110.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react110.useState(!1),[sid,setSid]=import_react110.useState(""),sidRef=import_react110.useRef(sid);sidRef.current=sid;let[tab,setTab]=import_react110.useState(CHAT_TAB),[hideSidebar,setHideSidebar]=import_react110.useState(!1),[usage,setUsage]=import_react110.useState(void 0),[info2,setInfo]=import_react110.useState(null),[title,setTitle]=import_react110.useState(""),[focusRegion,setFocusRegion]=import_react110.useState("input"),goToTab=import_react110.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react110.useState(""),[eikon,setEikon]=import_react110.useState(void 0),[queue,setQueue]=import_react110.useState([]),[busy,setBusy]=import_react110.useState("queue"),launchRef=import_react110.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react110.useState(launch.splash!==!1),[switching,setSwitching]=import_react110.useState(!1),summoned=import_react110.useRef(!1),[composing,setComposing]=import_react110.useState(!1),splashLast=import_react110.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),news=import_react110.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react110.useState([]),[cloudH,setCloudH]=import_react110.useState(CLOUD_MIN),[pick,setPick]=import_react110.useState(void 0),[skin,setSkin]=import_react110.useState(()=>deriveSkin(void 0)),inflight=import_react110.useRef(!1),interrupted=import_react110.useRef(!1),sessionStart=import_react110.useRef(Date.now()),composer2=import_react110.useRef(null),promptRef=import_react110.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react110.useRef(cmds);cmdsRef.current=cmds;let[errorPulse,setErrorPulse]=import_react110.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react110.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=pending(turn.messages),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react110.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react110.useRef(turn.streaming);import_react110.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react110.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react110.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react110.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react110.useRef(()=>{}),onEnqueue=import_react110.useCallback((t2)=>{if(busy==="steer"){gw.request("session.steer",{text:t2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"steered \u2014 lands on next tool result"});setQueue((q4)=>[...q4,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q4)=>[...q4,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q4)=>[t2,...q4]);setQueue((q4)=>[...q4,t2])},[busy,gw,toast]),onAttach=import_react110.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),reset=import_react110.useCallback(()=>{interrupted.current=!1,dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[]),newSession=import_react110.useCallback(async()=>{reset(),summoned.current=!0,setSplash(!0);try{setSid(await session.create()),sessionStart.current=Date.now()}catch{}},[reset,session]),switchSession=import_react110.useCallback(async(target)=>{reset(),summoned.current=!0,setSplash(!0),setSwitching(!0),goToTab(CHAT_TAB);try{let res=await session.resume(target);if(setSid(res.id),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});setSplash(!1),summoned.current=!1}catch(err){dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset,session,goToTab]),switchProfile=import_react110.useCallback((newHome,name)=>{rehome(newHome),reset(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset,goToTab,gwRestart,toast,gw]),runCompress=import_react110.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await session.compress();if(!r
|
|
4158
|
+
`)}process.exit(0)}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache2.clear(),resetKanban(),reload(),home2.reset()}var import_react107=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react107.useState(p.seconds);import_react107.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)=>{let pref=(get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal;if(toast.show({variant:"success",title:"Goal complete",message:head,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),act(s.goal)}).catch(()=>{})}}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),cmd=useCommand(),toast=useToast(),renderer=useRenderer(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react110.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react110.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react110.useState(!1),[sid,setSid]=import_react110.useState(""),sidRef=import_react110.useRef(sid);sidRef.current=sid;let[tab,setTab]=import_react110.useState(CHAT_TAB),[hideSidebar,setHideSidebar]=import_react110.useState(!1),[usage,setUsage]=import_react110.useState(void 0),[info2,setInfo]=import_react110.useState(null),[title,setTitle]=import_react110.useState(""),[focusRegion,setFocusRegion]=import_react110.useState("input"),goToTab=import_react110.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react110.useState(""),[eikon,setEikon]=import_react110.useState(void 0),[queue,setQueue]=import_react110.useState([]),[busy,setBusy]=import_react110.useState("queue"),launchRef=import_react110.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react110.useState(launch.splash!==!1),[switching,setSwitching]=import_react110.useState(!1),summoned=import_react110.useRef(!1),[composing,setComposing]=import_react110.useState(!1),splashLast=import_react110.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),news=import_react110.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react110.useState([]),[cloudH,setCloudH]=import_react110.useState(CLOUD_MIN),[pick,setPick]=import_react110.useState(void 0),[skin,setSkin]=import_react110.useState(()=>deriveSkin(void 0)),inflight=import_react110.useRef(!1),interrupted=import_react110.useRef(!1),sessionStart=import_react110.useRef(Date.now()),composer2=import_react110.useRef(null),promptRef=import_react110.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react110.useRef(cmds);cmdsRef.current=cmds;let[errorPulse,setErrorPulse]=import_react110.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react110.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=pending(turn.messages),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react110.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react110.useRef(turn.streaming);import_react110.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react110.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react110.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react110.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react110.useRef(()=>{}),onEnqueue=import_react110.useCallback((t2)=>{if(busy==="steer"){gw.request("session.steer",{text:t2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"steered \u2014 lands on next tool result"});setQueue((q4)=>[...q4,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q4)=>[...q4,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q4)=>[t2,...q4]);setQueue((q4)=>[...q4,t2])},[busy,gw,toast]),onAttach=import_react110.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),reset=import_react110.useCallback(()=>{interrupted.current=!1,dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[]),newSession=import_react110.useCallback(async()=>{let prev=sidRef.current;if(reset(),summoned.current=!0,setSplash(!0),prev)session.close(prev);try{setSid(await session.create()),sessionStart.current=Date.now()}catch{}},[reset,session]),switchSession=import_react110.useCallback(async(target)=>{let prev=sidRef.current;reset(),summoned.current=!0,setSplash(!0),setSwitching(!0),goToTab(CHAT_TAB);try{let res=await session.resume(target);if(setSid(res.id),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev);setSplash(!1),summoned.current=!1}catch(err){dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset,session,goToTab]),switchProfile=import_react110.useCallback((newHome,name)=>{rehome(newHome),reset(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset,goToTab,gwRestart,toast,gw]),runCompress=import_react110.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await session.compress();if(!r)return;if(r.info)setInfo(r.info);if(r.usage)setUsage(r.usage);if(Array.isArray(r.messages))dispatch({kind:"load",messages:transcriptToMessages(r.messages)});if(!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines2=[s.headline,s.token_line,s.note].filter(Boolean).join(`
|
|
4151
4159
|
`);if(lines2)dispatch({kind:"system",text:lines2});toast.show({variant:"success",message:s.headline??`Compressed ${r.before_messages??0}\u2192${r.after_messages??0} messages`})},[session,toast,dispatch]),loadEikon=import_react110.useCallback((path7)=>{Bun.file(path7).text().then((t2)=>setEikon(parseEikon(t2))).catch(()=>{})},[]),eikonPath=usePref("eikonPath");import_react110.useEffect(()=>{let p=eikonPath||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonPath,skin.skin?.name,loadEikon]);let pickEikon=import_react110.useCallback(()=>{openEikonPicker(dialog,(path7)=>set("eikonPath",path7))},[dialog]),applyTitle=import_react110.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{setTitle(r.title),dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),editTitle=import_react110.useCallback(()=>{openTextPrompt(dialog,{title:"Session Title",initial:title}).then((v2)=>{if(v2)applyTitle(v2)})},[dialog,title,applyTitle]),turnsFrom=(m2)=>{let at=turn.messages.findIndex((x2)=>x2.id===m2.id);return at<0?0:turn.messages.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react110.useCallback(async(m2)=>{if(turn.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),at=turn.messages.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):turn.messages.slice(0,at)}),composer2.current?.set(text2),setFocusRegion("input")},[turn.streaming,turn.messages,gw]),fork=import_react110.useCallback(async(m2)=>{if(turn.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}`})},[turn.streaming,turn.messages,gw,toast,switchSession]),msgMenu=import_react110.useCallback((m2)=>{if(turn.streaming)return;openMessage(dialog,m2,{rewind,fork})},[turn.streaming,dialog,rewind,fork]),attachClipboard=import_react110.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_react110.useRef(()=>{}),slash=import_react110.useCallback((c,arg="")=>{if(c.target==="local")switch(c.name){case"clear":dispatch({kind:"reset"});return;case"new":newSession();return;case"theme":openThemePicker(dialog,themeCtx);return;case"help":dialog.replace($jsx(HelpDialog,{}));return;case"keys":openKeys(dialog);return;case"logs":openLogs(dialog);return;case"eikon":pickEikon();return;case"title":arg?applyTitle(arg):editTitle();return;case"rollback":openRollback(dialog,gw,toast);return;case"history":openHistory(dialog,gw);return;case"status":openStatus(dialog,info2,sid);return;case"usage":openUsage(dialog,gw);return;case"profile":openProfile(dialog);return;case"chafa":if(!arg.trim()){toast.show({variant:"info",message:"usage: /chafa <path>"});return}openChafa(dialog,arg.trim());return;case"splash":summoned.current=!0,setSplash(!0);return;case"skin":{let name=arg.trim();if(!name){dispatch({kind:"system",text:`skin: ${skin.skin?.name??"\u2014"}
|
|
4152
|
-
${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikonPath",void 0),dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){switchSession(arg);return}goToTab(TAB_SLASH.sessions);return;case"branch":session.branch(arg||void 0).then((id)=>id?void switchSession(id):toast.show({variant:"error",message:"branch failed"}));return;case"compress":runCompress();return;case"undo":session.undo().then(()=>gw.request("session.history").then((r)=>dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}));return;case"retry":{let last3=[...turn.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}rewind(last3).then(()=>sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,sid,title);return;case"queue":if(!arg){dispatch({kind:"system",text:`${queue.length} queued`});return}setQueue((q4)=>[...q4,arg]);return;case"copy":{let all=turn.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all.length):all.length,m2=all[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":gw.request("voice.toggle",{action:(arg||"status").toLowerCase()}).then((r)=>dispatch({kind:"system",text:`voice ${r.enabled?"on":"off"}${r.tts?" \xB7 tts on":""}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"compact":case"setup":dispatch({kind:"system",text:`/${c.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text2)=>gw.request("session.steer",{text:text2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text2)=>{if(text2)fire(text2)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c.target!=="gateway"||!ready)return;let jump=TAB_SLASH[c.name];if(jump!==void 0&&!arg){goToTab(jump);return}let full=`/${c.name}${arg?" "+arg:""}`;if(turn.streaming){setQueue((q4)=>[...q4,full]);return}dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c.name,arg}).then((d2)=>{if(d2.notice)dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c.name}`});return void sendRef.current(d2.message)}dispatch({kind:"system",text:`/${c.name}: unknown`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`}))})},[ready,turn.streaming,turn.messages,dialog,themeCtx,newSession,gw,pickEikon,editTitle,applyTitle,toast,info2,sid,title,switchSession,session,runCompress,rewind,renderer,attachClipboard,goToTab,queue.length,goalHook,skin]),send=import_react110.useCallback(async(raw)=>{let m2=raw.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve7(cmdsRef.current,name);if("hit"in r)return slash(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text2=raw;if(hasInterp(raw))setStatus("interpolating\u2026"),text2=await interpolate(gw,raw),setStatus("");interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text2].filter(Boolean).join(`
|
|
4160
|
+
${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikonPath",void 0),dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){switchSession(arg);return}goToTab(TAB_SLASH.sessions);return;case"branch":session.branch(arg||void 0).then((id)=>id?void switchSession(id):toast.show({variant:"error",message:"branch failed"}));return;case"compress":runCompress();return;case"undo":session.undo().then(()=>gw.request("session.history").then((r)=>dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}));return;case"retry":{let last3=[...turn.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}rewind(last3).then(()=>sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,sid,title,gw);return;case"queue":if(!arg){dispatch({kind:"system",text:`${queue.length} queued`});return}setQueue((q4)=>[...q4,arg]);return;case"copy":{let all=turn.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all.length):all.length,m2=all[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":gw.request("voice.toggle",{action:(arg||"status").toLowerCase()}).then((r)=>dispatch({kind:"system",text:`voice ${r.enabled?"on":"off"}${r.tts?" \xB7 tts on":""}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"compact":case"setup":dispatch({kind:"system",text:`/${c.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text2)=>gw.request("session.steer",{text:text2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text2)=>{if(text2)fire(text2)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c.target!=="gateway"||!ready)return;let jump=TAB_SLASH[c.name];if(jump!==void 0&&!arg){goToTab(jump);return}let full=`/${c.name}${arg?" "+arg:""}`;if(turn.streaming){setQueue((q4)=>[...q4,full]);return}dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c.name,arg}).then((d2)=>{if(d2.notice)dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c.name}`});return void sendRef.current(d2.message)}dispatch({kind:"system",text:`/${c.name}: unknown`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`}))})},[ready,turn.streaming,turn.messages,dialog,themeCtx,newSession,gw,pickEikon,editTitle,applyTitle,toast,info2,sid,title,switchSession,session,runCompress,rewind,renderer,attachClipboard,goToTab,queue.length,goalHook,skin]),send=import_react110.useCallback(async(raw)=>{let m2=raw.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve7(cmdsRef.current,name);if("hit"in r)return slash(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text2=raw;if(hasInterp(raw))setStatus("interpolating\u2026"),text2=await interpolate(gw,raw),setStatus("");interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text2].filter(Boolean).join(`
|
|
4153
4161
|
`):text2;dispatch({kind:"user",text:withMedia}),setAttachments([]),gw.request("prompt.submit",{text:text2}).catch(()=>{inflight.current=!1}),setTab(CHAT_TAB)},[gw,slash,attachments]);sendRef.current=send;let onSend=import_react110.useCallback((raw)=>{return setSplash(!1),send(raw)},[send]),onEmptyEnter=import_react110.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react110.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react110.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_react110.useCallback((i)=>{let item=queue[i];if(item===void 0)return;setQueue((q4)=>q4.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[queue]),copyLast=import_react110.useCallback(()=>{for(let i=turn.messages.length-1;i>=0;i--){let m2=turn.messages[i];if(m2.role!=="assistant")continue;let text2=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");if(!text2)continue;return process.stdout.write(`\x1B]52;c;${Buffer.from(text2).toString("base64")}\x07`),!0}return!1},[turn.messages]),deltas=import_react110.useRef({text:"",think:"",timer:null}),flush2=import_react110.useCallback(()=>{let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;if(d2.think)dispatch({kind:"thinking",text:d2.think,final:!1}),d2.think="";if(d2.text)dispatch({kind:"message.delta",chunk:d2.text}),d2.text=""},[]),STREAM_EVENTS=import_react110.useRef(new Set(["message.start","message.delta","reasoning.delta","reasoning.available","thinking.delta","tool.start","tool.progress","tool.generating"])).current,handle2=import_react110.useCallback((ev)=>{if(interrupted.current){if(STREAM_EVENTS.has(ev.type))return;if(ev.type==="status.update"&&ev.payload?.kind==="lifecycle")return}let action=mapEvent(ev,{onReady:()=>{session.boot(launchRef.current).then((r)=>{if(setSid(r.id),sessionStart.current=Date.now(),r.messages.length)dispatch({kind:"load",messages:r.messages});if(r.note)toast.show({variant:"info",message:r.note})})},onSessionInfo:(si)=>{if(setInfo(si),setReady(!0),si.session_id)setSid(si.session_id);let bad=(si.mcp_servers??[]).filter((s)=>!s.connected);if(bad.length)dispatch({kind:"system",text:`MCP: ${bad.length} server(s) failed to connect \u2014 ${bad.map((s)=>s.name+(s.error?` (${s.error})`:"")).join(", ")}`});gw.request("session.title").then((r)=>{if(setTitle(r.title??""),r.session_key)set("lastSessionId",r.session_key)}).catch(()=>{}),gw.request("config.get",{key:"busy"}).then((r)=>{let m2=r.value;if(m2==="queue"||m2==="steer"||m2==="interrupt")setBusy(m2)}).catch(()=>{})},onUsage:(u3)=>setUsage(u3),onTurnComplete:()=>{setStatus(""),flush(gw,sidRef.current),goalHook.check(sidRef.current)},onBackground:(tid,text2)=>{let head=text2.split(`
|
|
4154
4162
|
`)[0].slice(0,80);dispatch({kind:"system",text:`\u25F7 background task ${tid} complete \u2014 ${head}`}),toast.show({variant:"info",title:"Background task complete",message:head,duration:8000,action:{label:"view",run:()=>openAlert(dialog,`Background task ${tid}`,text2)}})},onBtw:(text2)=>{let head=text2.split(`
|
|
4155
|
-
`)[0].slice(0,80);dispatch({kind:"system",text:`\u25C8 btw \u2014 ${head}`}),toast.show({variant:"info",title:"btw",message:head,duration:8000,action:{label:"view",run:()=>openAlert(dialog,"btw",text2)}})},onStatus:(text2)=>setStatus(text2),onSkin:(s)=>setSkin(deriveSkin(s))});if(!action)return;let d2=deltas.current;if(action.kind==="message.delta"){if(d2.think)flush2();d2.text+=action.chunk,d2.timer??=setTimeout(flush2,16);return}if(action.kind==="thinking"&&!action.final){if(d2.text)flush2();d2.think+=action.text,d2.timer??=setTimeout(flush2,16);return}if(flush2(),action.kind==="error")setErrorPulse(!0);dispatch(action)},[session,dialog,toast,gw,flush2,goalHook]);useGatewayEvent(handle2),import_react110.useEffect(()=>cmd.register([{title:"Help",value:"help",action:"help.open",category:"General",onSelect:()=>dialog.replace($jsx(HelpDialog,{}))},{title:"Keybindings",value:"keys",description:"View & rebind shortcuts",category:"General",onSelect:()=>openKeys(dialog)},{title:"Gateway Logs",value:"logs",description:"Show gateway stderr",category:"General",onSelect:()=>openLogs(dialog)},{title:"Switch Theme",value:"theme",action:"theme.pick",category:"General",onSelect:()=>openThemePicker(dialog,themeCtx)},{title:"Switch Model",value:"model",action:"model.pick",category:"General",onSelect:()=>openModelPicker(dialog,gw)},{title:"Pick Avatar",value:"eikon",description:"Choose sidebar .eikon avatar",category:"General",onSelect:()=>pickEikon()},{title:"Rollback",value:"rollback",description:"Browse & restore checkpoints",category:"Session",onSelect:()=>openRollback(dialog,gw,toast)},{title:"History",value:"history",action:"session.timeline",category:"Session",onSelect:()=>openHistory(dialog,gw)},{title:"Status",value:"status",action:"status.open",category:"Info",onSelect:()=>openStatus(dialog,info2,sid)},{title:"Usage",value:"usage",description:"Tokens \xB7 context \xB7 cost",category:"Info",onSelect:()=>openUsage(dialog,gw)},{title:"Profile",value:"profile",description:"Active profile details",category:"Info",onSelect:()=>openProfile(dialog)},{title:"New Session",value:"new-session",action:"session.new",category:"Session",onSelect:()=>newSession()},{title:"Compress Session",value:"compress",action:"session.compress",category:"Session",onSelect:()=>runCompress()},{title:"Undo Last Turn",value:"undo",description:"Pop last user+assistant pair",category:"Session",onSelect:()=>session.undo()},{title:"Branch Session",value:"branch",description:"Fork the current conversation",category:"Session",onSelect:()=>session.branch()}]),[cmd,dialog,themeCtx,session,gw,toast,newSession,pickEikon,info2,sid,runCompress]);let doInterrupt=import_react110.useCallback(()=>{interrupted.current=!0;let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;d2.text="",d2.think="",session.interrupt()},[session]);intr.current=doInterrupt,useAppKeys({tab,tabMax:TAB_MAX,chatTab:CHAT_TAB,setTab,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:doInterrupt,queued:queue.length,onFlushQueue:doInterrupt,onQuit:()=>quit(renderer,sid,title),onInterruptNotice:()=>dispatch({kind:"interrupt.notice",text:"Press Escape again to interrupt"}),onCopyLast:()=>{copyLast()},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)});let state2=import_react110.useRef({tab,ready,streaming:turn.streaming,messages:turn.messages,sid,focusRegion});state2.current={tab,ready,streaming:turn.streaming,messages:turn.messages,sid,focusRegion},import_react110.useEffect(()=>{if(!enabled2)return;setBridge({tab:()=>state2.current.tab,setTab,send:(msg)=>{if(!state2.current.ready||state2.current.streaming)return;dispatch({kind:"user",text:msg}),gw.request("prompt.submit",{text:msg}).catch(()=>{}),setTab(CHAT_TAB)},ready:()=>state2.current.ready,streaming:()=>state2.current.streaming,messages:()=>state2.current.messages.length,session:()=>state2.current.sid,input:()=>composer2.current?.value()??"",setInput:(v2)=>composer2.current?.set(v2),focusRegion:()=>state2.current.focusRegion,setFocusRegion,renderer:()=>renderer,logs:(n)=>gw.tail(n)})},[gw,renderer]);let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react110.useCallback((id,label,ok)=>dispatch({kind:"prompt.answered",id,label,ok}),[]),promptWire=import_react110.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react110.useEffect(()=>{if(prompt&&tab!==CHAT_TAB)setTab(CHAT_TAB)},[prompt?.id]);let content=()=>{let inner=(()=>{switch(tab){case 0:return $jsx(Chat,{messages:turn.messages,streaming:turn.streaming,prompt:promptWire,cloud,cloudH,pick,onResize:setCloudH,onPick,onClose:closeCloud,onRewind:msgMenu});case 1:return $jsx(Context,{description:TABS[tab].description,messages:turn.messages,sessionStart:sessionStart.current,info:info2??void 0,focused:contentFocused});case 2:return $jsx(Sessions,{onSwitch:switchSession,currentId:sid,focused:contentFocused});case 3:return $jsx(Agents,{focused:contentFocused,sessionId:sid,onSwitchProfile:switchProfile});case 4:return $jsx(Analytics,{focused:contentFocused});case 5:return $jsx(Skills,{focused:contentFocused});case 6:return $jsx(Cron,{focused:contentFocused});case 7:return $jsx(Toolsets,{focused:contentFocused});case 8:return $jsx(Config,{focused:contentFocused});case 9:return $jsx(Env,{focused:contentFocused});case 10:return $jsx(Memory,{focused:contentFocused});case 11:return $jsx(Kanban,{focused:contentFocused});default:return null}})(),name=TABS[tab]?.name??"unknown";return $jsx(import_react110.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react110.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt;return $jsx(import_react110.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:TABS,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:info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,last:summoned.current?void 0:splashLast?{id:splashLast.id,title:splashLast.title}:void 0,composing,news,loading:switching||!info2}):null]}),$jsx("box",{flexShrink:0,zIndex:1,children:$jsx(Composer,{ref:composer2,focused:inputFocused,ready,streaming:turn.streaming,status,queue,attachments,cmds,onSend,onSlash:slash,onAttach,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})})]}),dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar?$jsx(import_react110.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]})]})})})};init_perf();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(HELP),process.exit(0);if(argv.includes("--version")||argv.includes("-v"))process.stdout.write(VERSION+`
|
|
4163
|
+
`)[0].slice(0,80);dispatch({kind:"system",text:`\u25C8 btw \u2014 ${head}`}),toast.show({variant:"info",title:"btw",message:head,duration:8000,action:{label:"view",run:()=>openAlert(dialog,"btw",text2)}})},onStatus:(text2)=>setStatus(text2),onSkin:(s)=>setSkin(deriveSkin(s))});if(!action)return;let d2=deltas.current;if(action.kind==="message.delta"){if(d2.think)flush2();d2.text+=action.chunk,d2.timer??=setTimeout(flush2,16);return}if(action.kind==="thinking"&&!action.final){if(d2.text)flush2();d2.think+=action.text,d2.timer??=setTimeout(flush2,16);return}if(flush2(),action.kind==="error")setErrorPulse(!0);dispatch(action)},[session,dialog,toast,gw,flush2,goalHook]);useGatewayEvent(handle2),import_react110.useEffect(()=>cmd.register([{title:"Help",value:"help",action:"help.open",category:"General",onSelect:()=>dialog.replace($jsx(HelpDialog,{}))},{title:"Keybindings",value:"keys",description:"View & rebind shortcuts",category:"General",onSelect:()=>openKeys(dialog)},{title:"Gateway Logs",value:"logs",description:"Show gateway stderr",category:"General",onSelect:()=>openLogs(dialog)},{title:"Switch Theme",value:"theme",action:"theme.pick",category:"General",onSelect:()=>openThemePicker(dialog,themeCtx)},{title:"Switch Model",value:"model",action:"model.pick",category:"General",onSelect:()=>openModelPicker(dialog,gw)},{title:"Pick Avatar",value:"eikon",description:"Choose sidebar .eikon avatar",category:"General",onSelect:()=>pickEikon()},{title:"Rollback",value:"rollback",description:"Browse & restore checkpoints",category:"Session",onSelect:()=>openRollback(dialog,gw,toast)},{title:"History",value:"history",action:"session.timeline",category:"Session",onSelect:()=>openHistory(dialog,gw)},{title:"Status",value:"status",action:"status.open",category:"Info",onSelect:()=>openStatus(dialog,info2,sid)},{title:"Usage",value:"usage",description:"Tokens \xB7 context \xB7 cost",category:"Info",onSelect:()=>openUsage(dialog,gw)},{title:"Profile",value:"profile",description:"Active profile details",category:"Info",onSelect:()=>openProfile(dialog)},{title:"New Session",value:"new-session",action:"session.new",category:"Session",onSelect:()=>newSession()},{title:"Compress Session",value:"compress",action:"session.compress",category:"Session",onSelect:()=>runCompress()},{title:"Undo Last Turn",value:"undo",description:"Pop last user+assistant pair",category:"Session",onSelect:()=>session.undo()},{title:"Branch Session",value:"branch",description:"Fork the current conversation",category:"Session",onSelect:()=>session.branch()}]),[cmd,dialog,themeCtx,session,gw,toast,newSession,pickEikon,info2,sid,runCompress]);let doInterrupt=import_react110.useCallback(()=>{interrupted.current=!0;let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;d2.text="",d2.think="",session.interrupt()},[session]);intr.current=doInterrupt,useAppKeys({tab,tabMax:TAB_MAX,chatTab:CHAT_TAB,setTab,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:doInterrupt,queued:queue.length,onFlushQueue:doInterrupt,onQuit:()=>quit(renderer,sid,title,gw),onInterruptNotice:()=>dispatch({kind:"interrupt.notice",text:"Press Escape again to interrupt"}),onCopyLast:()=>{copyLast()},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)});let state2=import_react110.useRef({tab,ready,streaming:turn.streaming,messages:turn.messages,sid,focusRegion});state2.current={tab,ready,streaming:turn.streaming,messages:turn.messages,sid,focusRegion},import_react110.useEffect(()=>{if(!enabled2)return;setBridge({tab:()=>state2.current.tab,setTab,send:(msg)=>{if(!state2.current.ready||state2.current.streaming)return;dispatch({kind:"user",text:msg}),gw.request("prompt.submit",{text:msg}).catch(()=>{}),setTab(CHAT_TAB)},ready:()=>state2.current.ready,streaming:()=>state2.current.streaming,messages:()=>state2.current.messages.length,session:()=>state2.current.sid,input:()=>composer2.current?.value()??"",setInput:(v2)=>composer2.current?.set(v2),focusRegion:()=>state2.current.focusRegion,setFocusRegion,renderer:()=>renderer,logs:(n)=>gw.tail(n)})},[gw,renderer]);let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react110.useCallback((id,label,ok)=>dispatch({kind:"prompt.answered",id,label,ok}),[]),promptWire=import_react110.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react110.useEffect(()=>{if(prompt&&tab!==CHAT_TAB)setTab(CHAT_TAB)},[prompt?.id]);let content=()=>{let inner=(()=>{switch(tab){case 0:return $jsx(Chat,{messages:turn.messages,streaming:turn.streaming,prompt:promptWire,cloud,cloudH,pick,onResize:setCloudH,onPick,onClose:closeCloud,onRewind:msgMenu});case 1:return $jsx(Context,{description:TABS[tab].description,messages:turn.messages,sessionStart:sessionStart.current,info:info2??void 0,focused:contentFocused});case 2:return $jsx(Sessions,{onSwitch:switchSession,currentId:sid,focused:contentFocused});case 3:return $jsx(Agents,{focused:contentFocused,sessionId:sid,onSwitchProfile:switchProfile});case 4:return $jsx(Analytics,{focused:contentFocused});case 5:return $jsx(Skills,{focused:contentFocused});case 6:return $jsx(Cron,{focused:contentFocused});case 7:return $jsx(Toolsets,{focused:contentFocused});case 8:return $jsx(Config,{focused:contentFocused});case 9:return $jsx(Env,{focused:contentFocused});case 10:return $jsx(Memory,{focused:contentFocused});case 11:return $jsx(Kanban,{focused:contentFocused});default:return null}})(),name=TABS[tab]?.name??"unknown";return $jsx(import_react110.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react110.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt;return $jsx(import_react110.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:TABS,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:info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,last:summoned.current?void 0:splashLast?{id:splashLast.id,title:splashLast.title}:void 0,composing,news,loading:switching||!info2}):null]}),$jsx("box",{flexShrink:0,zIndex:1,children:$jsx(Composer,{ref:composer2,focused:inputFocused,ready,streaming:turn.streaming,status,queue,attachments,cmds,onSend,onSlash:slash,onAttach,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})})]}),dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar?$jsx(import_react110.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]})]})})})};init_perf();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(HELP),process.exit(0);if(argv.includes("--version")||argv.includes("-v"))process.stdout.write(VERSION+`
|
|
4156
4164
|
`),process.exit(0);var launch=parseLaunch(argv),main2=async()=>{resetTerminalModes(),installExitResetHooks(),mem("pre-renderer");let prefs=load(),end=mark("renderer-init"),renderer=await createCliRenderer({exitOnCtrlC:!1,useMouse:prefs.mouse??!0,targetFps:prefs.targetFps??30,gatherStats:!1});end();let bump=()=>renderer.capabilities?.kitty_keyboard||process.stdout.isTTY&&process.stdout.write("\x1B[>4;2m");bump(),renderer.on("focus",bump),mem("post-renderer");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(),mem("post-first-render"),monitor(15000),start()};main2().catch(console.error);
|