import{d as e,u as t}from"./subsystem-BQ1073Mu.js";import{Cu as n,Ml as r,Si as i,Wa as a,an as o,gu as s,mu as c,qa as l,qs as u,xi as d,xu as f,yi as p}from"./model-selection-p21GBPS6.js";import{c as m,f as h}from"./agent-scope-DW6ZDCxj.js";import{E as g,c as _,l as v,r as y}from"./session-key-D3P0tf5P.js";import{a as b}from"./types.secrets-C-5U96pc.js";import{a as x}from"./chat-envelope-HVpKusFc.js";import{r as S,t as C}from"./tool-display-DBTvIf_I.js";import{a as w,i as ee}from"./commands-registry-WhMJX_G0.js";import{g as T,i as E,o as D,t as O}from"./call-_dlYen_W.js";import{n as k,t as A}from"./format-relative-B9pSIdGe.js";import{n as j}from"./usage-format-BWD8FJFL.js";import M from"chalk";import{spawn as te}from"node:child_process";import{randomUUID as N}from"node:crypto";import{Box as ne,CombinedAutocompleteProvider as re,Container as P,Editor as ie,Input as ae,Key as F,Loader as oe,Markdown as se,ProcessTerminal as ce,SelectList as le,SettingsList as I,Spacer as L,TUI as ue,Text as de,getEditorKeybindings as fe,isKeyRelease as pe,matchesKey as R,truncateToWidth as me}from"@mariozechner/pi-tui";import{highlight as z,supportsLanguage as B}from"cli-highlight";const V=[`on`,`off`],he=[`on`,`off`],ge=[`on`,`off`,`ask`,`full`],_e=[`mention`,`always`],ve=[`off`,`tokens`,`full`],ye={elev:`elevated`};function H(e){return t=>e.filter(e=>e.startsWith(t.toLowerCase())).map(e=>({value:e,label:e}))}function be(e){let t=e.replace(/^\//,``).trim();if(!t)return{name:``,args:``};let[n,...r]=t.split(/\s+/),i=n.toLowerCase();return{name:ye[i]??i,args:r.join(` `).trim()}}function xe(e={}){let t=s(e.provider,e.model),n=H(V),r=H(he),i=H(ve),a=H(ge),o=H(_e),c=[{name:`help`,description:`Show slash command help`},{name:`status`,description:`Show gateway status summary`},{name:`agent`,description:`Switch agent (or open picker)`},{name:`agents`,description:`Open agent picker`},{name:`session`,description:`Switch session (or open picker)`},{name:`sessions`,description:`Open session picker`},{name:`model`,description:`Set model (or open picker)`},{name:`models`,description:`Open model picker`},{name:`think`,description:`Set thinking level`,getArgumentCompletions:e=>t.filter(t=>t.startsWith(e.toLowerCase())).map(e=>({value:e,label:e}))},{name:`verbose`,description:`Set verbose on/off`,getArgumentCompletions:n},{name:`reasoning`,description:`Set reasoning on/off`,getArgumentCompletions:r},{name:`usage`,description:`Toggle per-response usage line`,getArgumentCompletions:i},{name:`elevated`,description:`Set elevated on/off/ask/full`,getArgumentCompletions:a},{name:`elev`,description:`Alias for /elevated`,getArgumentCompletions:a},{name:`activation`,description:`Set group activation`,getArgumentCompletions:o},{name:`abort`,description:`Abort active run`},{name:`new`,description:`Reset the session`},{name:`reset`,description:`Reset the session`},{name:`settings`,description:`Open settings`},{name:`exit`,description:`Exit the TUI`},{name:`quit`,description:`Exit the TUI`}],l=new Set(c.map(e=>e.name)),u=e.cfg?w(e.cfg):ee();for(let e of u){let t=e.textAliases.length>0?e.textAliases:[`/${e.key}`];for(let n of t){let t=n.replace(/^\//,``).trim();!t||l.has(t)||(l.add(t),c.push({name:t,description:e.description}))}}return c}function U(e={}){return[`Slash commands:`,`/help`,`/commands`,`/status`,`/agent <id> (or /agents)`,`/session <key> (or /sessions)`,`/model <provider/model> (or /models)`,`/think <${c(e.provider,e.model,`|`)}>`,`/verbose <on|off>`,`/reasoning <on|off>`,`/usage <off|tokens|full>`,`/elevated <on|off|ask|full>`,`/elev <on|off|ask|full>`,`/activation <mention|always>`,`/new or /reset`,`/abort`,`/settings`,`/exit`].join(`
`)}function Se(e,t=!1){return t?{keyword:M.hex(`#AF00DB`),built_in:M.hex(`#267F99`),type:M.hex(`#267F99`),literal:M.hex(`#0000FF`),number:M.hex(`#098658`),string:M.hex(`#A31515`),regexp:M.hex(`#811F3F`),symbol:M.hex(`#098658`),class:M.hex(`#267F99`),function:M.hex(`#795E26`),title:M.hex(`#795E26`),params:M.hex(`#001080`),comment:M.hex(`#008000`),doctag:M.hex(`#008000`),meta:M.hex(`#001080`),"meta-keyword":M.hex(`#AF00DB`),"meta-string":M.hex(`#A31515`),section:M.hex(`#795E26`),tag:M.hex(`#800000`),name:M.hex(`#001080`),attr:M.hex(`#C50000`),attribute:M.hex(`#C50000`),variable:M.hex(`#001080`),bullet:M.hex(`#795E26`),code:M.hex(`#A31515`),emphasis:M.italic,strong:M.bold,formula:M.hex(`#AF00DB`),link:M.hex(`#267F99`),quote:M.hex(`#008000`),addition:M.hex(`#098658`),deletion:M.hex(`#A31515`),"selector-tag":M.hex(`#800000`),"selector-id":M.hex(`#800000`),"selector-class":M.hex(`#800000`),"selector-attr":M.hex(`#800000`),"selector-pseudo":M.hex(`#800000`),"template-tag":M.hex(`#AF00DB`),"template-variable":M.hex(`#001080`),default:e}:{keyword:M.hex(`#C586C0`),built_in:M.hex(`#4EC9B0`),type:M.hex(`#4EC9B0`),literal:M.hex(`#569CD6`),number:M.hex(`#B5CEA8`),string:M.hex(`#CE9178`),regexp:M.hex(`#D16969`),symbol:M.hex(`#B5CEA8`),class:M.hex(`#4EC9B0`),function:M.hex(`#DCDCAA`),title:M.hex(`#DCDCAA`),params:M.hex(`#9CDCFE`),comment:M.hex(`#6A9955`),doctag:M.hex(`#608B4E`),meta:M.hex(`#9CDCFE`),"meta-keyword":M.hex(`#C586C0`),"meta-string":M.hex(`#CE9178`),section:M.hex(`#DCDCAA`),tag:M.hex(`#569CD6`),name:M.hex(`#9CDCFE`),attr:M.hex(`#9CDCFE`),attribute:M.hex(`#9CDCFE`),variable:M.hex(`#9CDCFE`),bullet:M.hex(`#D7BA7D`),code:M.hex(`#CE9178`),emphasis:M.italic,strong:M.bold,formula:M.hex(`#C586C0`),link:M.hex(`#4EC9B0`),quote:M.hex(`#6A9955`),addition:M.hex(`#B5CEA8`),deletion:M.hex(`#F44747`),"selector-tag":M.hex(`#D7BA7D`),"selector-id":M.hex(`#D7BA7D`),"selector-class":M.hex(`#D7BA7D`),"selector-attr":M.hex(`#D7BA7D`),"selector-pseudo":M.hex(`#D7BA7D`),"template-tag":M.hex(`#C586C0`),"template-variable":M.hex(`#9CDCFE`),default:e}}const Ce=[0,95,135,175,215,255];function we(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Te(e,t,n){let r=we(e),i=we(t),a=we(n);return .2126*r+.7152*i+.0722*a}function Ee(e){return Te(Number.parseInt(e.slice(1,3),16),Number.parseInt(e.slice(3,5),16),Number.parseInt(e.slice(5,7),16))}function W(e,t){let n=Ee(t),r=Math.max(e,n),i=Math.min(e,n);return(r+.05)/(i+.05)}function De(e,t,n){let r=Te(e,t,n);return W(r,`#1E1E1E`)>=W(r,`#E8E3D5`)}function Oe(){let e=process.env.OPENCLAW_THEME?.toLowerCase();if(e===`light`)return!0;if(e===`dark`)return!1;let t=process.env.COLORFGBG;if(t&&t.length<=64){let e=t.lastIndexOf(`;`),n=Number.parseInt(e>=0?t.slice(e+1):t,10);if(n>=0&&n<=255){if(n<=15)return n===7||n===15;if(n>=232)return n>=244;let e=n-16,t=Ce[e%6],r=Ce[Math.floor(e/6)%6],i=Ce[Math.floor(e/36)];return De(i,r,t)}}return!1}const ke=Oe(),G=ke?{text:`#1E1E1E`,dim:`#5B6472`,accent:`#B45309`,accentSoft:`#C2410C`,border:`#5B6472`,userBg:`#F3F0E8`,userText:`#1E1E1E`,systemText:`#4B5563`,toolPendingBg:`#EFF6FF`,toolSuccessBg:`#ECFDF5`,toolErrorBg:`#FEF2F2`,toolTitle:`#B45309`,toolOutput:`#374151`,quote:`#1D4ED8`,quoteBorder:`#2563EB`,code:`#92400E`,codeBlock:`#F9FAFB`,codeBorder:`#92400E`,link:`#047857`,error:`#DC2626`,success:`#047857`}:{text:`#E8E3D5`,dim:`#7B7F87`,accent:`#F6C453`,accentSoft:`#F2A65A`,border:`#3C414B`,userBg:`#2B2F36`,userText:`#F3EEE0`,systemText:`#9BA3B2`,toolPendingBg:`#1F2A2F`,toolSuccessBg:`#1E2D23`,toolErrorBg:`#2F1F1F`,toolTitle:`#F6C453`,toolOutput:`#E1DACB`,quote:`#8CC8FF`,quoteBorder:`#3B4D6B`,code:`#F0C987`,codeBlock:`#1E232A`,codeBorder:`#343A45`,link:`#7DD3A5`,error:`#F97066`,success:`#7DD3A5`},K=e=>t=>M.hex(e)(t),q=e=>t=>M.bgHex(e)(t),J=Se(K(G.code),ke);function Y(e,t){try{return z(e,{language:t&&B(t)?t:void 0,theme:J,ignoreIllegals:!0}).split(`
`)}catch{return e.split(`
`).map(e=>K(G.code)(e))}}const X={fg:K(G.text),assistantText:e=>e,dim:K(G.dim),accent:K(G.accent),accentSoft:K(G.accentSoft),success:K(G.success),error:K(G.error),header:e=>M.bold(K(G.accent)(e)),system:K(G.systemText),userBg:q(G.userBg),userText:K(G.userText),toolTitle:K(G.toolTitle),toolOutput:K(G.toolOutput),toolPendingBg:q(G.toolPendingBg),toolSuccessBg:q(G.toolSuccessBg),toolErrorBg:q(G.toolErrorBg),border:K(G.border),bold:e=>M.bold(e),italic:e=>M.italic(e)},Z={heading:e=>M.bold(K(G.accent)(e)),link:e=>K(G.link)(e),linkUrl:e=>M.dim(e),code:e=>K(G.code)(e),codeBlock:e=>K(G.code)(e),codeBlockBorder:e=>K(G.codeBorder)(e),quote:e=>K(G.quote)(e),quoteBorder:e=>K(G.quoteBorder)(e),hr:e=>K(G.border)(e),listBullet:e=>K(G.accentSoft)(e),bold:e=>M.bold(e),italic:e=>M.italic(e),strikethrough:e=>M.strikethrough(e),underline:e=>M.underline(e),highlightCode:Y},Ae={selectedPrefix:e=>K(G.accent)(e),selectedText:e=>M.bold(K(G.accent)(e)),description:e=>K(G.dim)(e),scrollInfo:e=>K(G.dim)(e),noMatch:e=>K(G.dim)(e)},je=Ae,Me={...Ae,filterLabel:e=>K(G.dim)(e)},Ne={label:(e,t)=>t?M.bold(K(G.accent)(e)):K(G.text)(e),value:(e,t)=>t?K(G.accentSoft)(e):K(G.dim)(e),description:e=>K(G.systemText)(e),cursor:K(G.accent)(`→ `),hint:e=>K(G.dim)(e)},Pe={borderColor:e=>K(G.border)(e),selectList:je},Fe={...Ae,searchPrompt:e=>K(G.accentSoft)(e),searchInput:e=>K(G.text)(e),matchHighlight:e=>M.bold(K(G.accent)(e))},Ie=`\\x1b\\[[0-9;]*m`,Le=`\\x1b\\]8;;.*?(?:\\x07|\\x1b\\\\)`,Re=RegExp(`${Ie}|${Le}`,`g`),ze=RegExp(`^${Ie}`),Be=RegExp(`^${Le}`);function Q(e){let t=new Set,n=/\[(?:[^\]]*)\]\(\s*<?(https?:\/\/[^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)/g,r;for(;(r=n.exec(e))!==null;)t.add(r[1]);let i=e.replace(/\[(?:[^\]]*)\]\(\s*<?https?:\/\/[^)\s>]+>?(?:\s+["'][^"']*["'])?\s*\)/g,``),a=/https?:\/\/[^\s)\]>]+/g;for(;(r=a.exec(i))!==null;)t.add(r[0]);return[...t]}function Ve(e){return e.replace(Re,``)}function He(e,t,n){let r=[],i=null,a=0;if(n){let t=n.url.slice(n.consumed),o=e.trimStart(),s=e.length-o.length,c=0;for(let e=0;e<t.length&&e<o.length&&t[e]===o[e];e++)c++;c>0&&(r.push({start:s,end:s+c,url:n.url}),a=s+c,n.consumed+c<n.url.length&&(i={url:n.url,consumed:n.consumed+c}))}let o=/https?:\/\/[^\s)\]>]+/g;o.lastIndex=a;let s;for(;(s=o.exec(e))!==null;){let e=s[0],n=s.index,a=e,o=!1;for(let n of t)if(n===e){a=n,o=!0;break}if(!o){let n=0;for(let r of t)r.startsWith(e)&&r.length>n&&(a=r,n=r.length,o=!0)}if(!o){let n=0;for(let r of t)e.startsWith(r)&&r.length>n&&(a=r,n=r.length)}r.push({start:n,end:n+e.length,url:a}),a.length>e.length&&a.startsWith(e)&&(i={url:a,consumed:e.length})}return{ranges:r,pending:i}}function Ue(e,t){if(t.length===0)return e;let n=new Map;for(let e of t)for(let t=e.start;t<e.end;t++)n.set(t,e.url);let r=``,i=0,a=null,o=0;for(;o<e.length;){if(e.charCodeAt(o)===27){let t=e.slice(o).match(ze);if(t){r+=t[0],o+=t[0].length;continue}let n=e.slice(o).match(Be);if(n){r+=n[0],o+=n[0].length;continue}}let t=n.get(i)??null;t!==a&&(a!==null&&(r+=`\x1B]8;;\x07`),t!==null&&(r+=`\x1b]8;;${t}\x07`),a=t),r+=e[o],i++,o++}return a!==null&&(r+=`\x1B]8;;\x07`),r}function We(e,t){if(t.length===0)return e;let n=null;return e.map(e=>{let r=He(Ve(e),t,n);return n=r.pending,Ue(e,r.ranges)})}var Ge=class{constructor(e,t,n,r,i){this.inner=new se(e,t,n,r,i),this.urls=Q(e)}render(e){return We(this.inner.render(e),this.urls)}setText(e){this.inner.setText(e),this.urls=Q(e)}invalidate(){this.inner.invalidate()}},Ke=class extends P{constructor(e){super(),this.body=new Ge(e,1,0,Z,{color:e=>X.assistantText(e)}),this.addChild(new L(1)),this.addChild(this.body)}setText(e){this.body.setText(e)}};const qe=/\uFFFD/g,Je=/\S{33,}/g,Ye=/\S{33,}/,Xe=/^(https?:\/\/|file:\/\/)/i,Ze=/^[a-zA-Z]:[\\/]/,Qe=/^[a-zA-Z0-9._-]+$/,$e=/^[`"'([{<]+|[`"')\]}>.,:;!?]+$/g,et=/[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]/,tt=/[\u202a-\u202e\u2066-\u2069]/;function nt(e){for(let t of e){let e=t.charCodeAt(0);if(e<=31&&e!==9&&e!==10&&e!==13||e>=127&&e<=159)return!0}return!1}function rt(e){if(!nt(e))return e;let t=``;for(let n of e){let e=n.charCodeAt(0);!(e<=31&&e!==9&&e!==10&&e!==13)&&!(e>=127&&e<=159)&&(t+=n)}return t}function it(e,t){if(e.length<=t)return[e];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function at(e){let t=e.replace($e,``)||e;return!!(Xe.test(e)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`./`)||e.startsWith(`../`)||Ze.test(e)||e.startsWith(`\\\\`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`_`)&&Qe.test(e)||t.length>=24&&/[a-z]/i.test(t)&&/\d/.test(t))}function ot(e){return at(e)?e:it(e,32).join(` `)}function st(e){let t=(e.match(qe)||[]).length;return t>=12&&t*2>=e.length?`[binary data omitted]`:e}function ct(e){return!et.test(e)||tt.test(e)?e:`⁧${e}⁩`}function lt(e){return et.test(e)?e.split(`
`).map(e=>ct(e)).join(`
`):e}function $(e){if(!e)return e;let n=e.includes(`\x1B`),r=e.includes(`�`),i=Ye.test(e),a=nt(e);if(!n&&!r&&!i&&!a)return lt(e);let o=n?t(e):e,s=a?rt(o):o,c=r?s.split(`
`).map(e=>st(e)).join(`
`):s;return lt(Ye.test(c)?c.replace(Je,ot):c)}function ut(e){let t=e.finalText??``;if(t.trim())return t;let n=e.streamedText??``;if(n.trim())return n;let r=e.errorMessage??``;return r.trim()?o(r):`(no output)`}function dt(e){let t=e.thinkingText?.trim()??``,n=e.contentText?.trim()??``,r=[];return e.showThinking&&t&&r.push(`[thinking]\n${t}`),n&&r.push(n),r.join(`

