import{d as e,u as t}from"./subsystem-kTFXkQM5.js";import{E as n,J as r,Mi as i,_ as a,jo as o,ki as s,lr as c,sr as l,ur as u,w as d,y as f}from"./auth-profiles-qXC1L8hs.js";import{c as p,f as m}from"./agent-scope-BKE4M04k.js";import{E as h,c as g,l as ee,r as _}from"./session-key-C7F_iqYg.js";import{a as v}from"./types.secrets-D4tbc3Wq.js";import{t as y}from"./version-q3SkUw2K.js";import{a as b}from"./chat-envelope-Bznn2SoS.js";import{r as x,t as S}from"./tool-display-BTuQQN92.js";import{a as C,i as w}from"./commands-registry-CBl8DDux.js";import{g as T,i as E,o as D,t as O}from"./call-De18doTr.js";import{n as k,t as A}from"./format-relative-DkMjYy7z.js";import{n as j}from"./usage-format-yPwal8Iz.js";import{spawn as M}from"node:child_process";import N from"chalk";import{randomUUID as P}from"node:crypto";import{Box as te,CombinedAutocompleteProvider as ne,Container as F,Editor as re,Input as ie,Key as I,Loader as ae,Markdown as oe,ProcessTerminal as se,SelectList as ce,SettingsList as L,Spacer as R,TUI as le,Text as ue,getEditorKeybindings as de,isKeyRelease as fe,matchesKey as z,truncateToWidth as pe}from"@mariozechner/pi-tui";import{highlight as B,supportsLanguage as V}from"cli-highlight";const H=[`on`,`off`],me=[`on`,`off`],he=[`on`,`off`,`ask`,`full`],ge=[`mention`,`always`],_e=[`off`,`tokens`,`full`],ve={elev:`elevated`};function U(e){return t=>e.filter(e=>e.startsWith(t.toLowerCase())).map(e=>({value:e,label:e}))}function W(e){let t=e.replace(/^\//,``).trim();if(!t)return{name:``,args:``};let[n,...r]=t.split(/\s+/),i=n.toLowerCase();return{name:ve[i]??i,args:r.join(` `).trim()}}function ye(e={}){let t=f(e.provider,e.model),n=U(H),r=U(me),i=U(_e),a=U(he),o=U(ge),s=[{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`}],c=new Set(s.map(e=>e.name)),l=e.cfg?C(e.cfg):w();for(let e of l){let t=e.textAliases.length>0?e.textAliases:[`/${e.key}`];for(let n of t){let t=n.replace(/^\//,``).trim();!t||c.has(t)||(c.add(t),s.push({name:t,description:e.description}))}}return s}function G(e={}){return[`Slash commands:`,`/help`,`/commands`,`/status`,`/agent <id> (or /agents)`,`/session <key> (or /sessions)`,`/model <provider/model> (or /models)`,`/think <${a(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 be(e,t=!1){return t?{keyword:N.hex(`#AF00DB`),built_in:N.hex(`#267F99`),type:N.hex(`#267F99`),literal:N.hex(`#0000FF`),number:N.hex(`#098658`),string:N.hex(`#A31515`),regexp:N.hex(`#811F3F`),symbol:N.hex(`#098658`),class:N.hex(`#267F99`),function:N.hex(`#795E26`),title:N.hex(`#795E26`),params:N.hex(`#001080`),comment:N.hex(`#008000`),doctag:N.hex(`#008000`),meta:N.hex(`#001080`),"meta-keyword":N.hex(`#AF00DB`),"meta-string":N.hex(`#A31515`),section:N.hex(`#795E26`),tag:N.hex(`#800000`),name:N.hex(`#001080`),attr:N.hex(`#C50000`),attribute:N.hex(`#C50000`),variable:N.hex(`#001080`),bullet:N.hex(`#795E26`),code:N.hex(`#A31515`),emphasis:N.italic,strong:N.bold,formula:N.hex(`#AF00DB`),link:N.hex(`#267F99`),quote:N.hex(`#008000`),addition:N.hex(`#098658`),deletion:N.hex(`#A31515`),"selector-tag":N.hex(`#800000`),"selector-id":N.hex(`#800000`),"selector-class":N.hex(`#800000`),"selector-attr":N.hex(`#800000`),"selector-pseudo":N.hex(`#800000`),"template-tag":N.hex(`#AF00DB`),"template-variable":N.hex(`#001080`),default:e}:{keyword:N.hex(`#C586C0`),built_in:N.hex(`#4EC9B0`),type:N.hex(`#4EC9B0`),literal:N.hex(`#569CD6`),number:N.hex(`#B5CEA8`),string:N.hex(`#CE9178`),regexp:N.hex(`#D16969`),symbol:N.hex(`#B5CEA8`),class:N.hex(`#4EC9B0`),function:N.hex(`#DCDCAA`),title:N.hex(`#DCDCAA`),params:N.hex(`#9CDCFE`),comment:N.hex(`#6A9955`),doctag:N.hex(`#608B4E`),meta:N.hex(`#9CDCFE`),"meta-keyword":N.hex(`#C586C0`),"meta-string":N.hex(`#CE9178`),section:N.hex(`#DCDCAA`),tag:N.hex(`#569CD6`),name:N.hex(`#9CDCFE`),attr:N.hex(`#9CDCFE`),attribute:N.hex(`#9CDCFE`),variable:N.hex(`#9CDCFE`),bullet:N.hex(`#D7BA7D`),code:N.hex(`#CE9178`),emphasis:N.italic,strong:N.bold,formula:N.hex(`#C586C0`),link:N.hex(`#4EC9B0`),quote:N.hex(`#6A9955`),addition:N.hex(`#B5CEA8`),deletion:N.hex(`#F44747`),"selector-tag":N.hex(`#D7BA7D`),"selector-id":N.hex(`#D7BA7D`),"selector-class":N.hex(`#D7BA7D`),"selector-attr":N.hex(`#D7BA7D`),"selector-pseudo":N.hex(`#D7BA7D`),"template-tag":N.hex(`#C586C0`),"template-variable":N.hex(`#9CDCFE`),default:e}}const xe=[0,95,135,175,215,255];function Se(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Ce(e,t,n){let r=Se(e),i=Se(t),a=Se(n);return .2126*r+.7152*i+.0722*a}function we(e){return Ce(Number.parseInt(e.slice(1,3),16),Number.parseInt(e.slice(3,5),16),Number.parseInt(e.slice(5,7),16))}function K(e,t){let n=we(t),r=Math.max(e,n),i=Math.min(e,n);return(r+.05)/(i+.05)}function Te(e,t,n){let r=Ce(e,t,n);return K(r,`#1E1E1E`)>=K(r,`#E8E3D5`)}function Ee(){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=xe[e%6],r=xe[Math.floor(e/6)%6],i=xe[Math.floor(e/36)];return Te(i,r,t)}}return!1}const De=Ee(),q=De?{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`},J=e=>t=>N.hex(e)(t),Y=e=>t=>N.bgHex(e)(t),Oe=be(J(q.code),De);function X(e,t){try{return B(e,{language:t&&V(t)?t:void 0,theme:Oe,ignoreIllegals:!0}).split(`
`)}catch{return e.split(`
`).map(e=>J(q.code)(e))}}const Z={fg:J(q.text),assistantText:e=>e,dim:J(q.dim),accent:J(q.accent),accentSoft:J(q.accentSoft),success:J(q.success),error:J(q.error),header:e=>N.bold(J(q.accent)(e)),system:J(q.systemText),userBg:Y(q.userBg),userText:J(q.userText),toolTitle:J(q.toolTitle),toolOutput:J(q.toolOutput),toolPendingBg:Y(q.toolPendingBg),toolSuccessBg:Y(q.toolSuccessBg),toolErrorBg:Y(q.toolErrorBg),border:J(q.border),bold:e=>N.bold(e),italic:e=>N.italic(e)},Q={heading:e=>N.bold(J(q.accent)(e)),link:e=>J(q.link)(e),linkUrl:e=>N.dim(e),code:e=>J(q.code)(e),codeBlock:e=>J(q.code)(e),codeBlockBorder:e=>J(q.codeBorder)(e),quote:e=>J(q.quote)(e),quoteBorder:e=>J(q.quoteBorder)(e),hr:e=>J(q.border)(e),listBullet:e=>J(q.accentSoft)(e),bold:e=>N.bold(e),italic:e=>N.italic(e),strikethrough:e=>N.strikethrough(e),underline:e=>N.underline(e),highlightCode:X},ke={selectedPrefix:e=>J(q.accent)(e),selectedText:e=>N.bold(J(q.accent)(e)),description:e=>J(q.dim)(e),scrollInfo:e=>J(q.dim)(e),noMatch:e=>J(q.dim)(e)},Ae=ke,je={...ke,filterLabel:e=>J(q.dim)(e)},Me={label:(e,t)=>t?N.bold(J(q.accent)(e)):J(q.text)(e),value:(e,t)=>t?J(q.accentSoft)(e):J(q.dim)(e),description:e=>J(q.systemText)(e),cursor:J(q.accent)(`→ `),hint:e=>J(q.dim)(e)},Ne={borderColor:e=>J(q.border)(e),selectList:Ae},Pe={...ke,searchPrompt:e=>J(q.accentSoft)(e),searchInput:e=>J(q.text)(e),matchHighlight:e=>N.bold(J(q.accent)(e))},Fe=`\\x1b\\[[0-9;]*m`,Ie=`\\x1b\\]8;;.*?(?:\\x07|\\x1b\\\\)`,Le=RegExp(`${Fe}|${Ie}`,`g`),Re=RegExp(`^${Fe}`),ze=RegExp(`^${Ie}`);function Be(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(Le,``)}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(Re);if(t){r+=t[0],o+=t[0].length;continue}let n=e.slice(o).match(ze);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 oe(e,t,n,r,i),this.urls=Be(e)}render(e){return We(this.inner.render(e),this.urls)}setText(e){this.inner.setText(e),this.urls=Be(e)}invalidate(){this.inner.invalidate()}},Ke=class extends F{constructor(e){super(),this.body=new Ge(e,1,0,Q,{color:e=>Z.assistantText(e)}),this.addChild(new R(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 i=e.errorMessage??``;return i.trim()?r(i):`(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`?r(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`?b(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=S(x({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 F{constructor(e,t){super(),this.expanded=!1,this.isError=!1,this.isPartial=!0,this.toolName=e,this.args=t,this.box=new te(1,1,e=>Z.toolPendingBg(e)),this.header=new ue(``,0,0),this.argsLine=new ue(``,0,0),this.output=new oe(``,0,0,Q,{color:e=>Z.toolOutput(e)}),this.addChild(new R(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?Z.toolPendingBg:this.isError?Z.toolErrorBg:Z.toolSuccessBg;this.box.setBgFn(t=>e(t));let t=x({name:this.toolName,args:this.args}),n=`${t.emoji} ${t.label}${this.isPartial?` (running)`:``}`;this.header.setText(Z.toolTitle(Z.bold(n)));let r=wt(this.toolName,this.args);this.argsLine.setText(r?Z.dim(r):Z.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 F{constructor(e,t,n){super(),this.body=new oe(e,1,t,Q,n),this.addChild(new R(1)),this.addChild(this.body)}setText(e){this.body.setText(e)}},Ot=class extends Dt{constructor(e){super(e,1,{bgColor:e=>Z.userBg(e),color:e=>Z.userText(e)})}},kt=class extends F{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 R(1)),this.append(new ue(Z.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 re{handleInput(e){if(z(e,I.alt(`enter`))&&this.onAltEnter){this.onAltEnter();return}if(z(e,I.ctrl(`l`))&&this.onCtrlL){this.onCtrlL();return}if(z(e,I.ctrl(`o`))&&this.onCtrlO){this.onCtrlO();return}if(z(e,I.ctrl(`p`))&&this.onCtrlP){this.onCtrlP();return}if(z(e,I.ctrl(`g`))&&this.onCtrlG){this.onCtrlG();return}if(z(e,I.ctrl(`t`))&&this.onCtrlT){this.onCtrlT();return}if(z(e,I.shift(`tab`))&&this.onShiftTab){this.onShiftTab();return}if(z(e,I.escape)&&this.onEscape&&!this.isShowingAutocomplete()){this.onEscape();return}if(z(e,I.ctrl(`c`))&&this.onCtrlC){this.onCtrlC();return}if(z(e,I.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:u.GATEWAY_CLIENT,clientDisplayName:`openclaw-tui`,clientVersion:y,platform:process.platform,mode:c.UI,caps:[l.TOOL_EVENTS],instanceId:P(),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??P();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=o(),n=process.env,r=t.gateway?.auth?.mode,a=t.gateway?.mode===`remote`,c=t.gateway?.remote,l=jt(n.OPENCLAW_GATEWAY_TOKEN),u=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(a){let e=f.token?{value:f.token}:await s({value:c?.token,path:`gateway.remote.token`,env:n,config:t}),r=f.password||u?{value:f.password??u}:await s({value:c?.password,path:`gateway.remote.password`,env:n,config:t}),i=f.token??e.value,a=f.password??u??r.value;return!i&&!a&&Mt(e.unresolvedRefReason??r.unresolvedRefReason??`Missing gateway auth credentials.`),{url:p,token:i,password:a}}if(r===`none`||r===`trusted-proxy`)return{url:p,token:f.token??l,password:f.password??u};try{i(t)}catch(e){Mt(e instanceof Error?e.message:String(e))}let m=t.secrets?.defaults,h=v(t.gateway?.auth?.token,m),g=v(t.gateway?.auth?.password,m);if(r===`password`){let e=f.password||u?{value:f.password??u}:await s({value:t.gateway?.auth?.password,path:`gateway.auth.password`,env:n,config:t}),r=f.password??u??e.value;return r||Mt(e.unresolvedRefReason??`Missing gateway auth password.`),{url:p,token:f.token??l,password:r}}let ee=async()=>{let e=f.token?{value:f.token}:await s({value:t.gateway?.auth?.token,path:`gateway.auth.token`,env:n,config:t}),r=f.token??e.value??l;return r||Mt(e.unresolvedRefReason??`Missing gateway auth token.`),r};if(r===`token`)return{url:p,token:await ee(),password:f.password??u};let _=f.password??u;if(_||g&&!h){let e=_?{value:_}:await s({value:t.gateway?.auth?.password,path:`gateway.auth.password`,env:n,config:t}),r=f.password??e.value??u;return r||Mt(e.unresolvedRefReason??`Missing gateway auth password.`),{url:p,token:f.token??l,password:r}}return{url:p,token:await ee(),password:f.password??u}}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 ie,this.selectList=new ce(this.allItems,t,n)}applyFilter(){let e=this.filterText.toLowerCase();if(!e.trim()){this.selectList=new ce(this.allItems,this.maxVisible,this.theme);return}this.selectList=new ce(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(N.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(z(e,`up`)||z(e,`ctrl+p`)||t&&e===`k`){this.selectList.handleInput(`\x1B[A`);return}if(z(e,`down`)||z(e,`ctrl+n`)||t&&e===`j`){this.selectList.handleInput(`\x1B[B`);return}if(z(e,`enter`)){let e=this.selectList.getSelectedItem();e&&this.onSelect?.(e);return}if(de().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 ie}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=pe(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=pe(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=pe(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(fe(e))return;let t=!this.searchInput.getValue().trim();if(z(e,`up`)||z(e,`ctrl+p`)||t&&e===`k`){this.selectedIndex=Math.max(0,this.selectedIndex-1),this.notifySelectionChange();return}if(z(e,`down`)||z(e,`ctrl+n`)||t&&e===`j`){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+1),this.notifySelectionChange();return}if(z(e,`enter`)){let e=this.filteredItems[this.selectedIndex];e&&this.onSelect&&this.onSelect(e);return}if(de().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,Pe)}function Gt(e,t=7){return new Vt(e,t,je)}function Kt(e,t,n,r=7){return new L(e,r,Me,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:o,state:s,deliverDefault:c,openOverlay:l,closeOverlay:u,refreshSessionInfo:f,loadHistory:p,setSession:m,refreshAgents:h,abortActive:ee,setActivityStatus:_,formatSessionKey:v,applySessionInfoFromPatch:y,noteLocalRunId:b,forgetLocalRunId:x,requestExit:S}=e,C=async e=>{s.currentAgentId=g(e),await m(``)},w=()=>{u(),i.requestRender()},T=(e,t)=>{e.onSelect=e=>{(async()=>{await t(e.value),w()})()},e.onCancel=w,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:s.currentSessionKey,model:e});r.addSystem(`model set to ${e}`),y(n),await f()}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(),s.agents.length===0){r.addSystem(`no agents found`),i.requestRender();return}T(Wt(s.agents.map(e=>({value:e.id,label:e.name?`${e.id} (${e.name})`:e.id,description:e.id===s.agentDefaultId?`default`:``})),9),async e=>{await C(e)})},O=async()=>{try{T(Gt((await t.listSessions({includeGlobal:!1,includeUnknown:!1,includeDerivedTitles:!0,includeLastMessage:!0,agentId:s.currentAgentId})).sessions.map(e=>{let t=e.derivedTitle??e.displayName,n=v(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:s.toolsExpanded?`expanded`:`collapsed`,values:[`collapsed`,`expanded`]},{id:`thinking`,label:`Show thinking`,currentValue:s.showThinking?`on`:`off`,values:[`off`,`on`]}],(e,t)=>{e===`tools`&&(s.toolsExpanded=t===`expanded`,r.setToolsExpanded(s.toolsExpanded)),e===`thinking`&&(s.showThinking=t===`on`,p()),i.requestRender()},()=>{u(),i.requestRender()})),i.requestRender()},j=async e=>{let{name:o,args:c}=W(e);if(o){switch(o){case`help`:r.addSystem(G({provider:s.sessionInfo.modelProvider,model:s.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`:c?await C(c):await D();break;case`agents`:await D();break;case`session`:c?await m(c):await O();break;case`sessions`:await O();break;case`model`:if(!c)await E();else try{let e=await t.patchSession({key:s.currentSessionKey,model:c});r.addSystem(`model set to ${c}`),y(e),await f()}catch(e){r.addSystem(`model set failed: ${String(e)}`)}break;case`models`:await E();break;case`think`:if(!c){let e=a(s.sessionInfo.modelProvider,s.sessionInfo.model,`|`);r.addSystem(`usage: /think <${e}>`);break}try{let e=await t.patchSession({key:s.currentSessionKey,thinkingLevel:c});r.addSystem(`thinking set to ${c}`),y(e),await f()}catch(e){r.addSystem(`think failed: ${String(e)}`)}break;case`verbose`:if(!c){r.addSystem(`usage: /verbose <on|off>`);break}try{let e=await t.patchSession({key:s.currentSessionKey,verboseLevel:c});r.addSystem(`verbose set to ${c}`),y(e),await p()}catch(e){r.addSystem(`verbose failed: ${String(e)}`)}break;case`reasoning`:if(!c){r.addSystem(`usage: /reasoning <on|off>`);break}try{let e=await t.patchSession({key:s.currentSessionKey,reasoningLevel:c});r.addSystem(`reasoning set to ${c}`),y(e),await f()}catch(e){r.addSystem(`reasoning failed: ${String(e)}`)}break;case`usage`:{let e=c?d(c):void 0;if(c&&!e){r.addSystem(`usage: /usage <off|tokens|full>`);break}let i=s.sessionInfo.responseUsage,a=n(i),o=e??(a===`off`?`tokens`:a===`tokens`?`full`:`off`);try{let e=await t.patchSession({key:s.currentSessionKey,responseUsage:o===`off`?null:o});r.addSystem(`usage footer: ${o}`),y(e),await f()}catch(e){r.addSystem(`usage failed: ${String(e)}`)}break}case`elevated`:if(!c){r.addSystem(`usage: /elevated <on|off|ask|full>`);break}if(![`on`,`off`,`ask`,`full`].includes(c)){r.addSystem(`usage: /elevated <on|off|ask|full>`);break}try{let e=await t.patchSession({key:s.currentSessionKey,elevatedLevel:c});r.addSystem(`elevated set to ${c}`),y(e),await f()}catch(e){r.addSystem(`elevated failed: ${String(e)}`)}break;case`activation`:if(!c){r.addSystem(`usage: /activation <mention|always>`);break}try{let e=await t.patchSession({key:s.currentSessionKey,groupActivation:c===`always`?`always`:`mention`});r.addSystem(`activation set to ${c}`),y(e),await f()}catch(e){r.addSystem(`activation failed: ${String(e)}`)}break;case`new`:try{s.sessionInfo.inputTokens=null,s.sessionInfo.outputTokens=null,s.sessionInfo.totalTokens=null,i.requestRender();let e=`tui-${P()}`;await m(e),r.addSystem(`new session: ${e}`)}catch(e){r.addSystem(`new session failed: ${$(String(e))}`)}break;case`reset`:try{s.sessionInfo.inputTokens=null,s.sessionInfo.outputTokens=null,s.sessionInfo.totalTokens=null,i.requestRender(),await t.resetSession(s.currentSessionKey,o),r.addSystem(`session ${s.currentSessionKey} reset`),await p()}catch(e){r.addSystem(`reset failed: ${$(String(e))}`)}break;case`abort`:await ee();break;case`settings`:k();break;case`exit`:case`quit`:S();break;default:await M(e);break}i.requestRender()}},M=async e=>{if(!s.isConnected){r.addSystem(`not connected to gateway — message not sent`),_(`disconnected`),i.requestRender();return}try{r.addUser(e),i.requestRender();let n=P();b(n),s.activeChatRunId=n,_(`sending`),i.requestRender(),await t.sendChat({sessionKey:s.currentSessionKey,message:e,thinking:o.thinking,deliver:c,timeoutMs:o.timeoutMs,runId:n}),_(`waiting`),i.requestRender()}catch(e){s.activeChatRunId&&x?.(s.activeChatRunId),s.activeChatRunId=null,r.addSystem(`send failed: ${String(e)}`),_(`error`),i.requestRender()}};return{handleCommand:j,sendMessage:M,openModelSelector:E,openAgentSelector:D,openSessionSelector:O,openSettings:k,setAgent:C}}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}},g=()=>{r.currentSessionKey!==p&&(p=r.currentSessionKey,u.clear(),d.clear(),f=new Qt,l?.())},ee=e=>{d.set(e,Date.now()),m(d)},_=e=>{u.set(e,Date.now()),d.delete(e),f.drop(e),m(u)},v=e=>{r.activeChatRunId===e&&(r.activeChatRunId=null)},y=e=>{_(e.runId),v(e.runId),e.wasActiveRun&&i(e.status),a?.()},b=e=>{f.drop(e.runId),d.delete(e.runId),v(e.runId),e.wasActiveRun&&i(e.status),a?.()},x=e=>{let t=r.activeChatRunId;return!t||t===e?!1:d.has(t)},S=(e,t)=>{(s?.(e)??!1)&&(c?.(e),!t?.allowLocalWithoutDisplayableFinal)||x(e)||o?.()},C=(e,t)=>{let n=(e??``).trim().toLowerCase(),r=(t??``).trim().toLowerCase();if(!n||!r)return!1;if(n===r)return!0;let i=h(n),a=h(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(g(),C(a.sessionKey,r.currentSessionKey)&&!(u.has(a.runId)&&(a.state===`delta`||a.state===`final`))){if(ee(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){S(a.runId,{allowLocalWithoutDisplayableFinal:!0}),t.dropAssistant(a.runId),y({runId:a.runId,wasActiveRun:e,status:`idle`}),n.requestRender();return}if(bt(a.message)){S(a.runId);let r=yt(a.message);r&&t.addSystem(r),y({runId:a.runId,wasActiveRun:e,status:`idle`}),n.requestRender();return}S(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),y({runId:a.runId,wasActiveRun:e,status:i===`error`?`error`:`idle`})}if(a.state===`aborted`){let e=r.activeChatRunId===a.runId;t.addSystem(`run aborted`),b({runId:a.runId,wasActiveRun:e,status:`aborted`}),S(a.runId)}if(a.state===`error`){let e=r.activeChatRunId===a.runId;t.addSystem(`run error: ${a.errorMessage??`unknown`}`),b({runId:a.runId,wasActiveRun:e,status:`error`}),S(a.runId)}n.requestRender()}},handleAgentEvent:e=>{if(!e||typeof e!=`object`)return;let a=e;g();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??M,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,_=Promise.resolve(),v=null,y=e=>{a.agentDefaultId=g(e.defaultId),a.sessionMainKey=ee(e.mainKey),a.sessionScope=e.scope??a.sessionScope,a.agents=e.agents.map(e=>({id:g(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??g(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??g(e.defaultId??a.currentAgentId));let t=l(s);t!==a.currentSessionKey&&(a.currentSessionKey=t),a.initialSessionApplied=!0}u(),d()},b=async()=>{try{y(await t.listAgents())}catch(e){n.addSystem(`agents list failed: ${String(e)}`)}},x=e=>{let t=h(e);if(!t)return;let n=g(t.agentId);n!==a.currentAgentId&&(a.currentAgentId=n)},S=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}},C=e=>{let t=e.entry??void 0,n=e.defaults??v??void 0,i=v,o=e.defaults?i?.model!==e.defaults.model||i?.modelProvider!==e.defaults.modelProvider||i?.contextTokens!==e.defaults.contextTokens:!1;e.defaults&&(v=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=S(t);u.modelProvider!==void 0&&(l.modelProvider=u.modelProvider),u.model!==void 0&&(l.model=u.model),a.sessionInfo=l,f(),d(),r.requestRender()},w=async()=>{try{let e=(()=>{if(a.currentSessionKey===`global`||a.currentSessionKey===`unknown`)return;let e=h(a.currentSessionKey);return e?.agentId?g(e.agentId):a.currentAgentId})(),n=await t.listSessions({includeGlobal:!1,includeUnknown:!1,agentId:e}),r=e=>h(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&&(x(o.key),a.currentSessionKey=o.key,u()),C({entry:o,defaults:n.defaults})}catch(e){n.addSystem(`sessions list failed: ${String(e)}`)}},T=async()=>{_=_.then(w,w),await _},E=e=>{if(!e?.entry)return;e.key&&e.key!==a.currentSessionKey&&(x(e.key),a.currentSessionKey=e.key,u());let t=e.resolved;C({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:y,refreshAgents:b,refreshSessionInfo:T,applySessionInfoFromPatch:E,loadHistory:D,setSession:async e=>{let t=l(e);x(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`:_({agentId:e.currentAgentId,mainKey:e.sessionMainKey})}function fn(e){let t=h((e.initialSessionInput??``).trim());return t?.agentId?g(t.agentId):p(e.cfg,e.cwd??process.cwd())||g(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(!z(e,I.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=o(),n=(e.session??``).trim(),r=t.session?.scope??`per-sender`,i=ee(t.session?.mainKey),a=m(t),s=fn({cfg:t,fallbackAgentId:a,initialSessionInput:n,cwd:process.cwd()}),c=[],l=new Map,u=``,d=!1,f=null,p=null,_=!1,v=!1,y=!1,b=!1,x=!1,S=!1,C=new Set,w=e.deliver??!1,T=e.message?.trim(),E=!1,D={},O=0,k=!1,A=`idle`,j=`connecting`,M=null,N=null,P=null,te=A,re={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 c},set agents(e){c=e},get currentAgentId(){return s},set currentAgentId(e){s=e},get currentSessionKey(){return u},set currentSessionKey(e){u=e},get currentSessionId(){return f},set currentSessionId(e){f=e},get activeChatRunId(){return p},set activeChatRunId(e){p=e},get historyLoaded(){return _},set historyLoaded(e){_=e},get sessionInfo(){return D},set sessionInfo(e){D=e},get initialSessionApplied(){return d},set initialSessionApplied(e){d=e},get isConnected(){return v},set isConnected(e){v=e},get autoMessageSent(){return E},set autoMessageSent(e){E=e},get toolsExpanded(){return b},set toolsExpanded(e){b=e},get showThinking(){return x},set showThinking(e){x=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}},ie=e=>{if(e&&(C.add(e),C.size>200)){let[e]=C;e&&C.delete(e)}},I=e=>{C.delete(e)},oe=e=>C.has(e),ce=()=>{C.clear()},L=await Nt.connect({url:e.url,token:e.token,password:e.password}),R=new le(new se),de=mn();R.addInputListener(e=>{let t=de(e);return t.length===0?{consume:!0}:{data:t}});let fe=new ue(``,1,0),z=new F,pe=new ue(``,1,0),B=new kt,V=new At(R,Ne),H=new F;H.addChild(fe),H.addChild(B),H.addChild(z),H.addChild(pe),H.addChild(V);let me=()=>{V.setAutocompleteProvider(new ne(ye({cfg:t,provider:D.modelProvider,model:D.model}),process.cwd()))};R.addChild(H),R.setFocus(V);let he=e=>e===`global`||e===`unknown`?e:h(e)?.rest??e,ge=e=>{let t=l.get(e);return t?`${e} (${t})`:e},_e=e=>dn({raw:e,sessionScope:r,currentAgentId:s,sessionMainKey:i});u=_e(n);let ve=()=>{let e=he(u),t=ge(s);fe.setText(Z.header(`openclaw tui - ${L.connection.url} - agent ${t} - session ${e}`))},U=new Set([`sending`,`waiting`,`streaming`,`running`]),W=null,G=null,be=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`},xe=()=>{W||(z.clear(),G?.stop(),G=null,W=new ue(``,1,0),z.addChild(W))},Se=()=>{G||(z.clear(),W=null,G=new ae(R,e=>Z.accent(e),e=>Z.bold(Z.accentSoft(e)),``),z.addChild(G))},Ce=0,we=null,K=null,Te=()=>{if(!G||!P)return;let e=be(P);if(A===`waiting`){Ce++,G.setMessage(sn({theme:Z,tick:Ce,elapsed:e,connectionStatus:j,phrases:K?[K]:void 0}));return}G.setMessage(`${A} • ${e} | ${j}`)},Ee=()=>{N||=setInterval(()=>{U.has(A)&&Te()},1e3)},De=()=>{N&&=(clearInterval(N),null)},q=()=>{we||=(K||=rn[Math.floor(Math.random()*rn.length)]??rn[0]??`waiting`,Ce=0,setInterval(()=>{A===`waiting`&&Te()},120))},J=()=>{we&&(clearInterval(we),we=null,K=null)},Y=()=>{if(U.has(A))(!P||te!==A)&&(P=Date.now()),Se(),A===`waiting`?(De(),q()):(J(),Ee()),Te();else{P=null,De(),J(),G?.stop(),G=null,xe();let e=A?`${j} | ${A}`:j;W?.setText(Z.dim(e))}te=A},Oe=(e,t)=>{j=e,Y(),M&&clearTimeout(M),t&&t>0&&(M=setTimeout(()=>{j=v?`connected`:`disconnected`,Y()},t))},X=e=>{A=e,Y()},Q=()=>{let e=he(u),t=D.displayName?`${e} (${D.displayName})`:e,n=ge(s),r=D.model?D.modelProvider?`${D.modelProvider}/${D.model}`:D.model:`unknown`,i=xt(D.totalTokens??null,D.contextTokens??null),a=D.thinkingLevel??`off`,o=D.verboseLevel??`off`,c=D.reasoningLevel??`off`,l=c===`on`?`reasoning`:c===`stream`?`reasoning:stream`:null,d=[`agent ${n}`,`session ${t}`,r,a===`off`?null:`think ${a}`,o===`off`?null:`verbose ${o}`,l,i].filter(Boolean);pe.setText(Z.dim(d.join(` | `)))},{openOverlay:ke,closeOverlay:Ae}=tn(R,V),{refreshAgents:je,refreshSessionInfo:Me,applySessionInfoFromPatch:Pe,loadHistory:Fe,setSession:Ie,abortActive:Le}=nn({client:L,chatLog:B,tui:R,opts:e,state:re,agentNames:l,initialSessionInput:n,initialSessionAgentId:(()=>{if(!n)return null;let e=h(n);return e?g(e.agentId):null})(),resolveSessionKey:_e,updateHeader:ve,updateFooter:Q,updateAutocompleteProvider:me,setActivityStatus:X,clearLocalRunIds:ce}),{handleChatEvent:Re,handleAgentEvent:ze}=$t({chatLog:B,tui:R,state:re,setActivityStatus:X,refreshSessionInfo:Me,loadHistory:Fe,isLocalRunId:oe,forgetLocalRunId:I,clearLocalRunIds:ce}),Be=()=>{k||(k=!0,L.stop(),gn(()=>R.stop()),process.exit(0))},{handleCommand:Ve,sendMessage:He,openModelSelector:Ue,openAgentSelector:We,openSessionSelector:Ge}=Jt({client:L,chatLog:B,tui:R,opts:e,state:re,deliverDefault:w,openOverlay:ke,closeOverlay:Ae,refreshSessionInfo:Me,applySessionInfoFromPatch:Pe,loadHistory:Fe,setSession:Ie,refreshAgents:je,abortActive:Le,setActivityStatus:X,formatSessionKey:he,noteLocalRunId:ie,forgetLocalRunId:I,requestExit:Be}),{runLocalShellLine:Ke}=en({chatLog:B,tui:R,openOverlay:ke,closeOverlay:Ae});me(),V.onSubmit=un({submit:cn({editor:V,handleCommand:Ve,sendMessage:He,handleBangLine:Ke}),enabled:ln()}),V.onEscape=()=>{Le()};let qe=()=>{let e=Date.now(),t=_n({hasInput:V.getText().trim().length>0,now:e,lastCtrlCAt:O});if(O=t.nextLastCtrlCAt,t.action===`clear`){V.setText(``),X(`cleared input; press ctrl+c again to exit`),R.requestRender();return}if(t.action===`exit`){Be();return}X(`press ctrl+c again to exit`),R.requestRender()};V.onCtrlC=()=>{qe()},V.onCtrlD=()=>{Be()},V.onCtrlO=()=>{b=!b,B.setToolsExpanded(b),X(b?`tools expanded`:`tools collapsed`),R.requestRender()},V.onCtrlL=()=>{Ue()},V.onCtrlG=()=>{We()},V.onCtrlP=()=>{Ge()},V.onCtrlT=()=>{x=!x,Fe()},L.onEvent=e=>{e.event===`chat`&&Re(e.payload),e.event===`agent`&&ze(e.payload)},L.onConnected=()=>{v=!0,S=!1;let e=y;y=!1,Oe(`connected`),(async()=>{await je(),ve(),await Fe(),Oe(e?`gateway reconnected`:`gateway connected`,4e3),R.requestRender(),!E&&T&&(E=!0,await He(T)),Q(),R.requestRender()})()},L.onDisconnected=e=>{v=!1,y=!0,_=!1;let t=pn(e);Oe(t.connectionStatus,5e3),X(t.activityStatus),t.pairingHint&&!S&&(S=!0,B.addSystem(t.pairingHint)),Q(),R.requestRender()},L.onGap=e=>{Oe(`event gap: expected ${e.expected}, got ${e.received}`,5e3),R.requestRender()},ve(),Oe(`connecting`),Q();let Je=()=>{qe()},Ye=()=>{Be()};process.on(`SIGINT`,Je),process.on(`SIGTERM`,Ye),R.start(),L.start(),await new Promise(e=>{process.once(`exit`,()=>{process.removeListener(`SIGINT`,Je),process.removeListener(`SIGTERM`,Ye),e()})})}export{vn as t};