`).trim()}function ft(e){if(!(!e||typeof e!=`object`))return e}function pt(e){let t=ft(e);if(t)return{record:t,content:t.content}}function mt(e){return(typeof e.stopReason==`string`?e.stopReason:``)===`error`?o(typeof e.errorMessage==`string`?e.errorMessage:``):``}function ht(e){if(!Array.isArray(e.content))return[];let t=[];for(let n of e.content){if(!n||typeof n!=`object`)continue;let r=n;r.type===e.blockType&&typeof r[e.valueKey]==`string`&&t.push($(r[e.valueKey]))}return t}function gt(e){let t=pt(e);if(!t)return``;let{content:n}=t;return typeof n==`string`?``:ht({content:n,blockType:`thinking`,valueKey:`thinking`}).join(`
`).trim()}function _t(e){let t=pt(e);if(!t)return``;let{record:n,content:r}=t;if(typeof r==`string`)return $(r).trim();let i=ht({content:r,blockType:`text`,valueKey:`text`});return i.length>0?i.join(`
`).trim():mt(n)}function vt(e,t){if(typeof e==`string`)return $(e).trim();if(!Array.isArray(e))return``;let n=ht({content:e,blockType:`text`,valueKey:`text`});return dt({thinkingText:(t?.includeThinking===!0?ht({content:e,blockType:`thinking`,valueKey:`thinking`}):[]).join(`
`).trim(),contentText:n.join(`
`).trim(),showThinking:t?.includeThinking??!1})}function yt(e,t){let n=ft(e);if(!n)return``;let r=vt(n.content,t);return r?n.role===`user`?x(r):r:mt(n)||``}function bt(e){return!e||typeof e!=`object`?!1:e.command===!0}function xt(e,t){if(e==null&&t==null)return`tokens ?`;let n=e==null?`?`:j(e);if(t==null)return`tokens ${n}`;let r=typeof e==`number`&&t>0?Math.min(999,Math.round(e/t*100)):null;return`tokens ${n}/${j(t)}${r===null?``:` (${r}%)`}`}function St(e){let t=typeof e.total==`number`?j(e.total):`?`,n=typeof e.context==`number`?j(e.context):`?`,r=typeof e.percent==`number`?Math.min(999,Math.round(e.percent)):null,i=[typeof e.remaining==`number`?`${j(e.remaining)} left`:null,r===null?null:`${r}%`].filter(Boolean).join(`, `);return`tokens ${t}/${n}${i?` (${i})`:``}`}function Ct(e,t=``){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):t}function wt(e,t){let n=C(S({name:e,args:t}));if(n)return $(n);if(!t||typeof t!=`object`)return``;try{return $(JSON.stringify(t))}catch{return``}}function Tt(e){if(!e?.content)return``;let t=[];for(let n of e.content)if(n.type===`text`&&n.text)t.push($(n.text));else if(n.type===`image`){let e=n.mimeType??`image`,r=n.bytes?` ${Math.round(n.bytes/1024)}kb`:``,i=n.omitted?` (omitted)`:``;t.push(`[${e}${r}${i}]`)}return t.join(`
`).trim()}var Et=class extends P{constructor(e,t){super(),this.expanded=!1,this.isError=!1,this.isPartial=!0,this.toolName=e,this.args=t,this.box=new ne(1,1,e=>X.toolPendingBg(e)),this.header=new de(``,0,0),this.argsLine=new de(``,0,0),this.output=new se(``,0,0,Z,{color:e=>X.toolOutput(e)}),this.addChild(new L(1)),this.addChild(this.box),this.box.addChild(this.header),this.box.addChild(this.argsLine),this.box.addChild(this.output),this.refresh()}setArgs(e){this.args=e,this.refresh()}setExpanded(e){this.expanded=e,this.refresh()}setResult(e,t){this.result=e,this.isPartial=!1,this.isError=!!t?.isError,this.refresh()}setPartialResult(e){this.result=e,this.isPartial=!0,this.refresh()}refresh(){let e=this.isPartial?X.toolPendingBg:this.isError?X.toolErrorBg:X.toolSuccessBg;this.box.setBgFn(t=>e(t));let t=S({name:this.toolName,args:this.args}),n=`${t.emoji} ${t.label}${this.isPartial?` (running)`:``}`;this.header.setText(X.toolTitle(X.bold(n)));let r=wt(this.toolName,this.args);this.argsLine.setText(r?X.dim(r):X.dim(` `));let i=Tt(this.result)||(this.isPartial?`…`:``);if(!this.expanded&&i){let e=i.split(`
`),t=e.length>12?`${e.slice(0,12).join(`
`)}\n…`:i;this.output.setText(t)}else this.output.setText(i)}},Dt=class extends P{constructor(e,t,n){super(),this.body=new se(e,1,t,Z,n),this.addChild(new L(1)),this.addChild(this.body)}setText(e){this.body.setText(e)}},Ot=class extends Dt{constructor(e){super(e,1,{bgColor:e=>X.userBg(e),color:e=>X.userText(e)})}},kt=class extends P{constructor(e=180){super(),this.toolById=new Map,this.streamingRuns=new Map,this.toolsExpanded=!1,this.maxComponents=Math.max(20,Math.floor(e))}dropComponentReferences(e){for(let[t,n]of this.toolById.entries())n===e&&this.toolById.delete(t);for(let[t,n]of this.streamingRuns.entries())n===e&&this.streamingRuns.delete(t)}pruneOverflow(){for(;this.children.length>this.maxComponents;){let e=this.children[0];if(!e)return;this.removeChild(e),this.dropComponentReferences(e)}}append(e){this.addChild(e),this.pruneOverflow()}clearAll(){this.clear(),this.toolById.clear(),this.streamingRuns.clear()}addSystem(e){this.append(new L(1)),this.append(new de(X.system(e),1,0))}addUser(e){this.append(new Ot(e))}resolveRunId(e){return e??`default`}startAssistant(e,t){let n=new Ke(e);return this.streamingRuns.set(this.resolveRunId(t),n),this.append(n),n}updateAssistant(e,t){let n=this.resolveRunId(t),r=this.streamingRuns.get(n);if(!r){this.startAssistant(e,t);return}r.setText(e)}finalizeAssistant(e,t){let n=this.resolveRunId(t),r=this.streamingRuns.get(n);if(r){r.setText(e),this.streamingRuns.delete(n);return}this.append(new Ke(e))}dropAssistant(e){let t=this.resolveRunId(e),n=this.streamingRuns.get(t);n&&(this.removeChild(n),this.streamingRuns.delete(t))}startTool(e,t,n){let r=this.toolById.get(e);if(r)return r.setArgs(n),r;let i=new Et(t,n);return i.setExpanded(this.toolsExpanded),this.toolById.set(e,i),this.append(i),i}updateToolArgs(e,t){let n=this.toolById.get(e);n&&n.setArgs(t)}updateToolResult(e,t,n){let r=this.toolById.get(e);if(r){if(n?.partial){r.setPartialResult(t);return}r.setResult(t,{isError:n?.isError})}}setToolsExpanded(e){this.toolsExpanded=e;for(let t of this.toolById.values())t.setExpanded(e)}},At=class extends ie{handleInput(e){if(R(e,F.alt(`enter`))&&this.onAltEnter){this.onAltEnter();return}if(R(e,F.ctrl(`l`))&&this.onCtrlL){this.onCtrlL();return}if(R(e,F.ctrl(`o`))&&this.onCtrlO){this.onCtrlO();return}if(R(e,F.ctrl(`p`))&&this.onCtrlP){this.onCtrlP();return}if(R(e,F.ctrl(`g`))&&this.onCtrlG){this.onCtrlG();return}if(R(e,F.ctrl(`t`))&&this.onCtrlT){this.onCtrlT();return}if(R(e,F.shift(`tab`))&&this.onShiftTab){this.onShiftTab();return}if(R(e,F.escape)&&this.onEscape&&!this.isShowingAutocomplete()){this.onEscape();return}if(R(e,F.ctrl(`c`))&&this.onCtrlC){this.onCtrlC();return}if(R(e,F.ctrl(`d`))){this.getText().length===0&&this.onCtrlD&&this.onCtrlD();return}super.handleInput(e)}};function jt(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Mt(e){throw Error([e,`Fix: set OPENCLAW_GATEWAY_TOKEN/OPENCLAW_GATEWAY_PASSWORD, pass --token/--password,`,`or resolve the configured secret provider for this credential.`].join(`
`))}var Nt=class e{constructor(e){this.connection=e,this.readyPromise=new Promise(e=>{this.resolveReady=e}),this.client=new T({url:e.url,token:e.token,password:e.password,clientName:i.GATEWAY_CLIENT,clientDisplayName:`openclaw-tui`,clientVersion:r,platform:process.platform,mode:d.UI,caps:[p.TOOL_EVENTS],instanceId:N(),minProtocol:3,maxProtocol:3,onHelloOk:e=>{this.hello=e,this.resolveReady?.(),this.onConnected?.()},onEvent:e=>{this.onEvent?.({event:e.event,payload:e.payload,seq:e.seq})},onClose:(e,t)=>{this.readyPromise=new Promise(e=>{this.resolveReady=e}),this.onDisconnected?.(t)},onGap:e=>{this.onGap?.(e)}})}static async connect(t){return new e(await Pt(t))}start(){this.client.start()}stop(){this.client.stop()}async waitForReady(){await this.readyPromise}async sendChat(e){let t=e.runId??N();return await this.client.request(`chat.send`,{sessionKey:e.sessionKey,message:e.message,thinking:e.thinking,deliver:e.deliver,timeoutMs:e.timeoutMs,idempotencyKey:t}),{runId:t}}async abortChat(e){return await this.client.request(`chat.abort`,{sessionKey:e.sessionKey,runId:e.runId})}async loadHistory(e){return await this.client.request(`chat.history`,{sessionKey:e.sessionKey,limit:e.limit})}async listSessions(e){return await this.client.request(`sessions.list`,{limit:e?.limit,activeMinutes:e?.activeMinutes,includeGlobal:e?.includeGlobal,includeUnknown:e?.includeUnknown,includeDerivedTitles:e?.includeDerivedTitles,includeLastMessage:e?.includeLastMessage,agentId:e?.agentId})}async listAgents(){return await this.client.request(`agents.list`,{})}async patchSession(e){return await this.client.request(`sessions.patch`,e)}async resetSession(e,t){return await this.client.request(`sessions.reset`,{key:e,...t?{reason:t}:{}})}async getStatus(){return await this.client.request(`status`)}async listModels(){let e=await this.client.request(`models.list`);return Array.isArray(e?.models)?e.models:[]}};async function Pt(e){let t=u(),n=process.env,r=t.gateway?.auth?.mode,i=t.gateway?.mode===`remote`,o=t.gateway?.remote,s=jt(n.OPENCLAW_GATEWAY_TOKEN),c=jt(n.OPENCLAW_GATEWAY_PASSWORD),d=typeof e.url==`string`&&e.url.trim().length>0?e.url.trim():void 0,f=D({token:e.token,password:e.password});E({urlOverride:d,urlOverrideSource:`cli`,explicitAuth:f,errorHint:`Fix: pass --token or --password when using --url.`});let p=O({config:t,...d?{url:d}:{}}).url;if(d)return{url:p,token:f.token,password:f.password};if(i){let e=f.token?{value:f.token}:await a({value:o?.token,path:`gateway.remote.token`,env:n,config:t}),r=f.password||c?{value:f.password??c}:await a({value:o?.password,path:`gateway.remote.password`,env:n,config:t}),i=f.token??e.value,s=f.password??c??r.value;return!i&&!s&&Mt(e.unresolvedRefReason??r.unresolvedRefReason??`Missing gateway auth credentials.`),{url:p,token:i,password:s}}if(r===`none`||r===`trusted-proxy`)return{url:p,token:f.token??s,password:f.password??c};try{l(t)}catch(e){Mt(e instanceof Error?e.message:String(e))}let m=t.secrets?.defaults,h=b(t.gateway?.auth?.token,m),g=b(t.gateway?.auth?.password,m);if(r===`password`){let e=f.password||c?{value:f.password??c}:await a({value:t.gateway?.auth?.password,path:`gateway.auth.password`,env:n,config:t}),r=f.password??c??e.value;return r||Mt(e.unresolvedRefReason??`Missing gateway auth password.`),{url:p,token:f.token??s,password:r}}let _=async()=>{let e=f.token?{value:f.token}:await a({value:t.gateway?.auth?.token,path:`gateway.auth.token`,env:n,config:t}),r=f.token??e.value??s;return r||Mt(e.unresolvedRefReason??`Missing gateway auth token.`),r};if(r===`token`)return{url:p,token:await _(),password:f.password??c};let v=f.password??c;if(v||g&&!h){let e=v?{value:v}:await a({value:t.gateway?.auth?.password,path:`gateway.auth.password`,env:n,config:t}),r=f.password??e.value??c;return r||Mt(e.unresolvedRefReason??`Missing gateway auth password.`),{url:p,token:f.token??s,password:r}}return{url:p,token:await _(),password:f.password??c}}const Ft=/[\s\-_./:#@]/;function It(e,t){return t===0||Ft.test(e[t-1]??``)}function Lt(e,t){if(!t)return null;let n=e.toLowerCase(),r=t.toLowerCase(),i=n.length-r.length;if(i<0)return null;for(let e=0;e<=i;e++)if(n.startsWith(r,e)&&It(n,e))return e;return null}function Rt(e,t){if(e.length===0)return 0;if(e.length>t.length)return null;let n=0,r=0,i=-1,a=0;for(let o=0;o<t.length&&n<e.length;o++)if(t[o]===e[n]){let e=It(t,o);i===o-1?(a++,r-=a*5):(a=0,i>=0&&(r+=(o-i-1)*2)),e&&(r-=10),r+=o*.1,i=o,n++}return n<e.length?null:r}function zt(e,t){let n=t.trim();if(!n)return e;let r=n.split(/\s+/).filter(e=>e.length>0);if(r.length===0)return e;let i=[];for(let t of e){let e=t.searchTextLower??``,n=0,a=!0;for(let t of r){let r=Rt(t,e);if(r!==null)n+=r;else{a=!1;break}}a&&i.push({item:t,score:n})}return i.sort((e,t)=>e.score-t.score),i.map(e=>e.item)}function Bt(e){return e.map(e=>{let t=[];return e.label&&t.push(e.label),e.description&&t.push(e.description),e.searchText&&t.push(e.searchText),{...e,searchTextLower:t.join(` `).toLowerCase()}})}var Vt=class{constructor(e,t,n){this.filterText=``,this.allItems=Bt(e),this.maxVisible=t,this.theme=n,this.input=new ae,this.selectList=new le(this.allItems,t,n)}applyFilter(){let e=this.filterText.toLowerCase();if(!e.trim()){this.selectList=new le(this.allItems,this.maxVisible,this.theme);return}this.selectList=new le(zt(this.allItems,e),this.maxVisible,this.theme)}invalidate(){this.input.invalidate(),this.selectList.invalidate()}render(e){let t=[],n=this.theme.filterLabel(`Filter: `),r=this.input.render(e-8)[0]??``;t.push(n+r),t.push(M.dim(`─`.repeat(Math.max(0,e))));let i=this.selectList.render(e);return t.push(...i),t}handleInput(e){let t=!this.filterText.trim();if(R(e,`up`)||R(e,`ctrl+p`)||t&&e===`k`){this.selectList.handleInput(`\x1B[A`);return}if(R(e,`down`)||R(e,`ctrl+n`)||t&&e===`j`){this.selectList.handleInput(`\x1B[B`);return}if(R(e,`enter`)){let e=this.selectList.getSelectedItem();e&&this.onSelect?.(e);return}if(fe().matches(e,`selectCancel`)){this.filterText?(this.filterText=``,this.input.setValue(``),this.applyFilter()):this.onCancel?.();return}let n=this.input.getValue();this.input.handleInput(e);let r=this.input.getValue();r!==n&&(this.filterText=r,this.applyFilter())}getSelectedItem(){return this.selectList.getSelectedItem()}getFilterText(){return this.filterText}};const Ht=RegExp(`\x1B\\[[0-9;]*m`,`g`);var Ut=class n{static{this.DESCRIPTION_LAYOUT_MIN_WIDTH=40}static{this.DESCRIPTION_MIN_WIDTH=12}static{this.DESCRIPTION_SPACING_WIDTH=2}static{this.RIGHT_MARGIN_WIDTH=2}constructor(e,t,n){this.selectedIndex=0,this.regexCache=new Map,this.compareByScore=(e,t)=>e.tier===t.tier?e.score===t.score?this.getItemLabel(e.item).localeCompare(this.getItemLabel(t.item)):e.score-t.score:e.tier-t.tier,this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.searchInput=new ae}getCachedRegex(e){let t=this.regexCache.get(e);return t||(t=new RegExp(this.escapeRegex(e),`gi`),this.regexCache.set(e,t)),t}updateFilter(){let e=this.searchInput.getValue().trim();e?this.filteredItems=this.smartFilter(e):this.filteredItems=this.items,this.selectedIndex=0,this.notifySelectionChange()}smartFilter(e){let n=e.toLowerCase(),r=[],i=[];for(let e of this.items){let a=this.getItemLabel(e),o=e.description??``,s=t(a).toLowerCase(),c=t(o).toLowerCase(),l=s.indexOf(n);if(l!==-1){r.push({item:e,tier:0,score:l});continue}let u=Lt(s,n);if(u!==null){r.push({item:e,tier:1,score:u});continue}let d=c.indexOf(n);if(d!==-1){r.push({item:e,tier:2,score:d});continue}let f=e.searchText??``;i.push({item:e,searchTextLower:[a,o,f].map(e=>t(e)).filter(Boolean).join(` `).toLowerCase()})}r.sort(this.compareByScore);let a=zt(i,n);return[...r.map(e=>e.item),...a.map(e=>e.item)]}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}getItemLabel(e){return e.label||e.value}splitAnsiParts(e){let t=[];Ht.lastIndex=0;let n=0,r;for(;(r=Ht.exec(e))!==null;)r.index>n&&t.push({text:e.slice(n,r.index),isAnsi:!1}),t.push({text:r[0],isAnsi:!0}),n=r.index+r[0].length;return n<e.length&&t.push({text:e.slice(n),isAnsi:!1}),t}highlightMatch(e,t){let n=t.trim().split(/\s+/).map(e=>e.toLowerCase()).filter(e=>e.length>0);if(n.length===0)return e;let r=Array.from(new Set(n)).toSorted((e,t)=>t.length-e.length),i=this.splitAnsiParts(e);for(let e of r){let t=this.getCachedRegex(e),n=[];for(let e of i){if(e.isAnsi){n.push(e);continue}t.lastIndex=0;let r=e.text.replace(t,e=>this.theme.matchHighlight(e));if(r===e.text){n.push(e);continue}n.push(...this.splitAnsiParts(r))}i=n}return i.map(e=>e.text).join(``)}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){this.searchInput.invalidate()}render(t){let n=[],r=this.theme.searchPrompt(`search: `),i=Math.max(1,t-e(r)),a=this.searchInput.render(i)[0]??``;n.push(`${r}${this.theme.searchInput(a)}`),n.push(``);let o=this.searchInput.getValue().trim();if(this.filteredItems.length===0)return n.push(this.theme.noMatch(`  No matches`)),n;let s=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),c=Math.min(s+this.maxVisible,this.filteredItems.length);for(let e=s;e<c;e++){let r=this.filteredItems[e];if(!r)continue;let i=e===this.selectedIndex;n.push(this.renderItemLine(r,i,t,o))}if(this.filteredItems.length>this.maxVisible){let e=`${this.selectedIndex+1}/${this.filteredItems.length}`;n.push(this.theme.scrollInfo(`  ${e}`))}return n}renderItemLine(t,r,i,a){let o=r?`→ `:`  `,s=o.length,c=this.getItemLabel(t),l=t.description;if(l){let t=this.getDescriptionLayout(i,s);if(t){let i=me(c,t.maxValueWidth,``),s=this.highlightMatch(i,a),u=e(s),d=t.availableWidth-u-t.spacingWidth;if(d>=n.DESCRIPTION_MIN_WIDTH){let e=` `.repeat(t.spacingWidth),n=me(l,d,``),i=this.highlightMatch(n,a),c=`${o}${s}${e}${r?i:this.theme.description(i)}`;return r?this.theme.selectedText(c):c}}}let u=me(c,i-s-2,``),d=`${o}${this.highlightMatch(u,a)}`;return r?this.theme.selectedText(d):d}getDescriptionLayout(e,t){if(e<=n.DESCRIPTION_LAYOUT_MIN_WIDTH)return null;let r=Math.max(1,e-t-n.RIGHT_MARGIN_WIDTH),i=r-n.DESCRIPTION_MIN_WIDTH-n.DESCRIPTION_SPACING_WIDTH;return i<1?null:{availableWidth:r,maxValueWidth:i,spacingWidth:n.DESCRIPTION_SPACING_WIDTH}}handleInput(e){if(pe(e))return;let t=!this.searchInput.getValue().trim();if(R(e,`up`)||R(e,`ctrl+p`)||t&&e===`k`){this.selectedIndex=Math.max(0,this.selectedIndex-1),this.notifySelectionChange();return}if(R(e,`down`)||R(e,`ctrl+n`)||t&&e===`j`){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+1),this.notifySelectionChange();return}if(R(e,`enter`)){let e=this.filteredItems[this.selectedIndex];e&&this.onSelect&&this.onSelect(e);return}if(fe().matches(e,`selectCancel`)){this.onCancel&&this.onCancel();return}let n=this.searchInput.getValue();this.searchInput.handleInput(e),n!==this.searchInput.getValue()&&this.updateFilter()}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]??null}};function Wt(e,t=7){return new Ut(e,t,Fe)}function Gt(e,t=7){return new Vt(e,t,Me)}function Kt(e,t,n,r=7){return new I(e,r,Ne,t,n)}function qt(e){let t=[];if(t.push(`Gateway status`),e.runtimeVersion&&t.push(`Version: ${e.runtimeVersion}`),!e.linkChannel)t.push(`Link channel: unknown`);else{let n=e.linkChannel.label??`Link channel`,r=e.linkChannel.linked===!0,i=r&&typeof e.linkChannel.authAgeMs==`number`?` (last refreshed ${k(e.linkChannel.authAgeMs)})`:``;t.push(`${n}: ${r?`linked`:`not linked`}${i}`)}let n=Array.isArray(e.providerSummary)?e.providerSummary:[];if(n.length>0){t.push(``),t.push(`System:`);for(let e of n)t.push(`  ${e}`)}let r=e.heartbeat?.agents??[];if(r.length>0){let e=r.map(e=>{let t=e.agentId??`unknown`;return!e.enabled||!e.everyMs?`disabled (${t})`:`${e.every??`unknown`} (${t})`});t.push(``),t.push(`Heartbeat: ${e.join(`, `)}`)}let i=e.sessions?.paths??[];i.length===1?t.push(`Session store: ${i[0]}`):i.length>1&&t.push(`Session stores: ${i.length}`);let a=e.sessions?.defaults,o=a?.model??`unknown`,s=typeof a?.contextTokens==`number`?` (${j(a.contextTokens)} ctx)`:``;t.push(`Default model: ${o}${s}`);let c=e.sessions?.count??0;t.push(`Active sessions: ${c}`);let l=Array.isArray(e.sessions?.recent)?e.sessions?.recent:[];if(l.length>0){t.push(`Recent sessions:`);for(let e of l){let n=typeof e.age==`number`?k(e.age):`no activity`,r=e.model??`unknown`,i=St({total:e.totalTokens??null,context:e.contextTokens??null,remaining:e.remainingTokens??null,percent:e.percentUsed??null}),a=e.flags?.length?` | flags: ${e.flags.join(`, `)}`:``;t.push(`- ${e.key}${e.kind?` [${e.kind}]`:``} | ${n} | model ${r} | ${i}${a}`)}}let u=Array.isArray(e.queuedSystemEvents)?e.queuedSystemEvents:[];if(u.length>0){let e=u.slice(0,3).join(` | `);t.push(`Queued system events (${u.length}): ${e}`)}return t}function Jt(e){let{client:t,chatLog:r,tui:i,opts:a,state:o,deliverDefault:s,openOverlay:l,closeOverlay:u,refreshSessionInfo:d,loadHistory:p,setSession:m,refreshAgents:h,abortActive:g,setActivityStatus:v,formatSessionKey:y,applySessionInfoFromPatch:b,noteLocalRunId:x,forgetLocalRunId:S,requestExit:C}=e,w=async e=>{o.currentAgentId=_(e),await m(``)},ee=()=>{u(),i.requestRender()},T=(e,t)=>{e.onSelect=e=>{(async()=>{await t(e.value),ee()})()},e.onCancel=ee,l(e),i.requestRender()},E=async()=>{try{let e=await t.listModels();if(e.length===0){r.addSystem(`no models available`),i.requestRender();return}T(Wt(e.map(e=>({value:`${e.provider}/${e.id}`,label:`${e.provider}/${e.id}`,description:e.name&&e.name!==e.id?e.name:``})),9),async e=>{try{let n=await t.patchSession({key:o.currentSessionKey,model:e});r.addSystem(`model set to ${e}`),b(n),await d()}catch(e){r.addSystem(`model set failed: ${String(e)}`)}})}catch(e){r.addSystem(`model list failed: ${String(e)}`),i.requestRender()}},D=async()=>{if(await h(),o.agents.length===0){r.addSystem(`no agents found`),i.requestRender();return}T(Wt(o.agents.map(e=>({value:e.id,label:e.name?`${e.id} (${e.name})`:e.id,description:e.id===o.agentDefaultId?`default`:``})),9),async e=>{await w(e)})},O=async()=>{try{T(Gt((await t.listSessions({includeGlobal:!1,includeUnknown:!1,includeDerivedTitles:!0,includeLastMessage:!0,agentId:o.currentAgentId})).sessions.map(e=>{let t=e.derivedTitle??e.displayName,n=y(e.key),r=t&&t!==n?`${t} (${n})`:n,i=e.updatedAt?A(e.updatedAt,{dateFallback:!0,fallback:``}):``,a=e.lastMessagePreview?.replace(/\s+/g,` `).trim(),o=i&&a?`${i} · ${a}`:a??i;return{value:e.key,label:r,description:o,searchText:[e.displayName,e.label,e.subject,e.sessionId,e.key,e.lastMessagePreview].filter(Boolean).join(` `)}}),9),async e=>{await m(e)})}catch(e){r.addSystem(`sessions list failed: ${String(e)}`),i.requestRender()}},k=()=>{l(Kt([{id:`tools`,label:`Tool output`,currentValue:o.toolsExpanded?`expanded`:`collapsed`,values:[`collapsed`,`expanded`]},{id:`thinking`,label:`Show thinking`,currentValue:o.showThinking?`on`:`off`,values:[`off`,`on`]}],(e,t)=>{e===`tools`&&(o.toolsExpanded=t===`expanded`,r.setToolsExpanded(o.toolsExpanded)),e===`thinking`&&(o.showThinking=t===`on`,p()),i.requestRender()},()=>{u(),i.requestRender()})),i.requestRender()},j=async e=>{let{name:a,args:s}=be(e);if(a){switch(a){case`help`:r.addSystem(U({provider:o.sessionInfo.modelProvider,model:o.sessionInfo.model}));break;case`status`:try{let e=await t.getStatus();if(typeof e==`string`){r.addSystem(e);break}if(e&&typeof e==`object`){let t=qt(e);for(let e of t)r.addSystem(e);break}r.addSystem(`status: unknown response`)}catch(e){r.addSystem(`status failed: ${String(e)}`)}break;case`agent`:s?await w(s):await D();break;case`agents`:await D();break;case`session`:s?await m(s):await O();break;case`sessions`:await O();break;case`model`:if(!s)await E();else try{let e=await t.patchSession({key:o.currentSessionKey,model:s});r.addSystem(`model set to ${s}`),b(e),await d()}catch(e){r.addSystem(`model set failed: ${String(e)}`)}break;case`models`:await E();break;case`think`:if(!s){let e=c(o.sessionInfo.modelProvider,o.sessionInfo.model,`|`);r.addSystem(`usage: /think <${e}>`);break}try{let e=await t.patchSession({key:o.currentSessionKey,thinkingLevel:s});r.addSystem(`thinking set to ${s}`),b(e),await d()}catch(e){r.addSystem(`think failed: ${String(e)}`)}break;case`verbose`:if(!s){r.addSystem(`usage: /verbose <on|off>`);break}try{let e=await t.patchSession({key:o.currentSessionKey,verboseLevel:s});r.addSystem(`verbose set to ${s}`),b(e),await p()}catch(e){r.addSystem(`verbose failed: ${String(e)}`)}break;case`reasoning`:if(!s){r.addSystem(`usage: /reasoning <on|off>`);break}try{let e=await t.patchSession({key:o.currentSessionKey,reasoningLevel:s});r.addSystem(`reasoning set to ${s}`),b(e),await d()}catch(e){r.addSystem(`reasoning failed: ${String(e)}`)}break;case`usage`:{let e=s?f(s):void 0;if(s&&!e){r.addSystem(`usage: /usage <off|tokens|full>`);break}let i=o.sessionInfo.responseUsage,a=n(i),c=e??(a===`off`?`tokens`:a===`tokens`?`full`:`off`);try{let e=await t.patchSession({key:o.currentSessionKey,responseUsage:c===`off`?null:c});r.addSystem(`usage footer: ${c}`),b(e),await d()}catch(e){r.addSystem(`usage failed: ${String(e)}`)}break}case`elevated`:if(!s){r.addSystem(`usage: /elevated <on|off|ask|full>`);break}if(![`on`,`off`,`ask`,`full`].includes(s)){r.addSystem(`usage: /elevated <on|off|ask|full>`);break}try{let e=await t.patchSession({key:o.currentSessionKey,elevatedLevel:s});r.addSystem(`elevated set to ${s}`),b(e),await d()}catch(e){r.addSystem(`elevated failed: ${String(e)}`)}break;case`activation`:if(!s){r.addSystem(`usage: /activation <mention|always>`);break}try{let e=await t.patchSession({key:o.currentSessionKey,groupActivation:s===`always`?`always`:`mention`});r.addSystem(`activation set to ${s}`),b(e),await d()}catch(e){r.addSystem(`activation failed: ${String(e)}`)}break;case`new`:try{o.sessionInfo.inputTokens=null,o.sessionInfo.outputTokens=null,o.sessionInfo.totalTokens=null,i.requestRender();let e=`tui-${N()}`;await m(e),r.addSystem(`new session: ${e}`)}catch(e){r.addSystem(`new session failed: ${$(String(e))}`)}break;case`reset`:try{o.sessionInfo.inputTokens=null,o.sessionInfo.outputTokens=null,o.sessionInfo.totalTokens=null,i.requestRender(),await t.resetSession(o.currentSessionKey,a),r.addSystem(`session ${o.currentSessionKey} reset`),await p()}catch(e){r.addSystem(`reset failed: ${$(String(e))}`)}break;case`abort`:await g();break;case`settings`:k();break;case`exit`:case`quit`:C();break;default:await M(e);break}i.requestRender()}},M=async e=>{if(!o.isConnected){r.addSystem(`not connected to gateway — message not sent`),v(`disconnected`),i.requestRender();return}try{r.addUser(e),i.requestRender();let n=N();x(n),o.activeChatRunId=n,v(`sending`),i.requestRender(),await t.sendChat({sessionKey:o.currentSessionKey,message:e,thinking:a.thinking,deliver:s,timeoutMs:a.timeoutMs,runId:n}),v(`waiting`),i.requestRender()}catch(e){o.activeChatRunId&&S?.(o.activeChatRunId),o.activeChatRunId=null,r.addSystem(`send failed: ${String(e)}`),v(`error`),i.requestRender()}};return{handleCommand:j,sendMessage:M,openModelSelector:E,openAgentSelector:D,openSessionSelector:O,openSettings:k,setAgent:w}}function Yt(e){if(!e||typeof e!=`object`)return{textBlocks:[],sawNonTextContentBlocks:!1};let t=e.content;if(typeof t==`string`){let e=t.trim();return{textBlocks:e?[e]:[],sawNonTextContentBlocks:!1}}if(!Array.isArray(t))return{textBlocks:[],sawNonTextContentBlocks:!1};let n=[],r=!1;for(let e of t){if(!e||typeof e!=`object`)continue;let t=e;if(t.type===`text`&&typeof t.text==`string`){let e=t.text.trim();e&&n.push(e);continue}typeof t.type==`string`&&t.type!==`thinking`&&(r=!0)}return{textBlocks:n,sawNonTextContentBlocks:r}}function Xt(e){let{streamedTextBlocks:t,finalTextBlocks:n}=e;if(n.length===0||n.length>=t.length)return!1;if(n.every((e,n)=>t[n]===e))return!0;let r=t.length-n.length;return n.every((e,n)=>t[r+n]===e)}function Zt(e){return e.boundaryDropMode===`off`||!(e.boundaryDropMode===`streamed-or-incoming`?e.streamedSawNonTextContentBlocks||e.incomingSawNonTextContentBlocks:e.streamedSawNonTextContentBlocks)?!1:Xt({streamedTextBlocks:e.streamedTextBlocks,finalTextBlocks:e.nextContentBlocks})}var Qt=class{constructor(){this.runs=new Map}getOrCreateRun(e){let t=this.runs.get(e);return t||(t={thinkingText:``,contentText:``,contentBlocks:[],sawNonTextContentBlocks:!1,displayText:``},this.runs.set(e,t)),t}updateRunState(e,t,n,r){let i=gt(t),a=_t(t),{textBlocks:o,sawNonTextContentBlocks:s}=Yt(t);if(i&&(e.thinkingText=i),a){let t=o.length>0?o:[a];Zt({boundaryDropMode:r?.boundaryDropMode??`off`,streamedSawNonTextContentBlocks:e.sawNonTextContentBlocks,incomingSawNonTextContentBlocks:s,streamedTextBlocks:e.contentBlocks,nextContentBlocks:t})||(e.contentText=a,e.contentBlocks=t)}s&&(e.sawNonTextContentBlocks=!0),e.displayText=dt({thinkingText:e.thinkingText,contentText:e.contentText,showThinking:n})}ingestDelta(e,t,n){let r=this.getOrCreateRun(e),i=r.displayText;return this.updateRunState(r,t,n,{boundaryDropMode:`streamed-or-incoming`}),!r.displayText||r.displayText===i?null:r.displayText}finalize(e,t,n,r){let i=this.getOrCreateRun(e),a=i.displayText,o=[...i.contentBlocks],s=i.sawNonTextContentBlocks;this.updateRunState(i,t,n,{boundaryDropMode:`streamed-only`});let c=i.displayText,l=ut({finalText:s&&Xt({streamedTextBlocks:o,finalTextBlocks:i.contentBlocks})?a:c,streamedText:a,errorMessage:r});return this.runs.delete(e),l}drop(e){this.runs.delete(e)}};function $t(e){let{chatLog:t,tui:n,state:r,setActivityStatus:i,refreshSessionInfo:a,loadHistory:o,isLocalRunId:s,forgetLocalRunId:c,clearLocalRunIds:l}=e,u=new Map,d=new Map,f=new Qt,p=r.currentSessionKey,m=e=>{if(e.size<=200)return;let t=Date.now()-600*1e3;for(let[n,r]of e){if(e.size<=150)break;r<t&&e.delete(n)}if(e.size>200){for(let t of e.keys())if(e.delete(t),e.size<=150)break}},h=()=>{r.currentSessionKey!==p&&(p=r.currentSessionKey,u.clear(),d.clear(),f=new Qt,l?.())},_=e=>{d.set(e,Date.now()),m(d)},v=e=>{u.set(e,Date.now()),d.delete(e),f.drop(e),m(u)},y=e=>{r.activeChatRunId===e&&(r.activeChatRunId=null)},b=e=>{v(e.runId),y(e.runId),e.wasActiveRun&&i(e.status),a?.()},x=e=>{f.drop(e.runId),d.delete(e.runId),y(e.runId),e.wasActiveRun&&i(e.status),a?.()},S=e=>{let t=r.activeChatRunId;return!t||t===e?!1:d.has(t)},C=(e,t)=>{(s?.(e)??!1)&&(c?.(e),!t?.allowLocalWithoutDisplayableFinal)||S(e)||o?.()},w=(e,t)=>{let n=(e??``).trim().toLowerCase(),r=(t??``).trim().toLowerCase();if(!n||!r)return!1;if(n===r)return!0;let i=g(n),a=g(r);return i&&a?i.agentId===a.agentId&&i.rest===a.rest:i?i.rest===r:a?n===a.rest:!1};return{handleChatEvent:e=>{if(!e||typeof e!=`object`)return;let a=e;if(h(),w(a.sessionKey,r.currentSessionKey)&&!(u.has(a.runId)&&(a.state===`delta`||a.state===`final`))){if(_(a.runId),r.activeChatRunId||=a.runId,a.state===`delta`){let e=f.ingestDelta(a.runId,a.message,r.showThinking);if(!e)return;t.updateAssistant(e,a.runId),i(`streaming`)}if(a.state===`final`){let e=r.activeChatRunId===a.runId;if(!a.message){C(a.runId,{allowLocalWithoutDisplayableFinal:!0}),t.dropAssistant(a.runId),b({runId:a.runId,wasActiveRun:e,status:`idle`}),n.requestRender();return}if(bt(a.message)){C(a.runId);let r=yt(a.message);r&&t.addSystem(r),b({runId:a.runId,wasActiveRun:e,status:`idle`}),n.requestRender();return}C(a.runId);let i=a.message&&typeof a.message==`object`&&!Array.isArray(a.message)&&typeof a.message.stopReason==`string`?a.message.stopReason:``,o=f.finalize(a.runId,a.message,r.showThinking,a.errorMessage);o===`(no output)`&&!s?.(a.runId)?t.dropAssistant(a.runId):t.finalizeAssistant(o,a.runId),b({runId:a.runId,wasActiveRun:e,status:i===`error`?`error`:`idle`})}if(a.state===`aborted`){let e=r.activeChatRunId===a.runId;t.addSystem(`run aborted`),x({runId:a.runId,wasActiveRun:e,status:`aborted`}),C(a.runId)}if(a.state===`error`){let e=r.activeChatRunId===a.runId;t.addSystem(`run error: ${a.errorMessage??`unknown`}`),x({runId:a.runId,wasActiveRun:e,status:`error`}),C(a.runId)}n.requestRender()}},handleAgentEvent:e=>{if(!e||typeof e!=`object`)return;let a=e;h();let o=a.runId===r.activeChatRunId;if(o||d.has(a.runId)||u.has(a.runId)){if(a.stream===`tool`){let e=r.sessionInfo.verboseLevel??`off`,i=e!==`off`,o=e===`full`;if(!i)return;let s=a.data??{},c=Ct(s.phase,``),l=Ct(s.toolCallId,``),u=Ct(s.name,`tool`);if(!l)return;if(c===`start`)t.startTool(l,u,s.args);else if(c===`update`){if(!o)return;t.updateToolResult(l,s.partialResult,{partial:!0})}else c===`result`&&(o?t.updateToolResult(l,s.result,{isError:!!s.isError}):t.updateToolResult(l,{content:[]},{isError:!!s.isError}));n.requestRender();return}if(a.stream===`lifecycle`){if(!o)return;let e=typeof a.data?.phase==`string`?a.data.phase:``;e===`start`&&i(`running`),e===`end`&&i(`idle`),e===`error`&&i(`error`),n.requestRender()}}}}}function en(e){let t=!1,n=!1,r=e.createSelector??Wt,i=e.spawnCommand??te,a=e.getCwd??(()=>process.cwd()),o=e.env??process.env,s=e.maxOutputChars??4e4,c=async()=>n?!0:t?!1:(t=!0,await new Promise(t=>{e.chatLog.addSystem(`Allow local shell commands for this session?`),e.chatLog.addSystem(`This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.`),e.chatLog.addSystem(`Select Yes/No (arrows + Enter), Esc to cancel.`);let i=r([{value:`no`,label:`No`},{value:`yes`,label:`Yes`}],2);i.onSelect=r=>{e.closeOverlay(),r.value===`yes`?(n=!0,e.chatLog.addSystem(`local shell: enabled for this session`),t(!0)):(e.chatLog.addSystem(`local shell: not enabled`),t(!1)),e.tui.requestRender()},i.onCancel=()=>{e.closeOverlay(),e.chatLog.addSystem(`local shell: cancelled`),e.tui.requestRender(),t(!1)},e.openOverlay(i),e.tui.requestRender()}));return{runLocalShellLine:async r=>{let l=r.slice(1);if(l===``)return;if(t&&!n){e.chatLog.addSystem(`local shell: not enabled for this session`),e.tui.requestRender();return}if(!await c())return;e.chatLog.addSystem(`[local] $ ${l}`),e.tui.requestRender();let u=(e,t)=>{let n=e+t;return n.length>s?n.slice(-s):n};await new Promise(t=>{let n=i(l,{shell:!0,cwd:a(),env:{...o,OPENCLAW_SHELL:`tui-local`}}),r=``,c=``;n.stdout.on(`data`,e=>{r=u(r,e.toString(`utf8`))}),n.stderr.on(`data`,e=>{c=u(c,e.toString(`utf8`))}),n.on(`close`,(n,i)=>{let a=(r+(c?(r?`
`:``)+c:``)).slice(0,s).trimEnd();if(a)for(let t of a.split(`
`))e.chatLog.addSystem(`[local] ${t}`);e.chatLog.addSystem(`[local] exit ${n??`?`}${i?` (signal ${String(i)})`:``}`),e.tui.requestRender(),t()}),n.on(`error`,n=>{e.chatLog.addSystem(`[local] error: ${String(n)}`),e.tui.requestRender(),t()})})}}}function tn(e,t){return{openOverlay:t=>{e.showOverlay(t)},closeOverlay:()=>{if(e.hasOverlay()){e.hideOverlay();return}e.setFocus(t)}}}function nn(e){let{client:t,chatLog:n,tui:r,opts:i,state:a,agentNames:o,initialSessionInput:s,initialSessionAgentId:c,resolveSessionKey:l,updateHeader:u,updateFooter:d,updateAutocompleteProvider:f,setActivityStatus:p,clearLocalRunIds:m}=e,h=Promise.resolve(),y=null,b=e=>{a.agentDefaultId=_(e.defaultId),a.sessionMainKey=v(e.mainKey),a.sessionScope=e.scope??a.sessionScope,a.agents=e.agents.map(e=>({id:_(e.id),name:e.name?.trim()||void 0})),o.clear();for(let e of a.agents)e.name&&o.set(e.id,e.name);if(a.initialSessionApplied)a.agents.some(e=>e.id===a.currentAgentId)||(a.currentAgentId=a.agents[0]?.id??_(e.defaultId??a.currentAgentId));else{c?a.agents.some(e=>e.id===c)&&(a.currentAgentId=c):a.agents.some(e=>e.id===a.currentAgentId)||(a.currentAgentId=a.agents[0]?.id??_(e.defaultId??a.currentAgentId));let t=l(s);t!==a.currentSessionKey&&(a.currentSessionKey=t),a.initialSessionApplied=!0}u(),d()},x=async()=>{try{b(await t.listAgents())}catch(e){n.addSystem(`agents list failed: ${String(e)}`)}},S=e=>{let t=g(e);if(!t)return;let n=_(t.agentId);n!==a.currentAgentId&&(a.currentAgentId=n)},C=e=>{if(e?.modelProvider||e?.model)return{modelProvider:e.modelProvider??a.sessionInfo.modelProvider,model:e.model??a.sessionInfo.model};let t=e?.modelOverride?.trim();return t?{modelProvider:e?.providerOverride?.trim()||a.sessionInfo.modelProvider,model:t}:{modelProvider:a.sessionInfo.modelProvider,model:a.sessionInfo.model}},w=e=>{let t=e.entry??void 0,n=e.defaults??y??void 0,i=y,o=e.defaults?i?.model!==e.defaults.model||i?.modelProvider!==e.defaults.modelProvider||i?.contextTokens!==e.defaults.contextTokens:!1;e.defaults&&(y=e.defaults);let s=t?.updatedAt??null,c=a.sessionInfo.updatedAt??null;if(!e.force&&s!==null&&c!==null&&s<c&&!o)return;let l={...a.sessionInfo};t?.thinkingLevel!==void 0&&(l.thinkingLevel=t.thinkingLevel),t?.verboseLevel!==void 0&&(l.verboseLevel=t.verboseLevel),t?.reasoningLevel!==void 0&&(l.reasoningLevel=t.reasoningLevel),t?.responseUsage!==void 0&&(l.responseUsage=t.responseUsage),t?.inputTokens!==void 0&&(l.inputTokens=t.inputTokens),t?.outputTokens!==void 0&&(l.outputTokens=t.outputTokens),t?.totalTokens!==void 0&&(l.totalTokens=t.totalTokens),(t?.contextTokens!==void 0||n?.contextTokens!==void 0)&&(l.contextTokens=t?.contextTokens??n?.contextTokens??a.sessionInfo.contextTokens),t?.displayName!==void 0&&(l.displayName=t.displayName),t?.updatedAt!==void 0&&(l.updatedAt=t.updatedAt);let u=C(t);u.modelProvider!==void 0&&(l.modelProvider=u.modelProvider),u.model!==void 0&&(l.model=u.model),a.sessionInfo=l,f(),d(),r.requestRender()},ee=async()=>{try{let e=(()=>{if(a.currentSessionKey===`global`||a.currentSessionKey===`unknown`)return;let e=g(a.currentSessionKey);return e?.agentId?_(e.agentId):a.currentAgentId})(),n=await t.listSessions({includeGlobal:!1,includeUnknown:!1,agentId:e}),r=e=>g(e)?.rest??e,i=r(a.currentSessionKey),o=n.sessions.find(e=>e.key===a.currentSessionKey?!0:r(e.key)===i);o?.key&&o.key!==a.currentSessionKey&&(S(o.key),a.currentSessionKey=o.key,u()),w({entry:o,defaults:n.defaults})}catch(e){n.addSystem(`sessions list failed: ${String(e)}`)}},T=async()=>{h=h.then(ee,ee),await h},E=e=>{if(!e?.entry)return;e.key&&e.key!==a.currentSessionKey&&(S(e.key),a.currentSessionKey=e.key,u());let t=e.resolved;w({entry:t&&(t.modelProvider||t.model)?{...e.entry,modelProvider:t.modelProvider??e.entry.modelProvider,model:t.model??e.entry.model}:e.entry,force:!0})},D=async()=>{try{let e=await t.loadHistory({sessionKey:a.currentSessionKey,limit:i.historyLimit??200});a.currentSessionId=typeof e.sessionId==`string`?e.sessionId:null,a.sessionInfo.thinkingLevel=e.thinkingLevel??a.sessionInfo.thinkingLevel,a.sessionInfo.verboseLevel=e.verboseLevel??a.sessionInfo.verboseLevel;let r=(a.sessionInfo.verboseLevel??`off`)!==`off`;n.clearAll(),n.addSystem(`session ${a.currentSessionKey}`);for(let t of e.messages??[]){if(!t||typeof t!=`object`)continue;let e=t;if(bt(e)){let t=yt(e);t&&n.addSystem(t);continue}if(e.role===`user`){let t=yt(e);t&&n.addUser(t);continue}if(e.role===`assistant`){let t=yt(e,{includeThinking:a.showThinking});t&&n.finalizeAssistant(t);continue}if(e.role===`toolResult`){if(!r)continue;let t=Ct(e.toolCallId,``),i=Ct(e.toolName,`tool`);n.startTool(t,i,{}).setResult({content:Array.isArray(e.content)?e.content:[],details:typeof e.details==`object`&&e.details?e.details:void 0},{isError:!!e.isError})}}a.historyLoaded=!0}catch(e){n.addSystem(`history failed: ${String(e)}`)}await T(),r.requestRender()};return{applyAgentsResult:b,refreshAgents:x,refreshSessionInfo:T,applySessionInfoFromPatch:E,loadHistory:D,setSession:async e=>{let t=l(e);S(t),a.currentSessionKey=t,a.activeChatRunId=null,a.currentSessionId=null,a.sessionInfo.updatedAt=null,a.historyLoaded=!1,m?.(),u(),d(),await D()},abortActive:async()=>{if(!a.activeChatRunId){n.addSystem(`no active run`),r.requestRender();return}try{await t.abortChat({sessionKey:a.currentSessionKey,runId:a.activeChatRunId}),p(`aborted`)}catch(e){n.addSystem(`abort failed: ${String(e)}`),p(`abort failed`)}r.requestRender()}}}const rn=[`flibbertigibbeting`,`kerfuffling`,`dillydallying`,`twiddling thumbs`,`noodling`,`bamboozling`,`moseying`,`hobnobbing`,`pondering`,`conjuring`];function an(e,t=rn){return t[Math.floor(e/10)%t.length]??t[0]??`waiting`}function on(e,t,n){let r=t=>e.bold(e.accentSoft(t)),i=n%(t.length+6),a=Math.max(0,i-6),o=Math.min(t.length-1,i),s=``;for(let n=0;n<t.length;n++){let i=t[n];s+=n>=a&&n<=o?r(i):e.dim(i)}return s}function sn(e){let t=an(e.tick,e.phrases);return`${on(e.theme,`${t}…`,e.tick)} • ${e.elapsed} | ${e.connectionStatus}`}function cn(e){return t=>{let n=t,r=n.trim();if(e.editor.setText(``),r){if(n.startsWith(`!`)&&n!==`!`){e.editor.addToHistory(n),e.handleBangLine(n);return}if(e.editor.addToHistory(r),r.startsWith(`/`)){e.handleCommand(r);return}e.sendMessage(r)}}}function ln(e){let t=e?.platform??process.platform,n=e?.env??process.env,r=(n.TERM_PROGRAM??``).toLowerCase();if(t===`darwin`)return!!(r.includes(`iterm`)||r.includes(`apple_terminal`));if(t!==`win32`)return!1;let i=(n.MSYSTEM??``).toUpperCase(),a=n.SHELL??``;return i.startsWith(`MINGW`)||i.startsWith(`MSYS`)||a.toLowerCase().includes(`bash`)?!0:r.includes(`mintty`)}function un(e){let t=Math.max(1,e.burstWindowMs??50),n=e.now??(()=>Date.now()),r=e.setTimer??setTimeout,i=e.clearTimer??clearTimeout,a=null,o=0,s=null,c=()=>{s&&=(i(s),null)},l=()=>{if(a===null)return;let t=a;a=null,o=0,c(),e.submit(t)},u=()=>{c(),s=r(()=>{l()},t)};return r=>{if(!e.enabled){e.submit(r);return}if(r.includes(`
`)){l(),e.submit(r);return}let i=n();if(a===null){a=r,o=i,u();return}if(i-o<=t){a=`${a}\n${r}`,o=i,u();return}l(),a=r,o=i,u()}}function dn(e){let t=(e.raw??``).trim();return t?t===`global`||t===`unknown`?t:t.startsWith(`agent:`)?t.toLowerCase():`agent:${e.currentAgentId}:${t.toLowerCase()}`:e.sessionScope===`global`?`global`:y({agentId:e.currentAgentId,mainKey:e.sessionMainKey})}function fn(e){let t=g((e.initialSessionInput??``).trim());return t?.agentId?_(t.agentId):m(e.cfg,e.cwd??process.cwd())||_(e.fallbackAgentId)}function pn(e){let t=e?.trim()?e.trim():`closed`;return/pairing required/i.test(t)?{connectionStatus:`gateway disconnected: ${t}`,activityStatus:`pairing required: run openclaw devices list`,pairingHint:"Pairing required. Run `openclaw devices list`, approve your request ID, then reconnect."}:{connectionStatus:`gateway disconnected: ${t}`,activityStatus:`idle`}}function mn(e){let t=Math.max(0,Math.floor(e?.dedupeWindowMs??8)),n=e?.now??(()=>Date.now()),r=-1;return e=>{if(!R(e,F.backspace))return e;let i=n();return r>=0&&i-r<=t?``:(r=i,e)}}function hn(e){if(!e||typeof e!=`object`)return!1;let t=e,n=typeof t.code==`string`?t.code:``,r=typeof t.syscall==`string`?t.syscall:``,i=typeof t.message==`string`?t.message:``;return n===`EBADF`&&r===`setRawMode`?!0:/setRawMode/i.test(i)&&/EBADF/i.test(i)}function gn(e){try{e()}catch(e){if(!hn(e))throw e}}function _n(e){let t=Math.max(1,Math.floor(e.exitWindowMs??1e3));return e.hasInput?{action:`clear`,nextLastCtrlCAt:e.now}:e.now-e.lastCtrlCAt<=t?{action:`exit`,nextLastCtrlCAt:e.lastCtrlCAt}:{action:`warn`,nextLastCtrlCAt:e.now}}async function vn(e){let t=u(),n=(e.session??``).trim(),r=t.session?.scope??`per-sender`,i=v(t.session?.mainKey),a=h(t),o=fn({cfg:t,fallbackAgentId:a,initialSessionInput:n,cwd:process.cwd()}),s=[],c=new Map,l=``,d=!1,f=null,p=null,m=!1,y=!1,b=!1,x=!1,S=!1,C=!1,w=new Set,ee=e.deliver??!1,T=e.message?.trim(),E=!1,D={},O=0,k=!1,A=`idle`,j=`connecting`,M=null,te=null,N=null,ne=A,ie={get agentDefaultId(){return a},set agentDefaultId(e){a=e},get sessionMainKey(){return i},set sessionMainKey(e){i=e},get sessionScope(){return r},set sessionScope(e){r=e},get agents(){return s},set agents(e){s=e},get currentAgentId(){return o},set currentAgentId(e){o=e},get currentSessionKey(){return l},set currentSessionKey(e){l=e},get currentSessionId(){return f},set currentSessionId(e){f=e},get activeChatRunId(){return p},set activeChatRunId(e){p=e},get historyLoaded(){return m},set historyLoaded(e){m=e},get sessionInfo(){return D},set sessionInfo(e){D=e},get initialSessionApplied(){return d},set initialSessionApplied(e){d=e},get isConnected(){return y},set isConnected(e){y=e},get autoMessageSent(){return E},set autoMessageSent(e){E=e},get toolsExpanded(){return x},set toolsExpanded(e){x=e},get showThinking(){return S},set showThinking(e){S=e},get connectionStatus(){return j},set connectionStatus(e){j=e},get activityStatus(){return A},set activityStatus(e){A=e},get statusTimeout(){return M},set statusTimeout(e){M=e},get lastCtrlCAt(){return O},set lastCtrlCAt(e){O=e}},ae=e=>{if(e&&(w.add(e),w.size>200)){let[e]=w;e&&w.delete(e)}},F=e=>{w.delete(e)},se=e=>w.has(e),le=()=>{w.clear()},I=await Nt.connect({url:e.url,token:e.token,password:e.password}),L=new ue(new ce),fe=mn();L.addInputListener(e=>{let t=fe(e);return t.length===0?{consume:!0}:{data:t}});let pe=new de(``,1,0),R=new P,me=new de(``,1,0),z=new kt,B=new At(L,Pe),V=new P;V.addChild(pe),V.addChild(z),V.addChild(R),V.addChild(me),V.addChild(B);let he=()=>{B.setAutocompleteProvider(new re(xe({cfg:t,provider:D.modelProvider,model:D.model}),process.cwd()))};L.addChild(V),L.setFocus(B);let ge=e=>e===`global`||e===`unknown`?e:g(e)?.rest??e,_e=e=>{let t=c.get(e);return t?`${e} (${t})`:e},ve=e=>dn({raw:e,sessionScope:r,currentAgentId:o,sessionMainKey:i});l=ve(n);let ye=()=>{let e=ge(l),t=_e(o);pe.setText(X.header(`openclaw tui - ${I.connection.url} - agent ${t} - session ${e}`))},H=new Set([`sending`,`waiting`,`streaming`,`running`]),be=null,U=null,Se=e=>{let t=Math.max(0,Math.floor((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},Ce=()=>{be||(R.clear(),U?.stop(),U=null,be=new de(``,1,0),R.addChild(be))},we=()=>{U||(R.clear(),be=null,U=new oe(L,e=>X.accent(e),e=>X.bold(X.accentSoft(e)),``),R.addChild(U))},Te=0,Ee=null,W=null,De=()=>{if(!U||!N)return;let e=Se(N);if(A===`waiting`){Te++,U.setMessage(sn({theme:X,tick:Te,elapsed:e,connectionStatus:j,phrases:W?[W]:void 0}));return}U.setMessage(`${A} • ${e} | ${j}`)},Oe=()=>{te||=setInterval(()=>{H.has(A)&&De()},1e3)},ke=()=>{te&&=(clearInterval(te),null)},G=()=>{Ee||=(W||=rn[Math.floor(Math.random()*rn.length)]??rn[0]??`waiting`,Te=0,setInterval(()=>{A===`waiting`&&De()},120))},K=()=>{Ee&&(clearInterval(Ee),Ee=null,W=null)},q=()=>{if(H.has(A))(!N||ne!==A)&&(N=Date.now()),we(),A===`waiting`?(ke(),G()):(K(),Oe()),De();else{N=null,ke(),K(),U?.stop(),U=null,Ce();let e=A?`${j} | ${A}`:j;be?.setText(X.dim(e))}ne=A},J=(e,t)=>{j=e,q(),M&&clearTimeout(M),t&&t>0&&(M=setTimeout(()=>{j=y?`connected`:`disconnected`,q()},t))},Y=e=>{A=e,q()},Z=()=>{let e=ge(l),t=D.displayName?`${e} (${D.displayName})`:e,n=_e(o),r=D.model?D.modelProvider?`${D.modelProvider}/${D.model}`:D.model:`unknown`,i=xt(D.totalTokens??null,D.contextTokens??null),a=D.thinkingLevel??`off`,s=D.verboseLevel??`off`,c=D.reasoningLevel??`off`,u=c===`on`?`reasoning`:c===`stream`?`reasoning:stream`:null,d=[`agent ${n}`,`session ${t}`,r,a===`off`?null:`think ${a}`,s===`off`?null:`verbose ${s}`,u,i].filter(Boolean);me.setText(X.dim(d.join(` | `)))},{openOverlay:Ae,closeOverlay:je}=tn(L,B),{refreshAgents:Me,refreshSessionInfo:Ne,applySessionInfoFromPatch:Fe,loadHistory:Ie,setSession:Le,abortActive:Re}=nn({client:I,chatLog:z,tui:L,opts:e,state:ie,agentNames:c,initialSessionInput:n,initialSessionAgentId:(()=>{if(!n)return null;let e=g(n);return e?_(e.agentId):null})(),resolveSessionKey:ve,updateHeader:ye,updateFooter:Z,updateAutocompleteProvider:he,setActivityStatus:Y,clearLocalRunIds:le}),{handleChatEvent:ze,handleAgentEvent:Be}=$t({chatLog:z,tui:L,state:ie,setActivityStatus:Y,refreshSessionInfo:Ne,loadHistory:Ie,isLocalRunId:se,forgetLocalRunId:F,clearLocalRunIds:le}),Q=()=>{k||(k=!0,I.stop(),gn(()=>L.stop()),process.exit(0))},{handleCommand:Ve,sendMessage:He,openModelSelector:Ue,openAgentSelector:We,openSessionSelector:Ge}=Jt({client:I,chatLog:z,tui:L,opts:e,state:ie,deliverDefault:ee,openOverlay:Ae,closeOverlay:je,refreshSessionInfo:Ne,applySessionInfoFromPatch:Fe,loadHistory:Ie,setSession:Le,refreshAgents:Me,abortActive:Re,setActivityStatus:Y,formatSessionKey:ge,noteLocalRunId:ae,forgetLocalRunId:F,requestExit:Q}),{runLocalShellLine:Ke}=en({chatLog:z,tui:L,openOverlay:Ae,closeOverlay:je});he(),B.onSubmit=un({submit:cn({editor:B,handleCommand:Ve,sendMessage:He,handleBangLine:Ke}),enabled:ln()}),B.onEscape=()=>{Re()};let qe=()=>{let e=Date.now(),t=_n({hasInput:B.getText().trim().length>0,now:e,lastCtrlCAt:O});if(O=t.nextLastCtrlCAt,t.action===`clear`){B.setText(``),Y(`cleared input; press ctrl+c again to exit`),L.requestRender();return}if(t.action===`exit`){Q();return}Y(`press ctrl+c again to exit`),L.requestRender()};B.onCtrlC=()=>{qe()},B.onCtrlD=()=>{Q()},B.onCtrlO=()=>{x=!x,z.setToolsExpanded(x),Y(x?`tools expanded`:`tools collapsed`),L.requestRender()},B.onCtrlL=()=>{Ue()},B.onCtrlG=()=>{We()},B.onCtrlP=()=>{Ge()},B.onCtrlT=()=>{S=!S,Ie()},I.onEvent=e=>{e.event===`chat`&&ze(e.payload),e.event===`agent`&&Be(e.payload)},I.onConnected=()=>{y=!0,C=!1;let e=b;b=!1,J(`connected`),(async()=>{await Me(),ye(),await Ie(),J(e?`gateway reconnected`:`gateway connected`,4e3),L.requestRender(),!E&&T&&(E=!0,await He(T)),Z(),L.requestRender()})()},I.onDisconnected=e=>{y=!1,b=!0,m=!1;let t=pn(e);J(t.connectionStatus,5e3),Y(t.activityStatus),t.pairingHint&&!C&&(C=!0,z.addSystem(t.pairingHint)),Z(),L.requestRender()},I.onGap=e=>{J(`event gap: expected ${e.expected}, got ${e.received}`,5e3),L.requestRender()},ye(),J(`connecting`),Z();let Je=()=>{qe()},Ye=()=>{Q()};process.on(`SIGINT`,Je),process.on(`SIGTERM`,Ye),L.start(),I.start(),await new Promise(e=>{process.once(`exit`,()=>{process.removeListener(`SIGINT`,Je),process.removeListener(`SIGTERM`,Ye),e()})})}export{vn as t};
